import datetime
import json

from django.db import transaction
from django.db.models import Count, F
from rest_framework import serializers as serializer

from common.accounts.serializers import UsersLCSerializer
from console.inspection.serializers import TeamSerializer
from console.order.models import Order
from console.task.serializers import TaskInfoSerializer, \
    TaskListSerializer

from common.accounts.models import Users
from common.utils.service_code import PARAMETER_ERROR
from console.customer.models import Customer
from console.order.models import WorkTicket, OrderReport
from console.team.models import Team

from console.order.services import WorkTicketServer

from console.order.models import Material, ConsumableMaterial

from console.order.models import PowerLog

from common.utils.models import BaseConnection
from console.powerstation.models import PowerStation

from common.notify.message import MessageObject

from console.task.models import WorkLog

from console.task.services import create_order_notify

from console.order.services import send_order_finish_message, \
    send_order_assign_message

ORDER_TYPE_MAP = {
    "rush_to_repair": "抢修",
    "power_construction": "电力施工",
    "electrical_testing": "电力试验",
    "demand_declaration": "需量申报"
}


class OrderReportSerializer(serializer.ModelSerializer):
    class Meta:
        model = OrderReport
        fields = ("id", "problem", "describe", "investigation", "handle",
                  "proposal", "is_finish")


class OrderListInfoSerializer(serializer.ModelSerializer):
    task = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()

    def get_task(self, obj):
        return TaskListSerializer(obj.task).data

    def get_team(self, obj):
        return TeamSerializer(obj.team).data

    class Meta:
        model = Order
        fields = ("id", "name", "task", "type", "status", "team",
                  "created_time")


class OrderInfoSerializer(serializer.ModelSerializer):
    task = serializer.SerializerMethodField()
    recipient = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()
    weather = serializer.SerializerMethodField()
    work_log = serializer.SerializerMethodField()
    work_ticket = serializer.SerializerMethodField()
    file = serializer.SerializerMethodField()
    order_record = serializer.SerializerMethodField()

    def get_order_record(self, obj):
        record = OrderReport.objects.filter(order=obj)
        return OrderReportSerializer(record, many=True).data

    def get_file(self, obj):
        return json.loads(obj.file) if obj.file else None

    def get_work_ticket(self, obj):
        work_ticket = WorkTicket.objects.filter(order=obj,
                                                deleted=False).first()

        return {
            "id": work_ticket.id,
            "code": work_ticket.code,
            "type": work_ticket.type
        } if work_ticket else None

    def get_work_log(self, obj):
        power_logs = PowerLog.objects.filter(order=obj)
        serializers = PowerLogInfoSerializer(power_logs, many=True)
        return serializers.data

    def get_weather(self, obj):
        return "晴"

    def get_task(self, obj):
        return TaskInfoSerializer(obj.task).data

    def get_recipient(self, obj):
        return UsersLCSerializer(obj.recipient).data

    def get_team(self, obj):
        return TeamSerializer(obj.team).data

    class Meta:
        model = Order
        fields = ("id", "name", "task", "recipient", "team", "created_time",
                  "content", "commencement_date", "file", "conclusion",
                  "receiving_time", "status", "type", "start_time",
                  "finish_time", "weather", "work_log", "transfer_reason",
                  "work_ticket", "order_record")


