from utils import model
from django.contrib.postgres.fields import JSONField
from django.db import models
from rest_framework.exceptions import ParseError
from simple_history.models import HistoricalRecords

from apps.certset.models import ImplementRule, UnitType, Evaluations, Standard
from apps.crm.models import Enterprise
from apps.system.models import CommonAModel, CommonBModel, Dict, User
# from apps.plan.models import Plan

# Create your models here.

class Project(CommonBModel):
    """
    认证项目
    """
    status_choices = (
        ('创建中', '创建中'),
        ('待策划', '待策划'),
        ('策划中', '策划中'),
        ('审核任务已下达', '审核任务已下达'),
        ('审核任务已接受', '审核任务已接受'),
        ('待现场审核', '待现场审核'),
        ('现场审核中', '现场审核中'),
        ('任务已反馈', '任务已反馈')
    )
    status = models.CharField('项目状态', choices=status_choices, default='创建中', max_length=50)
    number = models.CharField('项目编号', max_length = 100, null=True, blank=True)
    auditee = models.ForeignKey(Enterprise, related_name='project_auditee', on_delete=models.DO_NOTHING, verbose_name='受审核方')
    auditee_v = JSONField(verbose_name='受审核方', default=dict)
    remark = models.TextField('备注', null=True, blank=True)
    can_paichai = models.BooleanField('是否可派差', default = False)
    plan = models.ForeignKey('plan.Plan', verbose_name='所属计划', on_delete=models.SET_NULL, null=True, blank=True)
    assgin_date = models.DateTimeField('任务下达时间', null=True, blank=True)
    assgin_by = models.ForeignKey(User, on_delete=models.SET_NULL, verbose_name='审核任务下达人', null=True, blank=True)
    edate0 = models.DateTimeField('预计审核开始时间', null=True, blank=True)
    edate1 = models.DateTimeField('预计审核结束时间', null=True, blank=True)
    

    class Meta:
        verbose_name = '认证项目'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.number


class CertApp(CommonBModel):
    """
    认证受理
    """
    status_choices = (
        ('草稿', '草稿'),
        ('已申请', '已申请'),
        ('已受理', '已受理'),
        ('进行中', '进行中'),
        ('已中止', '已中止'),
        ('已完成', '已完成')
    )
    result_choices = (
        ('未评审', '未评审'),
        ('合格', '合格'),
        ('不合格', '不合格'),
        ('有条件放行', '有条件放行')
    )
    number = models.CharField('受理编号', max_length = 100, null=True, blank=True)
    apply_date = models.DateField('申请日期', null=True, blank=True)
    accept_date = models.DateField('受理日期', null=True, blank=True)
    accept_by = models.ForeignKey(User, verbose_name='受理人', on_delete=models.SET_NULL, null=True, blank=True)
    applicant_v = JSONField(verbose_name='申请方')
    applicant = models.ForeignKey(Enterprise, related_name='certapp_applicant', on_delete=models.DO_NOTHING)
    
    status = models.CharField('申请状态', choices=status_choices, default='草稿', max_length=50)
    evresult = models.CharField('评审结论', choices = result_choices, default='未评审', max_length=50)
    evremark = models.TextField('备注', blank=True)
    level = models.ForeignKey(Dict, verbose_name='业务级别', related_name='certapp_level', on_delete=models.DO_NOTHING, default=Dict.objects.get(code='ybxm').id)
    pattern_choices = (
        ('正常', '正常'),
        ('ODM', 'ODM'),
        ('OEM', 'OEM')
    )
    risk_choices = (
        ('高', '高'),
        ('中', '中'),
        ('低', '低')
    )
    cert_field = models.ForeignKey(Dict, verbose_name='认证领域', related_name='certapp_cert_field', on_delete=models.DO_NOTHING)
    cccpv_class = models.ForeignKey(Dict, verbose_name='涉及CCC/PV分类', related_name='certapp_cccpv_class', on_delete=models.DO_NOTHING, null=True, blank=True)
    cnas_scopes = models.ManyToManyField(Dict, verbose_name='涉及cnas分类', related_name='certapp_cnas_sopes', blank=True)
    project = models.ForeignKey(Project, related_name='certapp_project', on_delete=models.SET_NULL, null=True)
    is_approve = models.BooleanField('是否认可', default=True)
    pattern = models.CharField('申请模式', choices=pattern_choices, max_length=50, null=True, blank=True)
    manufacture = models.ForeignKey(Enterprise, on_delete=models.CASCADE, related_name='certapp_manufacture', null=True, blank=True)
    manufacture_v = JSONField(verbose_name='制造商', null=True)
    factory = models.ForeignKey(Enterprise, on_delete=models.CASCADE, related_name='certapp_factory', null=True, blank=True)
    factory_v = JSONField(verbose_name='生产厂', null=True)
    scope = models.TextField('认证范围', null=True, blank=True)
    system_people = models.FloatField('体系相关员工数',null=True, blank=True, default=0)
    initial_people = models.FloatField('初始人日数',null=True, blank=True, default=0)
    supervision_people = models.FloatField('监督人日数',null=True, blank=True, default=0)
    Initial_certification = models.FloatField('初次认证费',null=True, blank=True, default=0)
    annuity = models.FloatField('年金',null=True, blank=True, default=0)
    supervise_amount = models.FloatField('监督金额',null=True, blank=True, default=0) 
    review_amount = models.FloatField('复评金额',null=True, blank=True, default=0)  
    system_standard = models.ForeignKey(Dict, verbose_name='依据的体系标准',null=True, blank=True, related_name='certapp_system_standard', on_delete=models.DO_NOTHING)
    professional_code = models.ManyToManyField(Dict, verbose_name='专业代码', related_name='certapp_professional_code')
    certification = models.CharField('认证范围', max_length = 1000, null=True, blank=True)
    risk = models.CharField('风险系数', choices=risk_choices, max_length=50, null=True, blank=True)
    class Meta:
        verbose_name = '认证受理'
        verbose_name_plural = verbose_name

