import datetime
import logging

from django.db.models import F
from rest_framework import serializers

from common.accounts.models import Enterprise, Users
from common.utils.exceptions import ValidationError

from console.customer.models import (Customer, CustomerAdmin)

from console.customer.models import CustomerReport

from console.electricityuser.models import ElectricityUser

LOG = logging.getLogger()


class EnterpriseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Enterprise
        fields = ('id', 'enterprise_id', 'name', 'logo', 'address', 'industry',
                  'scale', 'asset', 'longitude', 'latitude', 'covered_area')


class CustomerAdminSerializer(serializers.ModelSerializer):
    customer = serializers.PrimaryKeyRelatedField(
        queryset=Customer.objects.all())
    user = serializers.PrimaryKeyRelatedField(queryset=Users.objects.all())

    class Meta:
        model = CustomerAdmin
        fields = ('id', 'customer', 'user')


class CustomerListSerializer(serializers.ModelSerializer):
    industry = serializers.SerializerMethodField()
    address = serializers.SerializerMethodField()
    scale = serializers.SerializerMethodField()
    asset = serializers.SerializerMethodField()
    customer_admin = serializers.SerializerMethodField()
    electricityuser_num = serializers.SerializerMethodField()
    type = serializers.SerializerMethodField()

    class Meta:
        model = Customer
        fields = ('id', 'name', 'level', 'type', 'industry', 'scale', 'asset',
                  'customer_admin', 'address', 'electricityuser_num')

    def get_electricityuser_num(self, obj):
        num = obj.electricityuser.count()
        return num

    def get_address(self, obj):
        addr = obj.enterprise.address
        return addr

    def get_industry(self, obj):
        industry = obj.enterprise.industry if obj.enterprise else None
        return industry

    def get_scale(self, obj):
        scale = obj.enterprise.scale if obj.enterprise else None
        return scale

    def get_asset(self, obj):
        asset = obj.enterprise.asset if obj.enterprise else None
        return asset

    def get_customer_admin(self, obj):
        customer_admin = obj.customer_admin.filter(deleted=False).values(
            "user_id", nickname=F("user__nickname"), phone=F("user__phone"))
        return customer_admin

    def get_type(self, obj):
        if obj.type:
            return [int(i) for i in obj.type.split(",")]
        return []


class EnterpriseCSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False,
                                  allow_null=True,
                                  help_text="id")
    name = serializers.CharField(max_length=64, help_text="名字")
    address = serializers.CharField(max_length=1024,
                                    allow_null=True,
                                    allow_blank=True,
                                    help_text="地址")
    longitude = serializers.CharField(max_length=32,
                                      allow_null=True,
                                      allow_blank=True,
                                      help_text='经度')
    latitude = serializers.CharField(max_length=32,
                                     allow_null=True,
                                     allow_blank=True,
                                     help_text='纬度')
    adcode = serializers.CharField(max_length=32,
                                   allow_null=True,
                                   allow_blank=True,
                                   help_text='区域编码')
    logo = serializers.URLField(allow_null=True,
                                allow_blank=True,
                                help_text="企业logo")

    legal_person = serializers.CharField(allow_null=True,
                                         allow_blank=True,
                                         max_length=64,
                                         help_text="法人")
    legal_person_phone = serializers.CharField(max_length=16,
                                               allow_null=True,
                                               allow_blank=True,
                                               help_text="法人联系方式")
    tax_num = serializers.CharField(max_length=32,
                                    allow_blank=True,
                                    allow_null=True,
                                    help_text="税号")
    bank_account_name = serializers.CharField(max_length=255,
                                              allow_null=True,
                                              allow_blank=True,
                                              help_text="银行开户名")
    bank_name = serializers.CharField(max_length=255,
                                      allow_null=True,
                                      allow_blank=True,
                                      help_text="银行")
    postcode = serializers.CharField(max_length=16,
                                     allow_blank=True,
                                     allow_null=True,
                                     help_text="邮编")

    scale = serializers.CharField(max_length=16, allow_blank=True,
                                  allow_null=True, help_text="企业规模")
    nature = serializers.CharField(max_length=16, allow_blank=True,
                                   allow_null=True, help_text="企业性质")
    industry = serializers.CharField(max_length=16, allow_blank=True,
                                     allow_null=True, help_text="所属行业")
    asset = serializers.CharField(max_length=16, allow_blank=True,
                                  allow_null=True, help_text="资产规模")
    covered_area = serializers.CharField(max_length=16, allow_blank=True,
                                         allow_null=True, help_text="占地面积")

    parent_enterprise_id = serializers.CharField(required=False,
                                                 allow_blank=True,
                                                 allow_null=True,
                                                 help_text="上级公司id")

    def validate(self, attrs):
        attrs["parent_enterprise_id"] = None
        attrs["covered_area"] = None if attrs["covered_area"] == "" else attrs["covered_area"]
        attrs["asset"] = None if attrs["asset"] == "" else attrs["asset"]
        attrs["scale"] = None if attrs["scale"] == "" else attrs["scale"]
        attrs["nature"] = None if attrs["nature"] == "" else attrs["nature"]
        attrs["industry"] = None if attrs["industry"] == "" else attrs["industry"]
        attrs["legal_person_phone"] = None if attrs["legal_person_phone"] == "" else attrs["legal_person_phone"]

        return attrs