class OrderAssignSerializer(serializer.Serializer):
    team_id = serializer.IntegerField(required=True,
                                      allow_null=False,
                                      help_text="处理人id")

    def validate(self, attrs):
        team = Team.objects.filter(id=attrs.get("team_id"),
                                   deleted=False).first()
        if not team:
            raise serializer.ValidationError("班组%s不存在" % attrs.get("team_id"))
        attrs["team"] = team

        return attrs

    @transaction.atomic()
    def update(self, instance, validated_data):
        point = transaction.savepoint()
        try:
            request = self.context.get("request")
            instance.team_id = validated_data.get("team_id")
            # instance.receiving_time = datetime.datetime.now()
            instance.status = "pending"
            instance.save()
            send_order_assign_message(instance, validated_data.get("team"))
            # 发送短信通知
            team_headman = validated_data.get("team").team_headman
            phone_list = [
                member.phone
                for member in validated_data.get("team").member.all()
            ]
            phone_list.append(team_headman.phone)
            sms_obj = MessageObject()
            params = [
                instance.commencement_date.strftime("%Y-%m-%d %H:%M:%S"),
                ORDER_TYPE_MAP.get(instance.type)
            ]
            phone_list = list(filter(None, phone_list))
            sms_obj.send_sms_multi(phone_list, 781473, params)
            # 创建工作日志
            WorkLog.objects.create(task=instance.task,
                                   content="{}给班组{}({})派发工单{}".format(
                                       request.user.username,
                                       validated_data.get("team").id,
                                       validated_data.get("team").name,
                                       instance.name))

            create_order_notify(
                **{
                    "user": request.user,
                    "order": instance,
                    "team_id": validated_data.get("team_id")
                })
            transaction.savepoint_commit(point)
            return instance
        except Exception as e:
            transaction.savepoint_rollback(point)
            raise serializer.ValidationError(e)


