import json
import logging

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, Serializer

from common.utils.exceptions import ValidationError

from console.customer.models import Customer
from console.electricityuser.models import ElectricityUser
from console.powerstation.models import PowerStation
from console.monitor.models import (MonitorDevices, MonitorPoints,
                                    MonitorTemplates)

logger = logging.getLogger("")


class MonitorDeviceLSerializer(ModelSerializer):
    monitor_point_name = serializers.SerializerMethodField()

    class Meta:
        model = MonitorDevices
        fields = (
            'id',
            'manufacturer',
            'model',
            'imei',
            'network_type',
            'sim',
            'status',
            'device_img',
            'monitor_point_id',
            'monitor_point_name',
        )

    def get_monitor_point_name(self, instance):
        if instance.monitor_point:
            return instance.monitor_point.name
        return None


class MonitorPointSerializer(Serializer):
    customer_id = serializers.IntegerField()
    electrical_info_id = serializers.IntegerField(allow_null=True)
    electricity_user_id = serializers.IntegerField()
    station_id = serializers.IntegerField(allow_null=True)
    equipment_id = serializers.IntegerField()
    name = serializers.CharField(max_length=32)
    frequency = serializers.IntegerField(default=300)
    current_ratio = serializers.FloatField(default=1.0, help_text="流变")
    voltage_ratio = serializers.FloatField(default=1.0, help_text="压变")
    comments = serializers.CharField(max_length=1024, allow_null=True)
    power = serializers.FloatField(default=0, help_text="额定电压")


class MonitorDeviceCSerializer(Serializer):
    manufacturer = serializers.IntegerField(help_text="厂商")
    model = serializers.IntegerField(help_text="型号")
    imei = serializers.CharField(max_length=32, help_text="imei")
    network_type = serializers.IntegerField(help_text="网络类型")
    sim = serializers.CharField(required=False,
                                default=None,
                                allow_null=True,
                                max_length=32,
                                help_text="sim")
    device_img = serializers.CharField(required=False, max_length=256, help_text="监控设备照片")
    comments = serializers.CharField(required=False, max_length=1024, help_text="备注")
    monitor_point_id = serializers.IntegerField(required=False,
                                                default=None,
                                                allow_null=True,
                                                help_text="检测点id")

    def validate(self, attrs):
        q_set = MonitorDevices.objects.filter(imei=attrs["imei"])
        monitor_point_id = attrs.get("monitor_point_id")
        if q_set:
            raise ValidationError("imei号已被注册")
        if monitor_point_id:
            if MonitorDevices.objects.filter(
                    monitor_point_id=monitor_point_id):
                raise ValidationError("该检测点已被其他设备关联")
        return attrs


class MonitorDeviceUSerializer(MonitorDeviceCSerializer):
    id = serializers.IntegerField()

    def validate(self, attrs):
        id = self.context.get("device_id")
        monitor_point_id = attrs.get("monitor_point_id")
        if not id:
            raise ValidationError("缺少id参数")
        attrs["id"] = id
        if not MonitorDevices.objects.filter(id=id):
            raise ValidationError("数据不存在")
        if MonitorDevices.objects.filter(imei=attrs["imei"]).exclude(id=id):
            raise ValidationError("imei号已被注册")
        if monitor_point_id:
            if MonitorDevices.objects.filter(
                    monitor_point_id=monitor_point_id).exclude(id=id):
                raise ValidationError("该检测点已被其他设备关联")
        return attrs

    def to_internal_value(self, data):
        return data


class MonitorDevicesRecordCSerializer(Serializer):
    order_code = serializers.CharField(max_length=32, help_text="工程编号")
    customer_id = serializers.IntegerField(help_text="客户id")
    electricity_user_id = serializers.IntegerField(help_text="户号id")
    electrical_info_id = serializers.IntegerField(help_text="电气信息id")
    device_id = serializers.IntegerField(help_text="imei")

    device_img = serializers.CharField(max_length=256, help_text="监控设备照片")
    meter_img = serializers.CharField(max_length=256, help_text="电表照片")
    trans_nameplate_img = serializers.CharField(max_length=256,
                                                help_text="变压器铭牌")
    complete_img = serializers.CharField(max_length=256, help_text="安装完成整体照片")
    data_img = serializers.CharField(max_length=256, help_text="监控数据截图")
    other_img = serializers.CharField(required=False,
                                      max_length=256,
                                      allow_null=True,
                                      allow_blank=True,
                                      help_text="其他照片")
    online_time = serializers.DateTimeField(required=False,
                                            allow_null=True,
                                            help_text="上线时间")
    approval_time = serializers.DateTimeField(required=False,
                                              allow_null=True,
                                              help_text="审批时间")
    meter_number = serializers.CharField(required=False, max_length=32, help_text="电表号")
    trans_number = serializers.CharField(max_length=32, help_text="变压器号")
    trans_capacity = serializers.IntegerField(help_text="变压器容量")
    name = serializers.CharField(max_length=64, help_text="点位名称")
    voltage_ratio = serializers.DecimalField(max_digits=6,
                                             decimal_places=2,
                                             help_text="压变")
    current_ratio = serializers.DecimalField(max_digits=6,
                                             decimal_places=2,
                                             help_text="流变")

    comments = serializers.CharField(required=False,
                                     max_length=1024,
                                     allow_null=True,
                                     help_text="评论")
    iccid = serializers.CharField(required=False,
                                  max_length=64,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="iccid")


class MonitorDevicesRecordUSerializer(Serializer):
    record_id = serializers.IntegerField(help_text="电站id")
    status = serializers.IntegerField(required=False, help_text="状态")
    comments = serializers.CharField(required=False,
                                     max_length=1024,
                                     allow_null=True,
                                     help_text="评论")

