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
from PIL import Image, ImageDraw, ImageFont
import datetime
from server import settings

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)
        elif cert_template == 3:
            cer_path = make_img(candidate.consumer_name, str(candidate.start_date.year), str(candidate.start_date.month), str(candidate.end_date.year), str(candidate.end_date.month), str(candidate.end_date.day), candidate.number, header_path=candidate.photo, mode=True)
            candidate.path = cer_path
            candidate.number='HNHK'+  str(now.year) + str(now.month).zfill(2) + str(count+1).zfill(4)
        elif cert_template == 4:
            cer_path = make_img(candidate.consumer_name, str(candidate.start_date.year), str(candidate.start_date.month), str(candidate.end_date.year), str(candidate.end_date.month), str(candidate.end_date.day), candidate.number, header_path=candidate.photo, mode=False)
            candidate.path = cer_path
            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}


def make_img(name:str, year:str, month:str, expiry_year:str, expiry_month:str, expiry_day:str, certificate_number:str, header_path=None, mode=None):
    now = datetime.datetime.now()
    font_path = settings.BASE_DIR + "/media/cert/template/STKAITI.TTF"
    if mode:
        demo_image_path = settings.BASE_DIR + "/media/cert/template/assess.png"
        # demo_image_path = r"C:\code\cma_search\server\media\test.png"
        img = Image.open(demo_image_path)
        if img.mode == 'RGBA':
            img = img.convert('RGB')
        # Initialize ImageDraw
        draw = ImageDraw.Draw(img)

        # Set font paths and sizes
        # font_path = r"C:/code/cma_search/server/media/font/SIMLI.TTF"  # Update this to the correct font path
        font_name = ImageFont.truetype(font_path, 20)  # Font size for the name
        font_text = ImageFont.truetype(font_path, 20)  # Font size for the other text
        font_number = ImageFont.truetype(font_path, 15)  # Font size for the other text

        # uoload header image
        # header_path = "C:\code\cma_search\server\media\OIP.jpg"
        if header_path:
            header_img = Image.open(header_path)
            # 指定粘贴的位置
            header_position = (210, 235)  # 粘贴图像的左上角位置
            header_img = header_img.resize((140, 150))
            img.paste(header_img, header_position)
        if len(name) <= 3:
            position_name = (105, 395)
        else:
            position_name = (100, 395)
        position_year = (220, 395)
        position_month = (280, 395)

        position_exp_day = (310, 490)
        position_exp_month = (270, 490)
        position_exp_year = (210, 490)
        position_cert_number = (180, 530)

        # Define colors
        color = (0, 0, 0)  # Black color

        # Draw the text on the image
        draw.text(position_name, name, fill=color, font=font_name)
        draw.text(position_year, year, fill=color, font=font_text)
        draw.text(position_month, month, fill=color, font=font_text)

        draw.text(position_exp_year, expiry_year, fill=color, font=font_text)
        draw.text(position_exp_month, expiry_month, fill=color, font=font_text)
        draw.text(position_exp_day, expiry_day, fill=color, font=font_text)

        draw.text(position_cert_number, certificate_number, fill=color, font=font_number)
        # Save the edited image
        output_path = f"/media/cert/template/certificate/{now}.jpg"# Update this to the desired output path
        img.save(settings.BASE_DIR + output_path, format='JPEG')
    else:
        demo_image_path = settings.BASE_DIR + "/media/cert/template/inspect.jpg"
        # font_path = r"C:/code/cma_search/server/media/font/SIMLI.TTF"  # Update this to the correct font path
        img = Image.open(demo_image_path)
        if img.mode == 'RGBA':
            img = img.convert('RGB')
        # Initialize ImageDraw
        draw = ImageDraw.Draw(img)
        # Set font paths and sizes
        font_name = ImageFont.truetype(font_path, 20)  # Font size for the name
        font_text = ImageFont.truetype(font_path, 20)  # Font size for the other text
        font_number = ImageFont.truetype(font_path, 15)  # Font size for the other text

        # uoload header image
        if header_path:
            header_img = Image.open(header_path)
            # 指定粘贴的位置
            header_position = (240, 250)  # 粘贴图像的左上角位置
            header_img = header_img.resize((120, 150))
            img.paste(header_img, header_position)

        # Define text positions (X, Y) based on your image
        if len(name) <= 3:
            position_name = (130, 430)
        else:
            position_name = (140, 430)
        position_year = (245, 430)
        position_month = (308, 430)

        position_exp_day = (430, 525)
        position_exp_month = (390, 525)
        position_exp_year = (330, 525)
        position_cert_number = (200, 565)

        # Define colors
        color = (0, 0, 0)  # Black color

        # Draw the text on the image
        draw.text(position_name, name, fill=color, font=font_name)
        draw.text(position_year, year, fill=color, font=font_text)
        draw.text(position_month, month, fill=color, font=font_text)

        draw.text(position_exp_year, expiry_year, fill=color, font=font_text)
        draw.text(position_exp_month, expiry_month, fill=color, font=font_text)
        draw.text(position_exp_day, expiry_day, fill=color, font=font_text)

        draw.text(position_cert_number, certificate_number, fill=color, font=font_number)
        # Save the edited image
        output_path = f"/media/cert/template/certificate/{now}.jpg"# Update this to the desired output path  # Update this to the desired output path
        img.save(settings.BASE_DIR + output_path, format='JPEG')
    return output_path