class OrderWorkTicketSerializer(serializer.Serializer):
    customer_id = serializer.IntegerField(required=False,
                                          allow_null=False,
                                          help_text="客户id")
    code = serializer.CharField(required=True,
                                allow_null=False,
                                help_text="工作票编号")
    type = serializer.IntegerField(required=True,
                                   allow_null=False,
                                   help_text="工作票类型")
    order_id = serializer.IntegerField(required=True,
                                       allow_null=False,
                                       help_text="工单id")
    station_id = serializer.IntegerField(required=False,
                                         allow_null=True,
                                         help_text="电站id")
    issuer = serializer.IntegerField(required=False,
                                     allow_null=True,
                                     help_text="签发人")
    issue_time = serializer.DateTimeField(required=False,
                                          allow_null=True,
                                          help_text="签发时间")

    job_content = serializer.CharField(required=True,
                                       allow_null=False,
                                       help_text="工作内容")
    plan_start_time = serializer.DateTimeField(required=True,
                                               allow_null=False,
                                               help_text="计划开始时间")
    plan_end_time = serializer.DateTimeField(required=True,
                                             allow_null=False,
                                             help_text="计划结束时间")
    work_conditions = serializer.CharField(required=False,
                                           allow_blank=True,
                                           allow_null=True,
                                           help_text="工作条件")
    attention = serializer.CharField(required=False,
                                     allow_blank=True,
                                     allow_null=True,
                                     help_text="注意事项")
    file = serializer.CharField(required=False,
                                help_text="一次线路图",
                                allow_null=True)
    team_id = serializer.IntegerField(required=True,
                                      allow_null=False,
                                      help_text="班组id")
    person_liable_id = serializer.IntegerField(required=True,
                                               allow_null=False,
                                               help_text="负责人")
    weather = serializer.CharField(required=False,
                                   help_text="天气",
                                   allow_null=True)
    wt_safety_measure = serializer.ListField(child=serializer.DictField(),
                                             required=False,
                                             allow_null=True,
                                             allow_empty=True,
                                             help_text="安全措施")
    supplement = serializer.CharField(required=False,
                                      help_text="补充说明",
                                      allow_null=True,
                                      allow_blank=True)
    person_num = serializer.IntegerField(required=False,
                                         allow_null=True,
                                         help_text="人数")
    person_name = serializer.CharField(required=False,
                                       help_text="姓名",
                                       allow_null=True,
                                       allow_blank=True)
    wt_contact = serializer.ListField(child=serializer.DictField(),
                                      allow_empty=True,
                                      allow_null=True,
                                      help_text="无人值班变电站现场许可人与当值调度" +
                                                "（或集控站、中心站）联系")
    wt_person_changes = serializer.ListField(child=serializer.DictField(),
                                             allow_empty=True,
                                             allow_null=True,
                                             help_text="人员变动")
    delay = serializer.DateTimeField(required=False,
                                     allow_null=True,
                                     help_text="延期")
    wt_work_record = serializer.ListField(child=serializer.DictField(),
                                          allow_empty=True,
                                          allow_null=True,
                                          help_text="每日开工和收工时间（使用一天的工作票不必填写）")
    wt_child_ticket = serializer.ListField(child=serializer.DictField(),
                                           allow_empty=True,
                                           allow_null=True,
                                           help_text="工作票子票")
    finish_time = serializer.DateTimeField(required=False,
                                           allow_null=True,
                                           help_text="结束时间")
    the_end = serializer.ListField(allow_null=True,
                                   allow_empty=True,
                                   help_text="工作票终结")
    checked = serializer.ListField(allow_null=True,
                                   allow_empty=True,
                                   help_text="工作票检查",
                                   required=False)
    delay_leader = serializer.CharField(max_length=16,
                                        allow_null=True,
                                        help_text="延期负责人",
                                        required=False)
    delay_licensor = serializer.CharField(max_length=16,
                                          allow_null=True,
                                          help_text="延期许可人",
                                          required=False)
    supplement_safety_measure = serializer.CharField(max_length=1024,
                                                     allow_null=True,
                                                     help_text="补充安全措施",
                                                     required=False)
    last_leader = serializer.CharField(max_length=16,
                                       allow_null=True,
                                       help_text="原负责人",
                                       required=False)
    allow_start_time = serializer.DateTimeField(allow_null=True,
                                                help_text="允许开工时间",
                                                required=False)
    allower = serializer.CharField(max_length=16,
                                   allow_null=True,
                                   help_text="允许开工负责人",
                                   required=False)
    delay_date = serializer.DateTimeField(allow_null=True,
                                          help_text="延期日期",
                                          required=False)
    other = serializer.CharField(allow_null=True,
                                 max_length=1024,
                                 help_text="其他事项",
                                 required=False)
    handover_confirm = serializer.CharField(max_length=256,
                                            allow_null=True,
                                            help_text="交接安全确认",
                                            required=False)
    nameplate_operator = serializer.CharField(max_length=16,
                                              allow_null=True,
                                              help_text="铭牌操作员",
                                              required=False)
    nameplate_supervisor = serializer.CharField(max_length=16,
                                                allow_null=True,
                                                help_text="铭牌监督员",
                                                required=False)
    supervisor = serializer.CharField(max_length=16,
                                      allow_null=True,
                                      help_text="监护人",
                                      required=False)
    supervisor_event = serializer.CharField(max_length=1024,
                                            required=False,
                                            allow_null=True,
                                            help_text="监护事件")
    wt_work_change = serializer.ListField(child=serializer.DictField(),
                                          allow_empty=True,
                                          allow_null=True,
                                          help_text="工作转移")

    def validate(self, attrs):
        if attrs.get("type") not in [0, 1]:
            raise serializer.ValidationError("工作票类型不对，没有%s类型工作票" %
                                             attrs.get("type"),
                                             code=PARAMETER_ERROR)
        customer = Customer.objects.filter(id=attrs.get("customer_id"),
                                           deleted=False).first()
        if not customer:
            raise serializer.ValidationError("客户%s不存在" %
                                             attrs.get("customer_id"),
                                             code=PARAMETER_ERROR)
        team = Team.objects.filter(id=attrs.get("team_id"),
                                   deleted=False).first()
        if not team:
            raise serializer.ValidationError("班组%s不存在" % attrs.get("team_id"),
                                             code=PARAMETER_ERROR)
        user = Users.objects.filter(id=attrs.get("person_liable_id")).first()
        if not user:
            raise serializer.ValidationError("人员%s不存在" %
                                             attrs.get("person_liable_id"),
                                             code=PARAMETER_ERROR)
        attrs["customer"] = customer
        attrs["team"] = team
        return attrs

    def create(self, validated_data):
        wt_safety_measure = validated_data.pop("wt_safety_measure", [])
        wt_person_changes = validated_data.pop("wt_person_changes", [])
        wt_work_record = validated_data.pop("wt_work_record", [])
        wt_child_ticket = validated_data.pop("wt_child_ticket", [])
        wt_work_change = validated_data.pop("wt_work_change", [])
        wt_contact = validated_data.pop("wt_contact", [])
        work_ticket = WorkTicket.objects.create(**validated_data)
        service = WorkTicketServer()
        # 添加安全措施
        service.add_safety_measure(wt_safety_measure, work_ticket.id)
        # 添加值班站和调度室的联系记录
        service.add_contact(wt_contact, work_ticket.id)
        # 添加人员变动信息
        service.add_wt_person_changes(wt_person_changes, work_ticket.id)
        # 每日开工和收工时间（使用一天的工作票不必填写）
        service.add_wt_work_record(wt_work_record, work_ticket.id)
        # 工作票子票
        service.add_wt_child_ticket(wt_child_ticket, work_ticket.id)
        # 工作地点转移
        service.add_wt_work_change(wt_work_change, work_ticket.id)
        return work_ticket


