import datetime
import json
from django.db import transaction
from django.db.models import F, Sum
from rest_framework import serializers as serializer
from rest_framework.serializers import ValidationError

from common.utils.service_code import PARAMETER_ERROR
from console.customer.models import Customer, CustomerAdmin
from console.equipment.models import Equipment
from console.powerstation.models import PowerStation
from console.task.models import Task

from console.order.models import Order
from console.team.models import Team

from console.contract.models import Contract

from console.task.utils import get_serial_number

from console.electricityuser.models import ElectricityUser

from console.order.models import OrderReport

from common.notify.message import MessageObject

from console.task.models import WorkLog

from console.task.services import send_message

from console.task.services import create_order_notify

from common.third_party_api.amap.openapi import AmapApi

from common.accounts.models import Users, Enterprise
from console.powerstation.models import Transformer

from console.task.services import get_customer_info

from console.order.models import ConsumableMaterial

from console.order.services import send_order_assign_message

from console.equipment.models import EquipmentData

TYPE_NAME_MAP = {
    "rush_to_repair": "RR",
    "power_construction": "PC",
    "electrical_testing": "ET",
    "demand_declaration": "DD"
}

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


class TaskCreateSerializer(serializer.Serializer):
    customer_id = serializer.IntegerField(allow_null=True,
                                          required=False,
                                          help_text="客户id")
    ele_user_id = serializer.IntegerField(required=False,
                                          allow_null=True,
                                          help_text="户号id")
    name = serializer.CharField(allow_null=True,
                                required=False,
                                help_text="名称",
                                allow_blank=True)
    type = serializer.CharField(allow_null=False,
                                required=True,
                                help_text="任务类型")
    content = serializer.CharField(allow_null=True,
                                   required=False,
                                   allow_blank=True,
                                   help_text="任务描述")
    person = serializer.CharField(allow_null=True,
                                  required=False,
                                  allow_blank=True,
                                  help_text="联系人")
    phone = serializer.CharField(allow_null=True,
                                 required=False,
                                 allow_blank=True,
                                 help_text="联系人手机号码")
    addr = serializer.CharField(allow_null=True,
                                required=False,
                                help_text="地址",
                                allow_blank=True)
    file = serializer.ListField(required=False,
                                help_text="现场图片",
                                child=serializer.CharField(required=False))
    station_id = serializer.IntegerField(required=False,
                                         help_text="电站id",
                                         allow_null=True)
    equipment_id = serializer.IntegerField(required=False,
                                           help_text="设备id",
                                           allow_null=True)
    subtype = serializer.CharField(required=False, help_text="任务子类型")
    team_id = serializer.IntegerField(required=False,
                                      allow_null=True,
                                      help_text="服务班组")
    customer = serializer.CharField(allow_blank=True,
                                    required=False,
                                    allow_null=True)
    service_staff = serializer.IntegerField(required=False, allow_null=True)
    source = serializer.CharField(required=False,
                                  allow_blank=True,
                                  allow_null=True)
    dispatcher = serializer.CharField(required=False,
                                      allow_null=True,
                                      allow_blank=True)
    repair_time = serializer.DateTimeField(required=False, allow_null=True),
    remarks = serializer.CharField(required=False,
                                   allow_blank=True,
                                   allow_null=True)

    def validate(self, attrs):
        if attrs.get("customer_id"):
            customer = Customer.objects.filter(id=attrs.get("customer_id"),
                                               deleted=False).first()
            if not customer:
                raise ValidationError("客户%s不存在" % attrs.get("customer_id"),
                                      code=PARAMETER_ERROR)
        if not attrs.get("customer_id") and not attrs.get("customer"):
            raise ValidationError("请填写客户信息！")
        if attrs.get("station_id"):
            station = PowerStation.objects.filter(id=attrs.get("station_id"),
                                                  deleted=False).first()
            if not station:
                raise ValidationError("电站%s不存在" % attrs.get("station_id"),
                                      code=PARAMETER_ERROR)
        if attrs.get("equipment_id"):
            equipment = Equipment.objects.filter(id=attrs.get("equipment_id"),
                                                 deleted=False).first()
            if not equipment:
                raise ValidationError("设备%s不存在" % attrs.get("equipment_id"),
                                      code=PARAMETER_ERROR)
        if attrs.get("type") not in [
            "rush_to_repair", "power_construction", "electrical_testing",
            "demand_declaration"
        ]:
            raise ValidationError("任务类型不对")
        if attrs.get("team_id"):
            team = Team.objects.filter(id=attrs.get("team_id")).first()
            if not team:
                raise ValidationError("班组%s不存在" % attrs.get("team_id"))
            attrs["team"] = team
        if attrs.get("service_staff"):
            user = Users.objects.filter(id=attrs.get("service_staff")).first()
            if not user:
                raise ValidationError("客户代表不存在！")

        return attrs

    def create(self, validated_data):

        request = self.context.get("request")
        year = datetime.datetime.now().year
        month = datetime.datetime.now().month
        count = Task.objects.filter(created_time__year=year,
                                    created_time__month=month,
                                    type=validated_data.get("type")).count()

        customer_data = validated_data.get("customer")
        if customer_data:
            enterprise = Enterprise.objects.create(
                name=customer_data, address=validated_data.get("addr"))
            customer = Customer.objects.create(
                name=customer_data,
                enterprise=enterprise,
                type=2,
                service_enterprise=request.data.get("service_enterprise"),
                service_staff_id=validated_data.get("service_staff"))
        location = AmapApi().geo(address=validated_data.get("addr")) \
            if validated_data.get("addr") else None
        task = Task.objects.create(
            name=TYPE_NAME_MAP.get(validated_data.get("type")) +
                 datetime.datetime.now().strftime("%Y%m") + str(count + 1).zfill(5),
            customer_id=validated_data.get("customer_id")
            if validated_data.get("customer_id") else customer.id,
            station_id=validated_data.get("station_id"),
            equipment_id=validated_data.get("equipment_id"),
            type=validated_data.get("type"),
            subtype=validated_data.get("subtype"),
            status=("waiting_dispatch" if validated_data.get("type") not in [
                "power_construction", "electrical_testing"
            ] else "waiting_plan"),
            describe=validated_data.get("content"),
            contacts=validated_data.get("person"),
            contacts_phone=validated_data.get("phone"),
            addr=validated_data.get("addr"),
            file=json.dumps(validated_data.get("file"), ensure_ascii=False),
            number=(datetime.datetime.now().date().strftime("%Y%m%d") +
                    str(get_serial_number()).zfill(5)),
            location=location.get('geocodes')[0]["location"]
            if location and location.get('geocodes') else None,
            created_time=validated_data.get("repair_time")
            if validated_data.get("repair_time") else datetime.datetime.now(),
            dispatcher=validated_data.get("dispatcher"),
            source=validated_data.get("source"),
            remarks=validated_data.get("remarks"),
            ele_user=validated_data.get("ele_user_id"))
        # 发送通知
        send_message(task, request.user)
        # 创建工单
        team = Team.objects.filter(id=validated_data.get("team_id"),
                                   deleted=False).first()

        order = Order.objects.create(
            task=task,
            name=task.name + "-" + "01",
            team_id=validated_data.get("team_id"),
            type=validated_data.get("type"),
            status="pending"
            if validated_data.get("team_id") else "waiting_dispatch",
            # receiving_time=datetime.datetime.now(),
            commencement_date=task.plan_date
            if validated_data.get("type") != "rush_to_repair" else
            datetime.datetime.now())
        if team:
            WorkLog.objects.create(task=task,
                                   content="{}创建了工单并派发给了班组{}({})".format(
                                       request.user.username,
                                       validated_data.get("team_id"),
                                       validated_data.get("team").name))
            create_order_notify(
                **{
                    "user": request.user,
                    "order": order,
                    "team_id": validated_data.get("team_id")
                })
            task.status = "pending"
            task.save()
            # 发送短信通知
            sms_obj = MessageObject()
            phone_list = [team.team_headman.phone] if team.team_headman else []
            phone_list += [item.phone for item in team.member.all()]
            params = [
                order.created_time.strftime("%Y-%m-%d %H:%M:%S"),
                ORDER_TYPE_MAP.get(order.type)
            ]
            phone_list = list(filter(None, phone_list))
            sms_obj.send_sms_multi(phone_list, 781473, params)
            # 给客户经理发送短信
            send_order_assign_message(order, team)
        return task