class EnterpriseUSerializer(EnterpriseCSerializer):
    id = serializers.IntegerField(help_text="id")


class ContactSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False,
                                  allow_null=True,
                                  help_text="id")
    customer_id = serializers.IntegerField(required=False,
                                           allow_null=True,
                                           help_text="customer_id")
    name = serializers.CharField(max_length=64, help_text="名字")
    phone = serializers.CharField(max_length=64,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="手机号")
    tel = serializers.CharField(max_length=64, allow_null=True,
                                allow_blank=True, help_text="电话")
    email = serializers.CharField(max_length=128,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="邮箱")
    qq = serializers.CharField(max_length=64, allow_null=True,
                               allow_blank=True, help_text="qq")
    wechat = serializers.CharField(max_length=64,
                                   allow_null=True,
                                   allow_blank=True,
                                   help_text="微信")
    is_urge = serializers.BooleanField(default=False, help_text="催款人")
    is_quit = serializers.BooleanField(default=False, help_text="离职")
    comments = serializers.CharField(required=False,
                                     max_length=1024,
                                     allow_null=True,
                                     allow_blank=True,
                                     help_text="备注")
    tags = serializers.ListField(required=False, allow_null=True, help_text="职位")


class ContactUSerializer(ContactSerializer):
    id = serializers.IntegerField(help_text="id")


class CustomerAdminCSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False,
                                  allow_null=True,
                                  help_text="id")
    customer_id = serializers.IntegerField(required=False,
                                           allow_null=True,
                                           help_text="customer_id")
    username = serializers.CharField(max_length=64, help_text="名字")
    nickname = serializers.CharField(max_length=64, help_text="昵称")
    password = serializers.CharField(allow_null=True, max_length=32, help_text="密码")
    phone = serializers.IntegerField(help_text="手机号")
    email = serializers.CharField(max_length=128,
                                  allow_null=True,
                                  help_text="邮箱")
    wechat = serializers.CharField(max_length=64,
                                   allow_null=True,
                                   help_text="微信")
    tags = serializers.ListField(required=False, help_text="职位")


class CustomerAdminUSerializer(CustomerAdminCSerializer):
    id = serializers.IntegerField(required=False, help_text="id")


class ElectricityUserCSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False,
                                  allow_null=True,
                                  help_text="id")
    customer_id = serializers.IntegerField(required=False,
                                           allow_null=True,
                                           help_text="customer_id")
    number = serializers.CharField(max_length=32,
                                   allow_null=True,
                                   help_text="户号")
    ad_code = serializers.CharField(max_length=32, help_text="adcode")
    city_code = serializers.CharField(max_length=32,
                                      allow_null=True,
                                      help_text="city_code")
    addr = serializers.CharField(max_length=1024,
                                 allow_null=True,
                                 help_text="地址")
    transformer_capacity = serializers.FloatField(allow_null=True,
                                                  help_text="变压器容量")
    real_capacity = serializers.FloatField(allow_null=True, help_text="实际容量")
    voltage_level = serializers.IntegerField(allow_null=True, help_text="电压等级")
    type = serializers.IntegerField(allow_null=True, help_text="用电类型")
    ep_factor = serializers.FloatField(allow_null=True, help_text="电功率考核因素")
    trusteeship_num = serializers.FloatField(allow_null=True,
                                             help_text="托管电站数")
    longitude = serializers.CharField(max_length=32,
                                      allow_null=True,
                                      help_text='经度')
    latitude = serializers.CharField(max_length=32,
                                     allow_null=True,
                                     help_text='纬度')


class CustomerCSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False,
                                  allow_null=True,
                                  help_text="id")
    name = serializers.CharField(max_length=64, help_text="名字")
    level = serializers.IntegerField(help_text="等级")
    type = serializers.ListField(help_text="类型")
    code = serializers.CharField(required=False, max_length=32, help_text="编码")
    enterprise_id = serializers.IntegerField(required=False,
                                             allow_null=True,
                                             help_text="企业id")
    last_service_staff_id = serializers.IntegerField(allow_null=True,
                                                     help_text="原始客户代表id")
    service_staff_id = serializers.IntegerField(allow_null=True,
                                                help_text="客户代表id")
    service_enterprise_id = serializers.IntegerField(allow_null=True,
                                                     help_text="电管家内部企业id")
    service_organization_id = serializers.IntegerField(allow_null=True,
                                                       help_text="组织id")
    enterprise = EnterpriseCSerializer(required=True)
    contacts = ContactSerializer(required=False, many=True)
    customer_admin = CustomerAdminCSerializer(required=False, many=True)
    electricity_user = ElectricityUserCSerializer(required=False, many=True)

    # def validate(self, attrs):
    #     name = attrs["name"]
    #     if Customer.objects.filter(name=name, deleted=False):
    #         raise ValidationError("客户名重复")
    #     return attrs


class CustomerUSerializer(serializers.Serializer):
    id = serializers.IntegerField(help_text="id")
    name = serializers.CharField(max_length=64, help_text="名字")
    level = serializers.IntegerField(help_text="等级")
    type = serializers.ListField(help_text="类型")
    enterprise_id = serializers.IntegerField(help_text="企业id")
    last_service_staff_id = serializers.IntegerField(required=False,
                                                     allow_null=True,
                                                     help_text="原始客户代表id")
    service_staff_id = serializers.IntegerField(allow_null=True,
                                                help_text="客户代表id")
    service_enterprise_id = serializers.IntegerField(allow_null=True,
                                                     help_text="电管家内部企业id")
    service_organization_id = serializers.IntegerField(allow_null=True,
                                                       help_text="组织id")
    enterprise = EnterpriseUSerializer(required=False)
    customer_admin = CustomerAdminUSerializer(required=False, many=True)
    contacts = ContactUSerializer(required=False, many=True)

    def validate(self, attrs):
        name = attrs["name"]
        id = attrs["id"]
        if attrs["enterprise_id"] != attrs["enterprise"]["id"]:
            raise ValidationError("企业id不匹配")
        if Customer.objects.filter(name=name, deleted=False).exclude(id=id):
            raise ValidationError("客户名重复")
        return attrs


class CustomerReportUploadSerializer(serializers.Serializer):
    customer_id = serializers.IntegerField(required=True, allow_null=False)
    url = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    year_month = serializers.CharField(required=True, allow_blank=False, allow_null=False)
    report_id = serializers.CharField(required=True, allow_null=False, allow_blank=True)
    ele_user_id = serializers.IntegerField(required=True, allow_null=False)

    def validate(self, attrs):
        customer = Customer.objects.filter(id=attrs.get("customer_id")).first()
        if not customer:
            raise serializers.ValidationError("客户%s不存在" % attrs.get("customer_id"))
        ele_user = ElectricityUser.objects.filter(id=attrs.get("ele_user_id")).first()
        if not ele_user:
            raise serializers.ValidationError("户号%s不存在" % attrs.get("ele_user_id"))
        attrs["power_number"] = ele_user.number
        attrs.pop("ele_user_id")
        return attrs

    def create(self, validated_data):
        instance = CustomerReport.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        instance.url = validated_data.get("url")
        instance.year_month = validated_data.get("year_month")
        instance.save()
        return instance


class CustomerReportInfoSerializer(serializers.ModelSerializer):
    report_time = serializers.SerializerMethodField()
    confirm = serializers.SerializerMethodField()
    confirm_time = serializers.SerializerMethodField()

    def get_confirm(self, obj):
        return obj.basic_confirm

    def get_confirm_time(self, obj):
        return obj.basic_confirm_time

    def get_report_time(self, obj):
        return obj.created_time

    class Meta:
        model = CustomerReport
        fields = ("id", "url", "year_month", "report_time",
                  "confirm", "confirm_time")


class BasicConfirmSerializer(serializers.Serializer):
    def update(self, instance, validated_data):
        instance.basic_confirm = True
        instance.basic_confirm_time = datetime.datetime.now()
        instance.save()
        return instance


class SupperConfirmSerializer(serializers.Serializer):
    power_number = serializers.CharField(required=True, allow_blank=False, allow_null=True)
    year_month = serializers.CharField(required=True, allow_null=False, allow_blank=False)

    def update(self, instance, validated_data):
        instance.supper_confirm = True
        instance.supper_confirm_time = datetime.datetime.now()
        instance.save()
        return instance