class OrderRecieveConfirmSerialzier(serializer.Serializer):
    def validate(self, attrs):
        if self.context.get("order").status != "waiting_dispatch":
            raise serializer.ValidationError("工单不是待接单状态", code=PARAMETER_ERROR)
        return attrs

    def update(self, instance, validated_data):
        instance.receiving_time = datetime.datetime.now()
        instance.status = "pending"
        instance.save()
        return instance


class OrderTransferSerializer(serializer.Serializer):
    content = serializer.CharField(required=True,
                                   allow_blank=False,
                                   allow_null=False)

    def update(self, instance, validated_data):
        request = self.context.get("request")
        user = Users.objects.filter(account=request.user).first()
        instance.status = "waiting_dispatch"
        instance.receiving_time = None
        instance.handler = None
        instance.team = None
        instance.transfer_reason = validated_data.get("content")
        instance.save()
        # 同步创建工作日志
        WorkLog.objects.create(task=instance.task,
                               content="{}因为{}进行转单".format(
                                   user.nickname,
                                   validated_data.get("content")))
        # 给调度发送站内消息

        return instance


class OrderSignInSerializer(serializer.Serializer):
    def update(self, instance, validated_data):
        instance.start_time = datetime.datetime.now()
        instance.save()
        return instance


class OrderHandlerSerializer(serializer.Serializer):
    problem = serializer.CharField(required=False,
                                   allow_null=True,
                                   allow_blank=True,
                                   help_text="事故经过及原因分析")
    describe = serializer.CharField(required=False,
                                    allow_null=True,
                                    allow_blank=True,
                                    help_text="事故描述")
    investigation = serializer.CharField(required=False,
                                         allow_null=True,
                                         allow_blank=True,
                                         help_text="事故排查")
    handle = serializer.CharField(required=False,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="处理")
    proposal = serializer.CharField(required=False,
                                    allow_null=True,
                                    allow_blank=True,
                                    help_text="反制措施及建议")
    is_finish = serializer.BooleanField(required=True,
                                        allow_null=False,
                                        help_text="是否完成任务")
    file = serializer.ListField(required=False,
                                allow_null=True,
                                allow_empty=True,
                                child=serializer.CharField())

    def create(self, validated_data):
        order = self.context.get("order")
        user = Users.objects.filter(account=self.context.get("user")).first()
        work_report = OrderReport.objects.create(
            order=order,
            problem=validated_data.get("problem"),
            describe=validated_data.get("describe"),
            investigation=validated_data.get("investigation"),
            handle=validated_data.get("handle"),
            proposal=validated_data.get("proposal"),
            operator=user,
            is_finish=validated_data.get("is_finish"))
        order.status = "completed"
        order.file = json.dumps(validated_data.get("file"), ensure_ascii=False)
        order.finish_time = datetime.datetime.now()
        order.conclusion = validated_data.get("handle")
        order.save()
        if validated_data.get("is_finish"):
            order.task.finished_tag = True
            order.save()
            order.task.save()
        WorkLog.objects.create(task=order.task,
                               content="工单{}已完成！".format(order.id))
        send_order_finish_message(order)
        return work_report


