from django.db import models
from apps.utils.models import BaseModel, CommonBModel, CommonADModel, CommonBDModel
from apps.wpm.models import SfLog
from apps.mtm.models import Material, Mgroup, Team
from django_celery_beat.models import PeriodicTask

class Xscript(BaseModel):
    """TN:脚本"""
    name = models.CharField("脚本名称", max_length=50)
    code = models.TextField("脚本内容", null=True, blank=True)
    base_data = models.JSONField("基础数据", default=dict, null=True, blank=True)
    change_data = models.JSONField("变更数据", default=dict, null=True, blank=True)
    myschedule = models.ForeignKey('system.myschedule', verbose_name='周期', on_delete=models.SET_NULL, null=True, blank=True)
    periodictask = models.ForeignKey(PeriodicTask, verbose_name='关联定时任务', on_delete=models.CASCADE, related_name='xscript_periodictask', null=True, blank=True)

class Mpoint(CommonBModel):
    """TN:测点"""
    MT_AUTO = 10
    MT_COMPUTE = 20
    MT_MANUAL = 30

    MG_OK = 0  # 采集状态
    MG_SAVEWRONG = -1
    MG_OFFLINE = -2

    type = models.PositiveSmallIntegerField("类型", default=MT_AUTO, help_text="10:自动采集, 20:计算测点, 30:手动录入")
    up_down = models.BooleanField("上下行计算", default=False)
    is_unit = models.BooleanField("是否单位量", default=False)
    name = models.CharField("测点名称", max_length=50)
    nickname = models.CharField("测点别名", max_length=50, null=True, blank=True)
    code = models.CharField("测点编号", max_length=50, unique=True)
    unit = models.CharField("单位", max_length=50, null=True, blank=True)
    cate = models.CharField("分类", max_length=50, null=True, blank=True)
    save_expr = models.TextField("存储表达式", null=True, blank=True)
    material = models.ForeignKey(Material, verbose_name="计量某种物料", on_delete=models.CASCADE, null=True, blank=True)
    ep_belong = models.ForeignKey("em.equipment", verbose_name="所属设备", related_name="mp_ep_belong", on_delete=models.SET_NULL, null=True, blank=True)
    mgroup = models.ForeignKey("mtm.mgroup", verbose_name="所在集合", on_delete=models.SET_NULL, null=True, blank=True)
    is_rep_mgroup = models.BooleanField("是否代表所分配集合数据", default=False)
    formula = models.TextField("计算公式", default="")
    func_on_change = models.CharField("数据变动时执行方法", max_length=100, default="", blank=True)  # 废弃字段暂时不用
    interval = models.PositiveSmallIntegerField("采集间隔(秒)", default=10)
    val_type = models.CharField("值类型", default="float", max_length=50, help_text="float, int, str, bool")
    enabled = models.BooleanField("是否启用", default=False)
    third_info = models.JSONField("第三方信息", default=dict, blank=True)
    # {"from": "king", "n": "某名称","d": "某描述或备注","g": "某组", "t": "某类型",  "id": 5001, "o": "其他信息"}
    enp_field = models.CharField("关联enp采集字段", max_length=50, null=True, blank=True)
    is_rep_ep0_running_state = models.BooleanField("是否表示所属设备运行状态", default=False)
    is_rep_ep_running_state = models.BooleanField("是否表示所监测设备运行状态", default=False)
    ep_monitored = models.ForeignKey("em.equipment", verbose_name="所监测设备", related_name="mp_ep_monitored", on_delete=models.SET_NULL, null=True, blank=True)
    ep_rs_val = models.FloatField("状态量基准值", null=True, blank=True)
    ep_rs_expr = models.TextField("状态量表达式", null=True, blank=True)
    mpoint_affect = models.ForeignKey("self", verbose_name="影响测点", related_name="mp_mpoint_affect", on_delete=models.SET_NULL, null=True, blank=True, to_field='code')

    need_display = models.BooleanField("是否需要展示", default=False)
    report_sortstr = models.CharField('在报告中的排序', max_length=50, default='', blank=True)

    coefficient = models.FloatField("采集系数", default=1.0)

    need_change_cal_coefficient = models.BooleanField("是否需要变更计算系数", default=False)
    cal_coefficient_name = models.CharField("计算系数名称", max_length=50, null=True, blank=True)
    cal_coefficient_method = models.PositiveSmallIntegerField("计算系数方法", default=1, choices=((1, "乘"), (2, "除")))
    cal_coefficient = models.FloatField("计算系数", null=True, blank=True)

    mpoint_from = models.ForeignKey("self", verbose_name="来源自采测点", related_name="mp_mpoint_from", on_delete=models.SET_NULL, null=True, blank=True)
    cal_related_mgroup_running = models.PositiveSmallIntegerField("与工段运行状态的关联", default=10, choices=[(10, "不涉及"), (20, "运行时统计")], null=True, blank=True)

    @classmethod
    def cache_key(cls, code: str):
        return f"mpoint_{code}"