class OrderCreateSerializer(serializer.Serializer):
    task_id = serializer.IntegerField(required=True,
                                      allow_null=False,
                                      help_text="任务id")
    team_id = serializer.IntegerField(required=True,
                                      allow_null=False,
                                      help_text="班组id")
    type = serializer.CharField(required=True,
                                allow_null=False,
                                help_text="类型")

    def validate(self, attrs):
        task = Task.objects.filter(id=attrs.get("task_id")).first()
        if not task:
            raise ValidationError("任务%s不存在" % attrs.get("task_id"),
                                  code=PARAMETER_ERROR)
        if task.status not in ["waiting_dispatch", "in_process"]:
            raise ValidationError("当前任务流程不能派单", code=PARAMETER_ERROR)
        if task.status in ["completed", "closed"]:
            raise ValidationError("任务已完成，不需要再派单")
        team = Team.objects.filter(id=attrs.get("team_id"),
                                   deleted=False).first()
        if not team:
            raise ValidationError("班组%s不存在" % attrs.get("team_id"),
                                  code=PARAMETER_ERROR)
        # order = Order.objects.filter(task=task).exclude(
        #     status__contains="completed").first()
        # if order:
        #     raise ValidationError("已经存在正在施工中的工单，请等待该工单完成")
        attrs["task"] = task
        count = Order.objects.filter(task=task).count()
        attrs["order_count"] = count
        attrs["team"] = team
        return attrs

    @transaction.atomic()
    def create(self, validated_data):
        point = transaction.savepoint()
        try:
            request = self.context.get("request")
            order = Order.objects.create(
                task_id=validated_data.get("task_id"),
                name=validated_data.get("task").name + "-" +
                     str(validated_data.get("order_count")).zfill(2),
                team_id=validated_data.get("team_id"),
                type=validated_data.get("type"),
                status="pending",
                # receiving_time=datetime.datetime.now(),
                commencement_date=validated_data.get("task").plan_date
                if validated_data.get("type") != "rush_to_repair" else
                datetime.datetime.now())
            task = validated_data.get("task")
            task.status = "in_process"
            task.save()
            # 添加工作日志
            WorkLog.objects.create(
                task_id=validated_data.get("task_id"),
                content="{}发起工单并派单给班组{}".format(
                    request.user.username,
                    str(validated_data.get("team_id")) +
                    "({})".format(validated_data.get("team").name)))
            # 发送短信通知
            sms_obj = MessageObject()
            phone_list = [
                member.phone
                for member in validated_data.get("team").member.all()
            ]
            phone_list.append(validated_data.get("team").team_headman.phone)
            params = [
                order.commencement_date.strftime("%Y-%m-%d %H:%M:%S"),
                ORDER_TYPE_MAP.get(validated_data.get("type"))
            ]
            # 过滤空数据
            phone_list = list(filter(None, phone_list))
            sms_obj.send_sms_multi(phone_list, 781473, params)
            # 发送站内消息通知
            create_order_notify(
                **{
                    "user": request.user,
                    "order": order,
                    "team_id": validated_data.get("team_id")
                })
            transaction.savepoint_commit(point)
            return order
        except Exception as e:
            transaction.savepoint_rollback(point)
            raise ValidationError(e)