class MaterialInfoSerializer(serializer.ModelSerializer):
    name = serializer.CharField(required=True,
                                allow_blank=False,
                                allow_null=False)
    code = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    price = serializer.DecimalField(max_digits=12,
                                    decimal_places=2,
                                    required=False,
                                    allow_null=True)

    class Meta:
        model = Material
        fields = "__all__"

    def create(self, validated_data):
        material = Material.objects.create(name=validated_data.get("name"),
                                           code=validated_data.get("code"),
                                           price=validated_data.get("price"))
        return material

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name")
        instance.code = validated_data.get("code")
        instance.price = validated_data.get("price")
        instance.save()
        return instance


class OrderAddMaterialSerializer(serializer.Serializer):
    order_id = serializer.IntegerField(required=True, allow_null=False)
    material_id = serializer.IntegerField(
        required=True,
        allow_null=False,
    )
    number = serializer.IntegerField(required=False, allow_null=True)

    def validate(self, attrs):
        order = Order.objects.filter(id=attrs.get("order_id"),
                                     deleted=False).first()
        if not order:
            raise serializer.ValidationError("工单{}不存在".format(
                attrs.get("order_id")),
                code=PARAMETER_ERROR)

        material = Material.objects.filter(id=attrs.get("material_id"),
                                           deleted=False).first()
        if not material:
            raise serializer.ValidationError("物料{}不存在".format(
                attrs.get("material_id")),
                code=PARAMETER_ERROR)
        if attrs.get("number") and attrs.get("number") <= 0:
            raise serializer.ValidationError("数量要大于0")
        consumable_material = ConsumableMaterial.objects.filter(
            order=order, material=material, deleted=False).first()
        if consumable_material:
            attrs.update({"consumable_material": consumable_material})
        return attrs

    def create(self, validated_data):

        if validated_data.get("consumable_material"):
            consumable_material = validated_data.get("consumable_material")
            consumable_material.number += validated_data.get("number", 1)
            consumable_material.save()
        else:
            consumable_material = ConsumableMaterial.objects.create(
                order_id=validated_data.get("order_id"),
                material_id=validated_data.get("material_id"),
                number=validated_data.get("number", 1))
        return consumable_material


class ConsumableMaterialSerializer(serializer.ModelSerializer):
    order_id = serializer.SerializerMethodField()
    material = serializer.SerializerMethodField()

    def get_material(self, obj):
        return MaterialInfoSerializer(obj.material).data

    def get_order_id(self, obj):
        return obj.order.id if obj.order else None

    class Meta:
        model = ConsumableMaterial
        fields = ("id", "order_id", "number", "material")


class OrderWorkLogCreateSerializer(serializer.Serializer):
    time = serializer.DateTimeField(required=False, allow_null=True)
    content = serializer.CharField(required=False,
                                   allow_null=True,
                                   allow_blank=True)
    picture = serializer.ListField(required=False,
                                   allow_null=True,
                                   child=serializer.CharField())
    file = serializer.ListField(required=False,
                                allow_null=True,
                                child=serializer.CharField())
    file_title = serializer.ListField(required=False,
                                      allow_null=True,
                                      child=serializer.CharField())
    order_id = serializer.IntegerField(required=True, allow_null=False)

    def validate(self, attrs):
        order = Order.objects.filter(id=attrs.get("order_id")).first()
        if not order:
            raise serializer.ValidationError("工单{}不存在".format(
                attrs.get("order_id")),
                code=PARAMETER_ERROR)
        return attrs

    def create(self, validated_data):
        work_log = PowerLog.objects.create(
            order_id=validated_data.get("order_id"),
            time=validated_data.get("time"),
            content=validated_data.get("content"),
            picture=json.dumps(validated_data.get("picture"),
                               ensure_ascii=False),
            file=json.dumps(validated_data.get("file"), ensure_ascii=False),
            file_title=json.dumps(validated_data.get("file_title"),
                                  ensure_ascii=False))
        return work_log


class PowerLogInfoSerializer(serializer.ModelSerializer):
    def to_representation(self, instance):
        return {
            "id": instance.id,
            "time": instance.time,
            "content": instance.content,
            "picture": json.loads(instance.picture),
            "file": json.loads(instance.file),
            "file_title": json.loads(instance.file_title)
        }

    class Meta:
        model = PowerLog
        fields = ("id", "time", "content", "picture", "file", "file_title")


