# coding=utf-8
from django.conf import settings
from rest_framework import serializers

from apps.tenant.inspection_order.models import InspectionOrder
from apps.tenant.repair_order.models import RepairOrder
from apps.upload.serializers import UploadSerializer
from utils.serializersfield import DelayTimeCharField
from utils.exceptions import CustomError


class InspectionOrderDetailSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    user_name = serializers.CharField(source='user.employee.name', read_only=True)
    user_tel = serializers.CharField(source='user.employee.tel', read_only=True)
    images = serializers.SerializerMethodField()
    repair_type_text = serializers.CharField(source='repair_type.name', read_only=True)
    create_at = DelayTimeCharField(source='create_time', read_only=True)

    def get_images(self, obj):
        return UploadSerializer(obj.images, many=True).data

    class Meta:
        model = InspectionOrder
        fields = '__all__'


class InspectionOrderListSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    images = serializers.SerializerMethodField()
    repair_type_text = serializers.CharField(source='repair_type.name', read_only=True)
    create_at = DelayTimeCharField(source='create_time', read_only=True)

    def get_images(self, obj):
        return UploadSerializer(obj.images, many=True).data

    class Meta:
        model = InspectionOrder
        fields = '__all__'


class InspectionOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = InspectionOrder
        fields = ('id', 'device_id',  'device_name', 'device_address', 'problem', 'repair_type')

    def create(self, validated_data):
        # 巡检结果
        inspection_result = str(self.initial_data['inspection_result'])
        device = None
        if 'device' in self.initial_data:
            device = self.initial_data['device']
        if inspection_result == '0':
            # 巡检状态如果为正常，判断当前教室是否还存有未完成保修的工单
            repair_orders = RepairOrder.objects.filter(device_address=self.initial_data['device_address'],
                                                       device_name=self.initial_data['device_name'],
                                                       device=device,
                                                       status__in=[settings.NOT_CHECKED, settings.CHECKED,
                                                                   settings.DISPATCH, settings.HANG_UP])
            if repair_orders:
                raise CustomError('该地区还存在未完成的报修！')

            # 状态保存为正常
            validated_data['status'] = InspectionOrder.NOT_REPAIR
        if 'images' in self.initial_data:
            validated_data['images'] = self.initial_data['images'].split(',')
        user = self.context['request'].user
        validated_data['user'] = user
        validated_data['tenant'] = user.employee.tenant
        validated_data['device'] = device
        instance = super(InspectionOrderSerializer, self).create(validated_data)
        instance.no = instance.get_no()
        instance.save()

        # 点维修 转到报销里面，并自动派单给当前人，报销单状态直接是已派单，
        if inspection_result == '1':
            # 转报修
            repair_order = instance.turn_repair(user)
            # 自动派单
            repair_order.dispatch_repair_order(user, user.id)

        return instance