class TaskRelateContractSerializer(serializer.Serializer):
    contract_id = serializer.IntegerField(required=True,
                                          allow_null=False,
                                          help_text="合同id")

    def validate(self, attrs):
        contract = Contract.objects.filter(id=attrs.get("contract_id")).first()
        if not contract:
            raise ValidationError("合同%s不存在" % attrs.get("contract_id"),
                                  code=PARAMETER_ERROR)
        return attrs

    def update(self, instance, validated_data):
        request = self.context.get("request")
        contract = Contract.objects.filter(
            id=validated_data.get("contract_id")).first()
        instance.contract = contract
        instance.save()
        # 添加工作日志
        WorkLog.objects.create(task=instance,
                               content="{}把任务关联合同，合同id为{}".format(
                                   request.user.username,
                                   validated_data.get("contract_id")))
        return instance


class TaskCloseSerializer(serializer.Serializer):
    # def validate(self, attrs):
    #     data = self.initial_data
    #     order = Order.objects.filter(task_id=data.get("task_id")).exclude(
    #         status="completed")
    #     if order:
    #         raise ValidationError("任务还有未完成的工单，不能关闭！")
    #     return attrs

    def update(self, instance, validated_data):
        request = self.context.get("request")
        instance.status = "completed"
        instance.finish_time = datetime.datetime.now()
        instance.save()
        # 添加工作日志
        WorkLog.objects.create(task=instance,
                               content="{}关闭任务".format(request.user.username))
        return instance