class OrderListSerializer(serializer.ModelSerializer):
    customer_name = serializer.SerializerMethodField()
    team_headman = serializer.SerializerMethodField()
    task_id = serializer.SerializerMethodField()
    task_type = serializer.SerializerMethodField()
    task_confirm = serializer.SerializerMethodField()
    task_status = serializer.SerializerMethodField()

    def get_task_status(self, obj):
        return obj.task.status if obj.task else None

    def get_task_confirm(self, obj):
        return obj.task.confirm if obj.task else None

    def get_task_type(self, obj):
        return obj.task.type if obj.task else None

    def get_task_id(self, obj):
        return obj.task.id if obj.task else None

    def get_team_headman(self, obj):
        return obj.team.team_headman.nickname \
            if obj.team and obj.team.team_headman else None

    def get_customer_name(self, obj):
        return obj.task.customer.name \
            if obj.task and obj.task.customer else None

    class Meta:
        model = Order
        fields = ("id", "name", "customer_name", "type", "team_headman",
                  "task_id", "task_type", "task_confirm", "status",
                  "task_status", "created_time")


class MaterialUpdateSerialzier(serializer.Serializer):
    number = serializer.IntegerField(required=True,
                                     allow_null=False,
                                     min_value=1)

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


class WorkTicketInfoSerializer(serializer.ModelSerializer):
    customer = serializer.SerializerMethodField()
    station = serializer.SerializerMethodField()
    person_liable = serializer.SerializerMethodField()
    issuer = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()
    wt_safety_measure = serializer.SerializerMethodField()
    wt_contact = serializer.SerializerMethodField()
    wt_person_changes = serializer.SerializerMethodField()
    wt_work_record = serializer.SerializerMethodField()
    wt_child_ticket = serializer.SerializerMethodField()
    the_end = serializer.SerializerMethodField()
    remarks = serializer.SerializerMethodField()
    check = serializer.SerializerMethodField()
    wt_work_change = serializer.SerializerMethodField()

    def get_customer(self, obj):
        return CustomerSerializer(obj.customer).data

    def get_station(self, obj):
        return StationSerializer(obj.station).data

    def get_person_liable(self, obj):
        return UsersLCSerializer(obj.person_liable).data

    def get_issuer(self, obj):
        return UsersLCSerializer(obj.issuer).data

    def get_team(self, obj):
        return TeamSerializer(obj.team).data

    def get_wt_safety_measure(self, obj):
        sql = ("""
            select id,content,type,content_done,
                supplement_content,supplement_content_done
            from wt_safety_measure
            where work_ticket={}""".format(obj.id))

        return BaseConnection().query(sql)

    def get_wt_contact(self, obj):
        sql = """
        select id,time,content,leader,issuer
        from wt_contact
        where work_ticket={}""".format(obj.id)
        return BaseConnection().query(sql)

    def get_wt_person_changes(self, obj):
        sql = """select id,person_add,add_time,add_issuer,
        person_remove,remove_issuer,remove_time
        from wt_person_changes
        where work_ticket={}""".format(obj.id)
        return BaseConnection().query(sql)

    def get_wt_work_record(self, obj):
        sql = """
        select id,end_time,end_leader,end_issuer,
        start_time,start_leader,start_issuer
        from wt_work_record
        where work_ticket={}""".format(obj.id)
        return BaseConnection().query(sql)

    def get_wt_work_change(self, obj):
        sql = """
                select id,addr,start_time,end_time,leader
                from wt_work_change
                where work_ticket={}""".format(obj.id)
        return BaseConnection().query(sql)

    def get_wt_child_ticket(self, obj):
        sql = """
        select id,code,team,leader,issue_time,end_time
         from wt_child_ticket
        where work_ticket={}""".format(obj.id)
        return BaseConnection().query(sql)

    def get_the_end(self, obj):
        the_end = obj.the_end.replace("[", "").replace("]", "").replace(
            "'", "").split(",") if obj.the_end else None
        return the_end

    def get_remarks(self, obj):
        remarks = obj.remarks.replace("[", "").replace("]", "").replace(
            "'", "").split(",") if obj.remarks else None
        return remarks

    def get_check(self, obj):
        checked = obj.checked.replace("[", "").replace("]", "").replace(
            "'", "").split(",") if obj.checked else None
        return checked

    class Meta:
        model = WorkTicket
        fields = ("id", "order_id", "code", "type", "customer", "station",
                  "person_liable", "issuer", "issue_time", "team", "addr",
                  "job_content", "attention", "work_conditions",
                  "plan_start_time", "plan_end_time", "wt_safety_measure",
                  "supplement", "file", "person_num", "person_name",
                  "wt_contact", "wt_person_changes", "wt_work_record",
                  "wt_child_ticket", "finished_time", "the_end", "remarks",
                  "check", "created_time", "wt_work_change",
                  "supervisor_event", "supervisor", "nameplate_supervisor",
                  "nameplate_operator", "handover_confirm", "delay_date",
                  "allower", "allow_start_time", "leade_change_date",
                  "leader_change_issuer", "last_leader", "delay_licensor",
                  "delay_leader", "supplement_safety_measure")


