from django.db import models
from apps.utils.models import CommonBModel, CommonADModel, CommonBDModel
from apps.system.models import User

# Create your models here.


etype_choices = ((10, "生产设备"), (20, "计量设备"), (30, "治理设备"), (40, "监测设备"), (50, "监控设备"))


class Ecate(CommonADModel):
    """TN:设备类别"""
    name = models.CharField("名称", max_length=50, unique=True)
    code = models.CharField("编码", max_length=50, unique=True, null=True, blank=True)
    type = models.PositiveSmallIntegerField("类型", choices=etype_choices, help_text=str(etype_choices))
    is_for_safe = models.BooleanField("是否用于安全", default=False)
    is_for_enp = models.BooleanField("是否用于环保", default=False)
    is_car = models.BooleanField("是否为车辆", default=False)

    def __str__(self):
        return f"{self.name}|{self.code}"


class Equipment(CommonBModel):
    """
    TN:设备台账信息,其中belong_dept是责任部门
    """
    RUNING = 10
    STANDBY = 20
    STOP = 30
    FAILURE = 40
    OFFLINE = 50


    EQUIP_STATE_OK = 10
    EQUIP_STATE_LIMIT = 20
    EQUIP_STATE_FIX = 30
    EQUIP_STATE_DISABLE = 40
    EQUIP_STATE_SCRAP = 50
    state_choices = ((EQUIP_STATE_OK, "完好"), (EQUIP_STATE_LIMIT, "限用"), (EQUIP_STATE_FIX, "在修"), (EQUIP_STATE_DISABLE, "禁用"), (EQUIP_STATE_SCRAP, "报废"))
    EQUIP_TYPE_PRO = 10
    EQUIP_TYPE_MEA = 20
    EQ_NORMAL = 10
    EQ_WARNING = 20
    EQ_EXPIRED = 30
    EQ_WAIT = 40
    measure_state_choices = ((EQ_NORMAL, "正常"), (EQ_WARNING, "告警"), (EQ_EXPIRED, "过期"), (EQ_WAIT, "等待"))
    # mgmtype_choices = (
    #      (1, 'A'),
    #      (2, 'B'),
    #      (3, 'C')
    # )
    # way_choices = (
    #      (1, '外检'),
    #      (2, '自检'),

    # )
    # usetype_choices = (
    #      (1, '专用'),
    #      (2, '公用'),
    # )
    IM_DANDAN = 10
    IM_DANDOU = 20
    IM_DOUDAN = 30

    IM_CHOICES = (
        (10, '单开为开/单停为停'),
        (20, '单开为开/都停为停'),
        (30, '都开为开/单停为停')
    )

    running_state = models.PositiveSmallIntegerField("运行状态", default=50)
    ip = models.GenericIPAddressField("IP地址", null=True, blank=True)
    port = models.PositiveSmallIntegerField("端口号", null=True, blank=True)
    login_name = models.CharField("登录名", max_length=100, null=True, blank=True)
    login_pwd = models.CharField("登录密码", max_length=100, null=True, blank=True)
    mgroup = models.ForeignKey("mtm.mgroup", on_delete=models.SET_NULL, null=True, blank=True, related_name="equip_mgroup")
    indicate_mgroup_running = models.PositiveSmallIntegerField("表明工段运行的方式", choices=IM_CHOICES, null=True, blank=True)
    type = models.PositiveSmallIntegerField("类型", choices=etype_choices, default=10)
    cate = models.ForeignKey(Ecate, verbose_name="设备分类", on_delete=models.SET_NULL, null=True, blank=True, related_name="cate")
    tags = models.JSONField("设备标签", default=list, blank=True)
    name = models.CharField("设备名称", max_length=50)
    number_factory = models.CharField("出厂编号", max_length=50, default="", blank=True)
    number = models.CharField("设备编号", max_length=50, unique=True)
    model = models.CharField("规格型号", max_length=60, default="", blank=True)
    factory = models.CharField("生产厂", max_length=50, default="", blank=True)
    production_date = models.DateField("生产日期", null=True, blank=True)
    importance = models.PositiveSmallIntegerField("重要程度", default=10, choices=((10, "A"), (20, "B"), (30, "C")))
    buy_date = models.DateField("购置日期", null=True, blank=True)
    state = models.PositiveIntegerField("设备状态", choices=state_choices, default=EQUIP_STATE_OK)
    parameter = models.TextField("技术参数", default="", blank=True)
    parameter_json = models.JSONField("技术参数", default=dict, blank=True)
    place = models.CharField("安装/存放位置", max_length=50, default="", blank=True)
    count = models.PositiveIntegerField("数量", default=1)
    keeper = models.ForeignKey(User, verbose_name="责任人", on_delete=models.CASCADE, null=True, blank=True)
    description = models.CharField("描述", max_length=200, default="", blank=True)
    device_people = models.CharField("设备管理人", max_length=100, default="", blank=True)

    # 以下是计量检测设备单独字段
    # mgmtype  = models.IntegerField('管理类别', choices=mgmtype_choices, default=1)
    # usetype  = models.IntegerField('使用类别', choices=usetype_choices, default=1)
    # way  = models.IntegerField('校准或检定方式', choices=way_choices, default=1)
    # standard = models.CharField('溯源标准或依据', max_length=200, default='', blank=True)
    meter_type = models.CharField("仪表类型", max_length=100, null=True, blank=True)
    management_level = models.CharField("管理等级", max_length=10, default="A")
    accuracy_level = models.CharField("精度等级", max_length=10, default="", blank=True)
    measurement_range = models.CharField("量程范围", max_length=100, default="", blank=True)
    use_date = models.DateField("启用日期", null=True, blank=True)
    cycle = models.PositiveSmallIntegerField("校准或检定周期(月)", null=True, blank=True)
    check_date = models.DateField("最近校准检查日期", blank=True, null=True)
    next_check_date = models.DateField("预计下次校准检查日期", blank=True, null=True)
    state_measure = models.PositiveIntegerField("计量设备状态", choices=measure_state_choices, default=EQ_WAIT)
    check_days_number = models.PositiveSmallIntegerField("临期检验预警(天)", null=True, blank=True)
    power_kw = models.FloatField("功率", null=True, blank=True)

    coordinates = models.JSONField("坐标", default=dict, blank=True)
    cd_req_addr = models.TextField("采集数据的请求地址", null=True, blank=True)

    class Meta:
        verbose_name = "设备信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.number}|{self.name}|{self.model}"


