from apps.utils.serializers import CustomModelSerializer
from apps.enm.models import Mpoint, MpLog, MpointStat, EnStat, EnStat2
from apps.utils.constants import EXCLUDE_FIELDS
from rest_framework import serializers
from apps.mtm.models import Mgroup
from rest_framework.exceptions import ParseError


class MpointSerializer(CustomModelSerializer):
    mgroup = serializers.PrimaryKeyRelatedField(label="测点集", queryset=Mgroup.objects.all(), required=False, allow_null=True)
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    belong_dept_name = serializers.CharField(source='belong_dept.name', read_only=True)
    ep_monitored_name = serializers.CharField(source='ep_monitored.name', read_only=True)
    ep_monitored_power_kw = serializers.CharField(source='ep_monitored.power_kw', read_only=True)
    ep_belong_name = serializers.CharField(source='ep_belong.name', read_only=True)
    material_name = serializers.CharField(source='material.name', read_only=True)
    formula = serializers.CharField(allow_blank=True, required=False)
    class Meta:
        model = Mpoint
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS + ['belong_dept', 'cate']
    
    def validate(self, attrs):
        if 'material'  in attrs and attrs['material']:
            attrs['cate'] = 'material'
        if 'mgroup' in attrs and attrs['mgroup']:
            attrs['belong_dept'] = attrs['mgroup'].belong_dept
            # attrs['mgroups_allocate'] = [{'mgroup': attrs['mgroup'].id, 'mgroup_name': attrs['mgroup'].name, 'ratio': 1}]
        ratio_ = 0
        mgroupIds = []
        for i in attrs['mgroups_allocate']:
            if i['mgroup']:
                ratio_ = ratio_ + i['ratio']
                if i['mgroup'] in mgroupIds:
                    raise ParseError('分配集错误')
                mgroupIds.append(i['mgroup'])
                i['mgroup_name'] = Mgroup.objects.get(id=i['mgroup']).name
        if attrs['mgroups_allocate'] and round(ratio_, 3) != 1.0:
            raise ParseError('比例合计错误')
        return attrs


class MpLogSerializer(CustomModelSerializer):
    mpoint_name = serializers.CharField(source='mpoint.name', read_only=True)
    class Meta:
        model = MpLog
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS + ['mpoint_name']
    




class MpointStatSerializer(CustomModelSerializer):
    mpoint_name = serializers.CharField(source='mpoint.name', read_only=True)
    ep_monitored_name = serializers.CharField(source='mpoint.ep_monitored.name', read_only=True)
    ep_monitored_number = serializers.CharField(source='mpoint.ep_monitored.number', read_only=True)
    ep_monitored_power_kw= serializers.CharField(source='mpoint.ep_monitored.power_kw', read_only=True)
    ep_belong_name = serializers.CharField(source='mpoint.ep_belong.name', read_only=True)
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    belong_dept_name = serializers.CharField(source='mgroup.belong_dept.name', read_only=True)
    class Meta:
        model = MpointStat
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS + ['mpoint_name', 'type', 'year', 'month', 'day']
    
    def check_required_keys(dictionary, keys):
        for key in keys:
            if key not in dictionary or not dictionary[key]:
                return False
        return True

    def validate(self, attrs):
        mpoint = attrs['mpoint']
        if mpoint.material and mpoint.is_auto is False and 'sflog' in attrs and attrs['sflog']:
            attrs['type'] = 'sflog'
            sflog = attrs['sflog']
            attrs['year_s'], attrs['month_s'], attrs['day_s'] = sflog.get_ymd
            attrs['mgroup'] = sflog.mgroup
        else:
            raise ParseError('该数据不支持手工录入')
        # if 'sflog' in attrs and attrs['sflog']:
            
        # else:
        #     keys = ['hour', 'day_s', 'month_s', 'year_s']
        #     for ind, key in enumerate(keys):
        #         if key in attrs and attrs['key']:
        #             if not self.check_required_keys(attrs, keys[ind+1:]):
        #                 raise ParseError('缺少数据')
        #             attrs['type'] = key
        return super().validate(attrs)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        my_dic_keys = list(ret.keys())
        for key in my_dic_keys:
            ret_one_val = ret[key]
            if isinstance(ret_one_val, float):
                ret[key] = "{:.2f}".format(round(ret_one_val, 2))
        return ret


class EnStatSerializer(CustomModelSerializer):
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    team_name = serializers.CharField(source='team.name', read_only=True)
    belong_dept_name = serializers.CharField(source='mgroup.belong_dept.name', read_only=True)
    class Meta:
        model = EnStat
        fields = '__all__'
    
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        my_dic_keys = list(ret.keys())
        for key in my_dic_keys:
            ret_one_val = ret[key]
            if isinstance(ret_one_val, float):
                ret[key] = "{:.2f}".format(round(ret_one_val, 2))
            qua_data = ret['qua_data']
            equip_elec_data = ret['equip_elec_data']
            if qua_data:
                for item in qua_data:
                    ret[f'{item["material_name"]}_{item["testitem_name"]}_rate_pass'] = "{:.2f}".format(round(item['rate_pass'], 4)) 
            if equip_elec_data:
                for item in equip_elec_data:
                    val = item.get('consume_unit', None)
                    if val:
                        val = "{:.2f}".format(round(val, 2))
                    ret[f'{item["equipment_name"]}_consume_unit'] = val
        return ret

class EnStat2Serializer(CustomModelSerializer):
    class Meta:
        model = EnStat2
        fields = '__all__'

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        my_dic_keys = list(ret.keys())
        for key in my_dic_keys:
            ret_one_val = ret[key]
            if isinstance(ret_one_val, float):
                ret[key] = "{:.2f}".format(round(ret_one_val, 2))
        return ret
    

class ReCalSerializer(serializers.Serializer):
    start_time = serializers.DateTimeField(label="开始时间")
    end_time = serializers.DateTimeField(label="结束时间")