class ContractInfoSerializer(serializer.ModelSerializer):
    class Meta:
        model = Contract
        fields = ("id", "code")


class CustomerInfoSerializer(serializer.ModelSerializer):
    phone = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()
    customer_admin = serializer.SerializerMethodField()
    real_capacity = serializer.SerializerMethodField()
    total_capacity = serializer.SerializerMethodField()
    transformer_count = serializer.SerializerMethodField()
    service_staff = serializer.SerializerMethodField()
    contract = serializer.SerializerMethodField()
    type = serializer.SerializerMethodField()

    def get_type(self, obj):
        return obj.type.split(",") if obj.type else None

    def get_service_staff(self, obj):
        return obj.service_staff.nickname if obj.service_staff else None

    def get_real_capacity(self, obj):
        ele_user = ElectricityUser.objects.filter(
            customer=obj, deleted=False).values_list("number", flat=True)
        if not ele_user:
            return 0
        item = Transformer.objects.filter(ele_number__in=ele_user).aggregate(
            real_sum=Sum("real_capacity"))
        return item.get("real_sum")

    def get_total_capacity(self, obj):
        ele_user = ElectricityUser.objects.filter(
            customer=obj, deleted=False).values_list("number", flat=True)
        if not ele_user:
            return 0
        item = Transformer.objects.filter(ele_number__in=ele_user).aggregate(
            real_sum=Sum("capacity"))
        return item.get("real_sum")

    def get_transformer_count(self, obj):
        ele_user = ElectricityUser.objects.filter(
            customer=obj, deleted=False).values_list("number", flat=True)
        if not ele_user:
            return 0
        return Transformer.objects.filter(ele_number__in=ele_user).count()

    def get_phone(self, obj):
        users = CustomerAdmin.objects.filter(customer=obj).first()
        return users.user.phone if users and users.user else None

    def get_customer_admin(self, obj):
        customer_admin = obj.customer_admin.filter(deleted=False).values()
        admin_ids = customer_admin.values_list("user_id", flat=True)
        return Users.objects.filter(deleted=False, id__in=admin_ids).values(
            "id", "nickname", "phone", username=F("account__username"))

    def get_team(self, obj):
        team = Team.objects.filter(leader=obj.service_staff, deleted=False)
        return [{
            "id": item.id,
            "name": item.name,
            "team_headman": item.team_headman.nickname,
            "phone": item.team_headman.phone,
            "type": item.type
        } for item in team] if team else None

    def get_contract(self, obj):
        return Contract.objects.filter(customer=obj,
                                       type__in=[1, 2, 4, 5, 13]).values(
            "id", "code", "entry_date",
            "effective_date", "end_date",
            "closed_date", "type")

    class Meta:
        model = Customer
        fields = ("id", "name", "type", "phone", "customer_admin", "team",
                  "real_capacity", "total_capacity", "transformer_count",
                  "service_staff", "contract")


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


class EquipmentSerializer(serializer.ModelSerializer):
    line_type = serializer.SerializerMethodField()
    impedance = serializer.SerializerMethodField()
    oil_type = serializer.SerializerMethodField()
    switch_position = serializer.SerializerMethodField()
    test_reason = serializer.SerializerMethodField()
    factory = serializer.SerializerMethodField()

    def get_factory(self, obj):
        return obj.manufacturer

    def get_test_reason(self, obj):
        return ""

    def get_impedance(self, obj):
        return ""

    def get_oil_type(self, obj):
        return ""

    def get_switch_position(self, obj):
        return ""

    def get_line_type(self, obj):
        return "None"

    class Meta:
        model = EquipmentData
        fields = ("id", "name", "factory", "voltage", "electricity",
                  "production_code", "transformer_capacity", "line_type",
                  "production_date", "impedance", "oil_type",
                  "switch_position", "test_reason", "model", "type")