class EcheckRecord(CommonADModel):
    """
    TN:校准检定记录
    """

    CHECK_CHOICES = ((10, "正常"), (20, "异常"))
    equipment = models.ForeignKey(Equipment, verbose_name="关联设备", on_delete=models.CASCADE)
    check_organization = models.CharField("校准/检定机构", max_length=10)
    check_date = models.DateField("校准/检定日期")
    note = models.TextField("备注", null=True, blank=True)
    result = models.PositiveSmallIntegerField("结果", default=10, choices=CHECK_CHOICES, help_text=str(CHECK_CHOICES))


class EInspect(CommonADModel):
    """
    TN:巡检记录
    """

    INSPECT_RESULTS = (
        ("pass", "合格"),
        ("fail", "不合格"),
        # ('repair', '需要维修'),
        # ('urgent_repair', '紧急维修'),
        # ('partial_pass', '部分合格'),
        # ('observation', '观测中'),
        # ('repaired', '已修复'),
    )
    equipment = models.ForeignKey(Equipment, verbose_name="关联设备", on_delete=models.CASCADE)
    inspect_user = models.ForeignKey("system.user", verbose_name="巡检人", on_delete=models.CASCADE)
    inspect_time = models.DateTimeField("巡检时间")
    result = models.CharField(max_length=20, choices=INSPECT_RESULTS, verbose_name="巡检结果", help_text=str(INSPECT_RESULTS))
    note = models.TextField("备注", null=True, blank=True)


class Repair(CommonADModel):
    """
    TN:维修申请
    """
    equipment = models.ForeignKey(Equipment, verbose_name="关联设备", on_delete=models.CASCADE, related_name="repaire_equip")
    fault_description = models.TextField("故障描述")
    fault_cate = models.TextField("故障类别", null=True, blank=True)
    repair_user = models.ForeignKey("system.user", verbose_name="维修人", on_delete=models.CASCADE, null=True, blank=True)
    repair_start_time = models.DateTimeField("维修开始时间", null=True, blank=True)
    repair_duration = models.DecimalField("维修工时(小时)", max_digits=5, decimal_places=1, default=0.0)
    repair_description = models.TextField("维修描述", null=True, blank=True)
    ticket = models.OneToOneField('wf.ticket', verbose_name='关联工单',
                               on_delete=models.PROTECT, related_name='repair_ticket', null=True, blank=True)
    
    