class MpLogx(models.Model):
    """
    TN:测点记录超表
    """

    timex = models.DateTimeField("采集时间", primary_key=True)
    mpoint = models.ForeignKey(Mpoint, verbose_name="关联测点", on_delete=models.CASCADE)
    val_mrs = models.PositiveSmallIntegerField("所监测设备运行状态值", null=True, blank=True)
    val_float = models.FloatField("数值", null=True, blank=True)
    val_int = models.IntegerField("数值", null=True, blank=True)
    val_bool = models.BooleanField("数值", null=True, blank=True)
    val_str = models.TextField("数值", null=True, blank=True)

    class Meta:
        db_table = "enm_mplogx"
        managed = False
        unique_together = (("mpoint", "timex"),)


class MpLog(BaseModel):
    """TN:旧表(已废弃)"""

    mpoint = models.ForeignKey(Mpoint, verbose_name="关联测点", on_delete=models.SET_NULL, null=True, blank=True)
    tag_id = models.BigIntegerField("记录ID", db_index=True)
    tag_code = models.CharField("测点编号", max_length=50)
    tag_update = models.DateTimeField("更新时间")
    tag_val = models.FloatField("当前值")


class MpointStat(CommonADModel):
    """TN:测点统计表"""

    type = models.CharField("统计维度", max_length=50, default="hour", help_text="year/month/day/year_s/month_s/month_st/day_s/sflog/hour_s/hour")
    year = models.PositiveSmallIntegerField("年", null=True, blank=True)
    month = models.PositiveSmallIntegerField("月", null=True, blank=True)
    day = models.PositiveSmallIntegerField("日", null=True, blank=True)

    year_s = models.PositiveSmallIntegerField("班年", null=True, blank=True)
    month_s = models.PositiveSmallIntegerField("班月", null=True, blank=True)
    day_s = models.PositiveSmallIntegerField("班日", null=True, blank=True)

    hour = models.PositiveSmallIntegerField("时", null=True, blank=True)
    sflog = models.ForeignKey(SfLog, verbose_name="关联值班记录", on_delete=models.CASCADE, null=True, blank=True)
    mgroup = models.ForeignKey(Mgroup, verbose_name="关联测点集", on_delete=models.CASCADE, null=True, blank=True)
    mpoint = models.ForeignKey(Mpoint, verbose_name="关联测点", on_delete=models.CASCADE)
    val = models.FloatField("统计值", default=0)
    val_level = models.CharField("峰谷平", max_length=50, null=True, blank=True, help_text="peak/high/flat/low/deep")
    val_origin = models.FloatField("统计原始值", default=0)
    current_cal_coefficient = models.FloatField("采用计算系数", null=True, blank=True)
    val_correct = models.FloatField("统计矫正值", null=True, blank=True)
    total_production = models.FloatField("总产量", default=0, help_text="t")
    elec_consume_unit = models.FloatField("单位产品电耗", default=0, help_text="kw·h/t")