class ElectricityUserSerialzier(serializer.ModelSerializer):
    line_type = serializer.SerializerMethodField()

    def get_line_type(self, obj):
        return "电缆"

    class Meta:
        model = ElectricityUser
        fields = ("id", "number", "householder", "voltage_level",
                  "transformer_capacity", "line_type")


class TaskListSerializer(serializer.ModelSerializer):
    customer = serializer.SerializerMethodField()
    order_num = serializer.SerializerMethodField()
    contract = serializer.SerializerMethodField()
    station = serializer.SerializerMethodField()
    electricity_user = serializer.SerializerMethodField()

    def get_electricity_user(self, obj):
        ele_user = ElectricityUser.objects.filter(id=obj.ele_user).first()
        return ele_user.number if ele_user else None

    def get_station(self, obj):
        return obj.station.name if obj.station else None

    def get_customer(self, obj):
        return {
            "id":
                obj.customer.id,
            "name":
                obj.customer.name,
            "type":
                obj.customer.type.split(",") if obj.customer.type else [],
            "server_staff":
                obj.customer.service_staff.nickname
                if obj.customer.service_staff else None
        } if obj.customer else None

    def get_order_num(self, obj):
        orders = Order.objects.filter(task=obj)
        return {
            "count": orders.count(),
            "order_list":
                [order.id for order in orders] if len(orders) else []
        }

    def get_contract(self, obj):
        return {
            "id": obj.contract.id,
            "code": obj.contract.code
        } if obj.contract else None

    class Meta:
        model = Task
        fields = (
            "id",
            "name",
            "customer",
            "type",
            "status",
            "order_num",
            "contract",
            "created_time",
            "confirm",
            "describe",
            "contacts",
            "contacts_phone",
            "finished_tag",
            "addr",
            "location",
            "station",
            "electricity_user",
            "finish_time",
        )


class TaskInfoSerializer(serializer.ModelSerializer):
    customer = serializer.SerializerMethodField()
    station = serializer.SerializerMethodField()
    equipments = serializer.SerializerMethodField()
    contract = serializer.SerializerMethodField()
    order_num = serializer.SerializerMethodField()
    relate_order = serializer.SerializerMethodField()
    electricity_user = serializer.SerializerMethodField()
    person = serializer.SerializerMethodField()
    problem = serializer.SerializerMethodField()
    handle = serializer.SerializerMethodField()
    proposal = serializer.SerializerMethodField()
    work_log = serializer.SerializerMethodField()
    file = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()

    def get_team(self, obj):
        order = Order.objects.filter(
            task=obj).order_by("-created_time").first()
        return {
            "id": order.team.id,
            "name": order.team.name,
            "team_headman": order.team.team_headman.nickname,
            "phone": order.team.team_headman.phone
        } if order and order.team else None

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

    def get_work_log(self, obj):
        work_log = WorkLog.objects.filter(task=obj)
        return WorkLogSerializer(work_log, many=True).data

    def get_proposal(self, obj):
        order = Order.objects.filter(task=obj).order_by("created_time").first()
        order_record = OrderReport.objects.filter(order=order).first()
        return order_record.proposal if order_record else None

    def get_handle(self, obj):
        order = Order.objects.filter(task=obj).order_by("created_time").first()
        order_record = OrderReport.objects.filter(order=order).first()
        return order_record.handle if order_record else None

    def get_problem(self, obj):
        order = Order.objects.filter(task=obj).order_by("created_time").first()
        order_record = OrderReport.objects.filter(order=order).first()
        return order_record.problem if order_record else None

    def get_person(self, obj):
        order = Order.objects.filter(task=obj).exclude(
            status="completed").prefetch_related("team").first()
        if not order:
            return
        return {
            "nickname": order.team.team_headman.nickname,
            "phone": order.team.team_headman.phone
        } if order.team else None

    def get_electricity_user(self, obj):
        ele_user = ElectricityUser.objects.filter(id=obj.ele_user).first()
        return {
            "number": ele_user.number,
            "transformer_capacity": ele_user.transformer_capacity,
            "real_capacity": ele_user.real_capacity,
            "voltage_level": ele_user.voltage_level,
            "line_type": None
        } if ele_user else None

    def get_customer(self, obj):
        return get_customer_info(obj.customer.id, obj.ele_user)

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

    def get_equipments(self, obj):
        return EquipmentSerializer(obj.equipment.equipment_data).data if obj.equipment else None

    def get_contract(self, obj):
        return ContractInfoSerializer(obj.contract).data

    def get_order_num(self, obj):
        orders = Order.objects.filter(task=obj)
        return {
            "count": orders.count(),
            "order_list":
                [order.id for order in orders] if len(orders) else []
        }

    def get_relate_order(self, obj):
        orders = Order.objects.filter(task=obj)
        return [order.id for order in orders] if orders.count() else []

    class Meta:
        model = Task
        fields = ("id", "name", "customer", "type", "station", "equipments",
                  "subtype", "reason", "status", "describe", "contacts",
                  "contacts_phone", "addr", "is_cost", "contract", "file",
                  "finished_tag", "confirm", "order_num", "relate_order",
                  "number", "person", "created_time", "problem", "handle",
                  "proposal", "plan_date", "work_log", "team", "location",
                  "dispatcher", "source", "remarks", "electricity_user",
                  "score", "appraise", "appraise_time")