class MonitorPointsLSerializer(ModelSerializer):
    equipment_name = serializers.SerializerMethodField()
    customer_name = serializers.SerializerMethodField()
    number = serializers.SerializerMethodField()
    equipment_code = serializers.SerializerMethodField()
    station_name = serializers.SerializerMethodField()
    device_id = serializers.SerializerMethodField()
    imei = serializers.SerializerMethodField()

    class Meta:
        model = MonitorPoints
        fields = ('id', 'name', 'frequency', 'comments', 'customer_id',
                  'customer_name', 'equipment_code', 'electricity_user_id',
                  'number', 'equipment_id', 'equipment_name', 'station_id',
                  'station_name', "device_id", "imei", 'status',
                  'current_ratio', 'voltage_ratio', "power")

    def get_equipment_name(self, instance):
        if instance.equipment:
            return instance.equipment.name
        return None

    def get_equipment_code(self, instance):
        if instance.equipment:
            return instance.equipment.code
        return None

    def get_customer_name(self, instance):
        if instance.customer:
            return instance.customer.name
        return None

    def get_number(self, instance):
        if instance.electricity_user:
            return instance.electricity_user.number
        return None

    def get_station_name(self, instance):
        if instance.station:
            return instance.station.name
        return None

    def get_device_id(self, instance):
        device = instance.ptdv.first()
        if device:
            return device.id
        return None

    def get_imei(self, instance):
        device = instance.ptdv.first()
        if device:
            return device.imei
        return None


class MonitorPointsCSerializer(Serializer):
    name = serializers.CharField(max_length=32)
    frequency = serializers.IntegerField()
    current_ratio = serializers.FloatField(default=1.0, help_text="流变")
    voltage_ratio = serializers.FloatField(default=1.0, help_text="压变")
    comments = serializers.CharField(max_length=1024, allow_null=True)
    customer_id = serializers.IntegerField()
    electricity_user_id = serializers.IntegerField()
    station_id = serializers.IntegerField(required=False)
    electrical_info_id = serializers.IntegerField(required=False)
    outline_id = serializers.IntegerField(required=False, allow_null=True)
    equipment_id = serializers.IntegerField(allow_null=True, required=False)
    device_id = serializers.IntegerField(required=False, allow_null=True)
    template_id = serializers.IntegerField(required=False, allow_null=True)
    power = serializers.IntegerField(required=False, allow_null=True)
    phone_list = serializers.CharField(max_length=256, required=False, allow_null=True)

    def validate(self, attrs):
        customer_id = attrs["customer_id"]
        device_id = attrs.get("device_id")
        electricity_user_id = attrs["electricity_user_id"]
        template_id = attrs["template_id"]
        name = attrs["name"]
        if not Customer.objects.filter(id=customer_id, deleted=False):
            raise ValidationError("客户不存在")
        if not ElectricityUser.objects.filter(id=electricity_user_id,
                                              deleted=False):
            raise ValidationError("户号不存在")
        if device_id:
            device = MonitorDevices.objects.filter(id=device_id,
                                                   deleted=False).first()
            if not device:
                raise ValidationError("设备不存在")
            if device.monitor_point:
                raise ValidationError("设备已被其他检测点绑定")
        if template_id:
            if not MonitorTemplates.objects.filter(id=template_id,
                                                   deleted=False):
                raise ValidationError("监控模板不存在")
        # if MonitorPoints.objects.filter(name=name, deleted=False):
        #     raise ValidationError("监控点名称重复")
        return attrs


class MonitorPointsUSerializer(MonitorPointsCSerializer):
    id = serializers.IntegerField()

    def validate(self, attrs):
        id = attrs["id"]
        device_id = attrs.get("device_id")
        if device_id:
            device = MonitorDevices.objects.filter(id=device_id, deleted=False)
            if not device:
                raise ValidationError("设备不存在")
            if device.exclude(monitor_point_id=id):
                raise ValidationError("设备已被其他检测点绑定")
        return attrs

    def to_internal_value(self, data):
        return data


class MonitorTemplateCSerializer(ModelSerializer):
    id = serializers.IntegerField(required=False)

    class Meta:
        model = MonitorTemplates
        fields = ('id', 'name', 'role', 'notification_type', 'comments')

    def validate(self, attrs):
        name = attrs["name"]
        try:
            attrs["role"] = json.dumps(attrs["role"])
            attrs["notification_type"] = ','.join(
                [str(i) for i in attrs["notification_type"]])
        except Exception as e:
            logger.debug(e)
            raise ValidationError("role或notification_type参数不合法")
        if MonitorTemplates.objects.filter(name=name):
            raise ValidationError("模板名称重复")
        return attrs

    def to_internal_value(self, data):
        return data


class MonitorTemplateUSerializer(MonitorTemplateCSerializer):
    id = serializers.IntegerField()

    def validate(self, attrs):
        id = attrs["id"]
        name = attrs["name"]
        try:
            attrs["role"] = json.dumps(attrs["role"])
            attrs["notification_type"] = ','.join(
                [str(i) for i in attrs["notification_type"]])
        except Exception as e:
            logger.debug(e)
            raise ValidationError("role或notification_type参数不合法")
        if MonitorTemplates.objects.filter(name=name).exclude(id=id):
            raise ValidationError("模板名称重复")
        return attrs


class AlarmUSerializer(Serializer):
    status = serializers.IntegerField(required=True, help_text="状态")
    comments = serializers.CharField(required=True, help_text="备注")
    alarm_id = serializers.IntegerField(required=True, help_text="告警id")