class EnStat(BaseModel):
    """
    TN:能源数据统计表
    """

    type = models.CharField("统计维度", max_length=50, default="hour", help_text="year_s/month_s/month_st/day_s/sflog/hour_s")
    sflog = models.ForeignKey(SfLog, verbose_name="关联值班记录", on_delete=models.CASCADE, null=True, blank=True)
    team = models.ForeignKey(Team, verbose_name="关联班组", on_delete=models.CASCADE, null=True, blank=True)
    mgroup = models.ForeignKey(Mgroup, verbose_name="关联工段", on_delete=models.CASCADE)
    year = models.PositiveSmallIntegerField("年", null=True, blank=True)
    month = models.PositiveSmallIntegerField("月", null=True, blank=True)
    day = models.PositiveSmallIntegerField("日", null=True, blank=True)
    hour = models.PositiveSmallIntegerField("小时", null=True, blank=True)
    year_s = models.PositiveSmallIntegerField("班年", null=True, blank=True)
    month_s = models.PositiveSmallIntegerField("班月", null=True, blank=True)
    day_s = models.PositiveSmallIntegerField("班日", null=True, blank=True)
    total_production = models.FloatField("总产量", default=0, help_text="t")
    total_production_cost = models.FloatField("总产量(用于成本)", default=0, help_text="t")
    elec_consume = models.FloatField("总电耗", default=0, help_text="kw·h")
    elec_coal_consume = models.FloatField("电量折标煤", default=0, help_text="tce")
    pcoal_heat = models.FloatField("煤粉热值", default=0)
    pcoal_consume = models.FloatField("煤粉消耗", default=0, help_text="t")
    pcoal_coal_consume = models.FloatField("煤粉折标煤", default=0, help_text="tce")
    water_consume = models.FloatField("水消耗", default=0, help_text="t")
    cair_consume = models.FloatField("压缩空气", default=0, help_text="m3")
    out_steam = models.FloatField("外送蒸汽", default=0, help_text="t")
    out_steam_coal = models.FloatField("外送蒸汽折标煤", default=0, help_text="tce")
    ccr_consume = models.FloatField("电石渣消耗", default=0, help_text="t")
    kiln_end_heat = models.FloatField("窑尾余热", default=0, help_text="tce")
    imaterial_data = models.JSONField("成本物料数据", default=list, blank=True)
    imaterial_data_dict = models.JSONField("成本物料数据", default=dict, blank=True)
    other_cost_data = models.JSONField("其他成本数据", default=list, blank=True)
    qua_data = models.JSONField("质检数据", default=list, blank=True)
    equip_elec_data = models.JSONField("设备电耗数据", default=list, blank=True)
    production_cost_unit = models.FloatField("单位产品成本", default=0, help_text="y/t")
    elec_consume_unit = models.FloatField("单位产品分布电耗", default=0, help_text="kw·h/t")
    celec_consume_unit = models.FloatField("单位产品综合电耗", default=0, help_text="kw·h/t")
    coal_consume_unit = models.FloatField("单位产品标煤耗", default=0, help_text="kgce/t")
    en_consume_unit = models.FloatField("单位产品能耗", default=0, help_text="kgce/t")
    cen_consume_unit = models.FloatField("单位产品综合能耗", default=0, help_text="kgce/t")
    production_hour = models.FloatField("台时产量/发电功率", default=0, help_text="t/h")
    production_elec_unit = models.FloatField("吨熟料发电量", default=0, help_text="kw·h/t")
    production_elec_consume_unit = models.FloatField("吨熟料电耗", default=0, help_text="kw·h/t")
    total_sec_now = models.PositiveIntegerField("动态总时长", default=0, help_text="s")
    run_sec = models.PositiveIntegerField("运转时长", default=0, help_text="s")
    shut_sec = models.PositiveIntegerField("停机时长", default=0, help_text="s")
    run_rate = models.FloatField("运转率", default=0, help_text="%")
    ammonia_consume = models.FloatField("氨水消耗", default=0, help_text="t")
    note = models.TextField("备注", default="", blank=True)


class EnStat2(BaseModel):
    """
    TN:能源数据统计表2
    """

    type = models.CharField("统计维度", max_length=50, default="month_s", help_text="month_s/day_s")
    year_s = models.PositiveSmallIntegerField("班年")
    month_s = models.PositiveSmallIntegerField("班月")
    day_s = models.PositiveSmallIntegerField("班日", null=True, blank=True)
    industry_total_val = models.FloatField("工业总产值", default=0, help_text="万元")
    industry_add_val = models.FloatField("工业增加值", default=0, help_text="万元")
    elec_consume = models.FloatField("总电耗", default=0, help_text="kw·h")
    water_consume = models.FloatField("水耗", default=0, help_text="t")
    cair_consume = models.FloatField("压缩空气", default=0, help_text="m3")
    elec_coal_consume = models.FloatField("电量折标煤", default=0, help_text="tce")
    pcoal_consume = models.FloatField("煤粉消耗", default=0, help_text="t")
    pcoal_coal_consume = models.FloatField("煤粉折标煤", default=0, help_text="tce")
    bulk_cement_val = models.FloatField("散装水泥发运量", default=0)
    bulk_cement_price = models.FloatField("散装水泥价格", default=0)
    bag_cement_val = models.FloatField("袋装水泥发运量", default=0)
    bag_cement_price = models.FloatField("袋装水泥价格", default=0)
    clinker_val = models.FloatField("出窑熟料产量", default=0)
    clinker_price = models.FloatField("出窑熟料价格", default=0)
    cliker_price_cost = models.FloatField("出窑熟料成本", default=0)
    bulk_clinker_val = models.FloatField("散装熟料出厂量", default=0)
    bulk_clinker_price = models.FloatField("散装熟料价格", default=0)
    cement_val = models.FloatField("出磨水泥产量", default=0)
    cement_cost_unit = models.FloatField("出磨水泥单位成本", default=0)
    out_cement_val = models.FloatField("出厂水泥产量", default=0)
    out_cement_cost_unit = models.FloatField("出厂水泥单位成本", default=0)
    en_consume = models.FloatField("能源消耗", default=0, help_text="tce")
    en_consume_unit = models.FloatField("单位工业总产值能耗", default=0)
    en_add_consume_unit = models.FloatField("单位工业增加值能耗", default=0)