class TaskPlanDateSerializer(serializer.Serializer):
    plan_date = serializer.DateField(required=True, allow_null=False)

    def validate(self, attrs):
        if self.context.get("task").status != "waiting_plan":
            raise ValidationError("该任务现在不需要排期", code=PARAMETER_ERROR)
        return attrs

    def update(self, instance, validated_data):
        instance.plan_date = validated_data.get("plan_date")
        instance.status = "waiting_confirm"
        instance.save()
        # 创建任务日志
        WorkLog.objects.create(task=instance,
                               content="%s对任务进行排期，计划日期为%s" %
                                       (self.context.get("request").user.username,
                                        validated_data.get("plan_date")))
        return instance


class TaskPlanCheckSerializer(serializer.Serializer):
    result = serializer.BooleanField(required=True, allow_null=False)
    reason = serializer.CharField(required=False,
                                  allow_null=True,
                                  allow_blank=True)

    def validate(self, attrs):
        if self.context.get("task").status != "waiting_confirm":
            raise ValidationError("该任务现在不需要确认排期", code=PARAMETER_ERROR)
        return attrs

    def update(self, instance, validated_data):
        # 排期通过
        if validated_data.get("result"):
            instance.status = "waiting_dispatch"
        # 被驳回
        else:
            instance.status = "waiting_plan"
            instance.plan_date = None
        instance.remarks = validated_data.get("reason")
        instance.save()
        # 创建任务日志
        WorkLog.objects.create(
            task=instance,
            content="%s审核任务排期，审核结果为%s" %
                    (self.context.get("request").user.username,
                     ("通过  " if validated_data.get("result") else "不通过  ") +
                     validated_data.get("reason", '')))
        return instance


class TaskConfirmSerializer(serializer.Serializer):
    def update(self, instance, validated_data):
        instance.confirm = True
        instance.save()
        # 创建任务日志
        WorkLog.objects.create(task=instance, content="客户确认任务完成")
        return instance


class WorkLogSerializer(serializer.ModelSerializer):
    class Meta:
        model = WorkLog
        fields = ("id", "content", "created_time")