class CustomerSerializer(serializer.ModelSerializer):
    class Meta:
        model = Customer
        fields = ("id", "name")


class StationSerializer(serializer.ModelSerializer):
    class Meta:
        model = PowerStation
        fields = ("id", "name")


class OrderArriveSerializer(serializer.Serializer):
    def update(self, instance, validated_data):
        instance.start_time = datetime.datetime.now()
        instance.save()
        WorkLog.objects.create(
            task=instance.task,
            content="班组{}已到达现场".format(
                instance.team.name if instance.team else None))
        return instance


class OrderStatisticSerializer(serializer.Serializer):
    finish_num = serializer.SerializerMethodField()
    transfer_status = serializer.SerializerMethodField()
    on_time = serializer.SerializerMethodField()
    order_status = serializer.SerializerMethodField()

    def get_order_status(self, obj):
        orders = Order.objects.filter(team=obj).values("type").annotate(
            count=Count("id")).values("type", "count")
        return orders

    def get_finish_num(self, obj):
        count = Order.objects.filter(status="completed", team=obj).count()
        return count

    def get_transfer_status(self, obj):
        request = self.context.get("request")
        user = Users.objects.filter(account=request.user).first()
        transfer_num = WorkLog.objects.filter(
            content__startswith=user.nickname, content__endswith="转单").count()
        count = Order.objects.filter(team=obj).count()
        return transfer_num / (count + transfer_num) if (count +
                                                         transfer_num) else 0

    def get_on_time(self, obj):
        rr_count = Order.objects.filter(
            team=obj,
            type__in=["rush_to_repair", "demand_declaration"],
            start_time__isnull=False,
            start_time__lte=F("created_time") +
                            datetime.timedelta(hours=1)).count()
        other = Order.objects.filter(
            team=obj,
            type__in=["electrical_testing", "power_construction"],
            commencement_date__isnull=False,
            start_time__isnull=False,
            start_time__lte=F("commencement_date") +
                            datetime.timedelta(hours=1)).count()
        count = Order.objects.filter(team=obj).count()
        return (rr_count + other) / count if count else 0

    class Meta:
        model = Team
        fields = ("finish_num", "transfer_status", "on_time", "order_status")


class OrderReceiveSerializer(serializer.Serializer):
    def update(self, instance, validated_data):
        instance.receiving_time = datetime.datetime.now()
        instance.save()
        instance.task.status = "in_process"
        instance.task.save()
        return instance


class OrderSelfAssignSerializer(serializer.Serializer):
    team_id = serializer.IntegerField(required=True, allow_null=False)

    def validate(self, attrs):
        team = Team.objects.filter(id=attrs.get("team_id")).first()
        if not team:
            raise serializer.ValidationError("班组%s不存在" % attrs.get("team_id"))
        return attrs

    def update(self, instance, validated_data):
        instance.team_id = validated_data.get("team_id")
        instance.status = "pending"
        instance.receiving_time = datetime.datetime.now()
        instance.save()
        return instance
