
from wsgiref.validate import validator
from apps.hrm.serializers import EmployeeSimpleSerializer
from apps.system.models import Dept
from apps.utils.fields import MyFilePathField
from apps.utils.serializers import CustomModelSerializer
from apps.utils.tools import check_id_number_strict, check_phone_e
from apps.vm.models import Visit, Visitor, Vpeople
from rest_framework import serializers
from rest_framework.exceptions import ParseError
from django.db import transaction
from apps.third.dahua import dhClient
from apps.third.tapis import dhapis
from apps.system.serializers import UserSimpleSerializer, FileSerializer
from apps.wf.serializers import TicketSerializer


class VisitCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Visit
        fields = ['id', 'purpose', 'name', 'description', 'visit_time',
                  'leave_time', 'receptionist', 'company', 'level', 'count_people', 'vehicle_photos']

    def create(self, validated_data):
        receptionist = validated_data.get('receptionist', None)
        if receptionist is None and validated_data['purpose'] != 50:
            raise ParseError('请指定接待人')
        if receptionist:
            if receptionist.type != 'employee':
                raise ParseError('接待人需为正式员工')
            validated_data['belong_dept'] = validated_data['receptionist'].belong_dept
        else:
            validated_data['belong_dept'] = Dept.objects.all().order_by('create_time').first()
        return super().create(validated_data)

    def update(self, instance, validated_data):
        receptionist = validated_data.get('receptionist', None)
        if receptionist is None and validated_data['purpose'] != 50:
            raise ParseError('请指定接待人')
        if receptionist:
            if receptionist.type != 'employee':
                raise ParseError('接待人需为正式员工')
            validated_data['belong_dept'] = validated_data['receptionist'].belong_dept
        else:
            validated_data['belong_dept'] = Dept.objects.all().order_by('create_time').first()
        return super().update(instance, validated_data)


class VisitSerializer(CustomModelSerializer):
    receptionist_ = UserSimpleSerializer(source='receptionist', read_only=True)
    ticket_ = TicketSerializer(source='ticket', read_only=True)

    class Meta:
        model = Visit
        fields = '__all__'


class VisitorCreateSerializer(CustomModelSerializer):
    phone = serializers.CharField(label="手机号", validators=[check_phone_e])
    photo = serializers.CharField(label='照片地址', required=True)
    id_number = serializers.CharField(
        label="身份证号", validators=[check_id_number_strict], required=True)

    class Meta:
        model = Visitor
        fields = ['name', 'phone', 'photo', 'id_number']

    def create(self, validated_data):
        with transaction.atomic():
            # 校验上传的证件照
            if validated_data.get('photo', None):
                dhClient.request(
                    **dhapis['person_img_upload'], file_path_rela=validated_data['photo'])
            return super().create(validated_data)


class VisitorSerializer(CustomModelSerializer):
    photo_f = MyFilePathField(source='photo', read_only=True)
    blt_ = serializers.SerializerMethodField()

    class Meta:
        model = Visitor
        fields = '__all__'

    def get_blt_(self, obj):
        from apps.third.serializers import TDeviceSimpleSerializer
        ep = obj.employee
        if ep and hasattr(ep, 'tdevice'):
            return TDeviceSimpleSerializer(instance=ep.tdevice).data


class VpeopleCreateSerializer(CustomModelSerializer):
    class Meta:
        model = Vpeople
        fields = '__all__'

    def create(self, validated_data):
        visit = validated_data['visit']
        visitor = validated_data['visitor']
        if visit.state != Visit.V_CREATE:
            raise ParseError('项目非创建状态不可新增成员')
        if visit.level == 10:
            if visitor.id_number and visitor.photo:
                pass
            else:
                raise ParseError('访客信息不全,请完善后再试')
        if Vpeople.objects.filter(visit=visit, visitor=visitor).exists():
            raise ParseError('该访客已选中')
        ins = super().create(validated_data)
        if ins.is_main:
            Vpeople.objects.filter(visit=visit).exclude(
                id=ins.id).update(is_main=False)
        if visit.level == 10:
            visit.count_people = Vpeople.objects.filter(visit=visit).count()
            visit.save()
        return ins


class VpeopleSerializer(CustomModelSerializer):
    visitor_ = VisitorSerializer(source='visitor', read_only=True)

    class Meta:
        model = Vpeople
        fields = '__all__'


class VisitorRegisterSerializer(serializers.Serializer):
    type = serializers.CharField(label="人员类型")
    name = serializers.CharField(label="姓名")
    phone = serializers.CharField(label="手机号")
    code = serializers.CharField(label='手机号验证码')
    wxmp_openid = serializers.CharField(label='微信小程序ID', required=False)
    wx_openid = serializers.CharField(label='微信公众号ID', required=False)


class VisitDetailSerializer(CustomModelSerializer):
    receptionist_ = UserSimpleSerializer(source='receptionist', read_only=True)
    receptionist_name = serializers.CharField(
        source='receptionist.name', read_only=True)
    visitors_ = serializers.SerializerMethodField()
    ticket_ = TicketSerializer(source='ticket', read_only=True)
    vehicle_photos_ = FileSerializer(source='vehicle_photos', read_only=True, many=True)

    class Meta:
        model = Visit
        fields = '__all__'

    def get_visitors_(self, obj):
        objs = Vpeople.objects.filter(
            visit=obj).order_by('is_main', 'create_time')
        return VpeopleSerializer(instance=objs, many=True).data