class TaskExportSerializer(serializer.ModelSerializer):
    date = serializer.SerializerMethodField()
    contacts = serializer.SerializerMethodField()
    create_time = serializer.SerializerMethodField()
    assign_time = serializer.SerializerMethodField()
    arrive_time = serializer.SerializerMethodField()
    finish_time = serializer.SerializerMethodField()
    customer = serializer.SerializerMethodField()
    service_staff = serializer.SerializerMethodField()
    customer_type = serializer.SerializerMethodField()
    team_headman = serializer.SerializerMethodField()
    add_user = serializer.SerializerMethodField()
    result = serializer.SerializerMethodField()
    equipment = serializer.SerializerMethodField()
    customer_had = serializer.SerializerMethodField()

    def get_customer_had(self, obj):
        return

    def get_equipment(self, obj):
        order = Order.objects.filter(task=obj, deleted=False)
        metarial = ConsumableMaterial.objects.filter(order__in=order)
        result = ""
        for item in metarial:
            result += "{} {} /n".format(item.material.name, item.number)
        return result

    def get_result(self, obj):
        order = Order.objects.filter(
            task=obj, deleted=False).order_by("-created_time").first()
        order_log = OrderReport.objects.filter(order=order).first()
        return order_log.handle if order_log else None

    def get_add_user(self, obj):
        order = Order.objects.filter(
            deleted=False, task=obj).order_by("created_time").first()
        if not order or not order.team:
            return
        member = order.team.member.all() if order.team.member else []
        return " ".join([item.nickname for item in member])

    def get_team_headman(self, obj):
        order = Order.objects.filter(
            deleted=False, task=obj).order_by("created_time").first()
        if not order or not order.team:
            return
        return order.team.team_headman.nickname \
            if order.team.team_headman else None

    def get_customer_type(self, obj):
        if not obj.customer:
            return
        if not obj.customer.type:
            return "非托管"

        return "托管" if "1" in obj.customer.type.split(",") else "非托管"

    def get_service_staff(self, obj):
        if not obj.customer:
            return
        return obj.customer.service_staff.nickname if \
            obj.customer.service_staff else None

    def get_customer(self, obj):
        return obj.customer.name if obj.customer else None

    def get_finish_time(self, obj):
        order = Order.objects.filter(
            deleted=False, task=obj).order_by("created_time").first()
        if not order:
            return
        return order.finish_time.strftime("%H:%M:%S") \
            if order.finish_time else None

    def get_arrive_time(self, obj):
        order = Order.objects.filter(
            deleted=False, task=obj).order_by("created_time").first()
        if not order:
            return
        return order.start_time.strftime("%H:%M:%S") \
            if order.start_time else None

    def get_assign_time(self, obj):
        order = Order.objects.filter(
            deleted=False, task=obj).order_by("created_time").first()
        if not order:
            return
        return order.created_time.strftime("%H:%M:%S")

    def get_create_time(self, obj):
        return obj.created_time.strftime("%H:%M:%S")

    def get_date(self, obj):
        return obj.created_time.date()

    def get_contacts(self, obj):
        if not obj.contacts_phone:
            return obj.contacts
        if not obj.contacts:
            return "现场联系人  " + obj.contacts_phone
        return obj.contacts + "  " + obj.contacts_phone

    class Meta:
        model = Task
        fields = ("id", "name", "dispatcher", "source", "date", "contacts",
                  "create_time", "assign_time", "arrive_time", "finish_time",
                  "customer", "addr", "service_staff", "customer_type",
                  "describe", "team_headman", "add_user", "result",
                  "equipment", "customer_had", "remarks")


class TaskEditSerializer(serializer.Serializer):
    describe = serializer.CharField(help_text="任务描述", allow_null=True)
    contacts = serializer.CharField(max_length=32,
                                    help_text="联系人",
                                    allow_null=True)
    contacts_phone = serializer.CharField(max_length=32,
                                          help_text="联系人电话",
                                          allow_null=True)
    remarks = serializer.CharField(allow_blank=True,
                                   allow_null=True,
                                   required=False)

    def update(self, instance, validated_data):
        instance.describe = validated_data.get("describe")
        instance.contacts = validated_data.get("contacts")
        instance.contacts_phone = validated_data.get("contacts_phone")
        instance.remarks = validated_data.get("remarks")
        instance.save()
        return instance


class TaskEvaluateSerializer(serializer.Serializer):
    score = serializer.FloatField(required=False, allow_null=True)
    appraise = serializer.CharField(required=False, allow_null=True, allow_blank=True)

    def update(self, instance, validated_data):
        instance.score = validated_data.get("score")
        instance.appraise = validated_data.get("appraise")
        instance.appraise_time = datetime.datetime.now()
        return instance