class Application(CommonBModel):
    """
    主申请
    """
    status_choices = (
        ('草稿', '草稿'),
        ('已申请', '已申请'),
        ('已受理', '已受理'),
        ('进行中', '进行中'),
        ('已中止', '已中止'),
        ('已完成', '已完成')
    )
    result_choices = (
        ('未评审', '未评审'),
        ('合格', '合格'),
        ('不合格', '不合格'),
        ('有条件放行', '有条件放行')
    )
    stage_choices = (
        (0, '基本信息'),
        (1, '申请内容')
    )
    number = models.CharField('申请编号', max_length = 100)
    apply_date = models.DateField('申请日期', null=True, blank=True)
    accept_date = models.DateField('受理日期', null=True, blank=True)

    applicant_v = JSONField(verbose_name='申请方')
    applicant = models.ForeignKey(Enterprise, related_name='application_applicant', on_delete=models.DO_NOTHING)
    fields = models.TextField('认证领域', blank=True)
    status = models.CharField('申请状态', choices=status_choices, default='草稿', max_length=50)
    stage = models.IntegerField('步骤状态', choices=stage_choices, default=0)
    evresult = models.CharField('评审结论', choices = result_choices, default='未评审', max_length=50)
    evremark = models.TextField('备注', blank=True)
    level = models.ForeignKey(Dict, related_name='application_level', on_delete = models.DO_NOTHING)

    class Meta:
        verbose_name = '认证主申请'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.number

class SubApplication(CommonBModel):
    """
    子申请
    """
    pattern_choices = (
        ('正常', '正常'),
        ('ODM', 'ODM'),
        ('OEM', 'OEM')
    )
    number = models.CharField('子申请编号', max_length = 100)
    application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='subapplication_application')
    cert_field = models.ForeignKey(Dict, verbose_name='认证领域', related_name='subapplication_cert_field', on_delete=models.DO_NOTHING)
    cccpv_class = models.ForeignKey(Dict, verbose_name='涉及CCC/PV分类', related_name='subapplication_cccpv_class', on_delete=models.DO_NOTHING, null=True, blank=True)
    cnas_scopes = models.ManyToManyField(Dict, verbose_name='涉及cnas分类', related_name='subapplication_cnas_sopes', blank=True)
    project = models.ForeignKey(Project, related_name='subapplication_project', on_delete=models.SET_NULL, null=True)
    is_approve = models.BooleanField('是否认可', default=True)
    pattern = models.CharField('申请模式', choices=pattern_choices, max_length=50, null=True, blank=True)
    manufacture = models.ForeignKey(Enterprise, on_delete=models.CASCADE, related_name='subapplication_manufacture', null=True, blank=True)
    manufacture_v = JSONField(verbose_name='制造商', null=True)
    factory = models.ForeignKey(Enterprise, on_delete=models.CASCADE, related_name='subapplication_factory', null=True, blank=True)
    factory_v = JSONField(verbose_name='生产厂', null=True)

    class Meta:
        verbose_name = '认证子申请'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.number

class EvaluationDetail(CommonBModel):
    result_choices = (
        ('符合', '符合'),
        ('不符合', '不符合'),
        ('不适用', '不适用'),
        ('需说明', '需说明'),
    )
    cert_app = models.ManyToManyField(CertApp,  verbose_name='关联受理',  related_name='evaluationdetail_cert_app')
    item = models.ForeignKey(Evaluations,on_delete=models.DO_NOTHING,verbose_name='评审项',null=True, blank=True, related_name='evaluationdetail_item')
    item_v = JSONField(verbose_name='评审项目',null=True, blank=True)
    remark = models.TextField('备注', null=True, blank=True)

    class Meta:
        verbose_name = '评审记录详情'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

class Unit(CommonBModel):
    """
    认证单元,一个单元一张证书
    """
    name = models.CharField('单元名称', max_length=200)
    description = models.TextField('单元描述', blank=True)
    implementrule = models.ForeignKey(ImplementRule, verbose_name='采用规则', on_delete=models.DO_NOTHING)
    unittype = models.ForeignKey(UnitType, verbose_name='单元类型', on_delete = models.DO_NOTHING)
    standard = models.ForeignKey(Standard, verbose_name='采用标准', on_delete = models.DO_NOTHING)
    certapp = models.ForeignKey(CertApp, verbose_name='所属业务', on_delete = models.CASCADE)

    class Meta:
        verbose_name = '认证单元'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        obj = self.certapp
        objs = Unit.objects.filter(certapp=obj, is_deleted=False).values_list('name', flat=True)
        obj.scope = obj.factory_v['address'] + ':' + ';'.join(objs)
        obj.save()

