from .models import ExamTest
from crm.models import Candidate
from django.utils import timezone
from datetime import timedelta
from rest_framework.exceptions import ParseError
from rbac.models import UserProfile
def issue(obj: ExamTest, create_admin: UserProfile = None):
    if create_admin is None:
        create_admin = obj.exam.create_admin
    workscope = obj.workscope
    candidate = obj.candidate if hasattr(obj, 'candidate') else None
    if obj.is_pass and candidate is None:
        candidates = Candidate.objects.filter(consumer=obj.consumer, workscope=workscope, number__isnull=True)
        if candidates.exists():
            candidate = candidates[0]
        else:
            candidate = Candidate.objects.create(consumer=obj.consumer, workscope=workscope)
        candidate.examtest = obj
        now = timezone.now()
        candidate.issue_date = now
        candidate.start_date = now
        candidate.end_date = now + timedelta(days=workscope.issue_year*365) # 有效期
        candidate.examtest_date = obj.start_time.date()
        candidate.workscope_name = workscope.name
        candidate.consumer_name = obj.consumer_detail['name']
        candidate.ID_number = obj.consumer_detail['ID_number']
        candidate.company_name = obj.consumer_detail['company_name']
        candidate.deptname = obj.consumer_detail['deptname']
        candidate.train_name = obj.exam.train_name
        candidate.train_start_date = obj.exam.train_start_date
        candidate.train_end_date = obj.exam.train_end_date
        candidate.save()
        cert_template = obj.exam.cert_template
        # if cert_template == 2 or (cert_template is None and workscope.name in ['放射工作人员(上岗)', '放射工作人员(在岗)']):  # 如果是放射工作人员处理方式
        if cert_template == 2:
            count = Candidate.objects.filter(create_admin=create_admin, issue_date__year=now.year, issue_date__month=now.month).count()
            candidate.number='HNHK'+  str(now.year) + str(now.month).zfill(2) + str(count+1).zfill(4)
        else:
            candidate.number='SL'+  str(now.year)[-2:] + str(candidate.pk).zfill(6)
        candidate.create_admin = create_admin
        candidate.save()
        return {"id":candidate.pk, "number":candidate.number, "path":None}