
from apps.auth1.services import check_phone_code
from apps.auth1.views import get_tokens_for_user
from apps.hrm.models import Employee
from apps.system.models import User
from apps.utils.tools import ranstr
from apps.utils.viewsets import CustomGenericViewSet, CustomModelViewSet
from apps.vm.models import Visit, Visitor, Vpeople
from apps.vm.serializers import (VisitCreateUpdateSerializer, VisitDetailSerializer,
                                 VisitSerializer, VisitorCreateSerializer, VisitorRegisterSerializer, VisitorSerializer,
                                 VpeopleCreateSerializer, VpeopleSerializer)
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.exceptions import ParseError
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin
from django.contrib.auth.hashers import make_password
from django.db import transaction
from rest_framework.serializers import Serializer
from apps.utils.constants import DEFAULT_PWD

from apps.vm.services import sync_to_visitor, visit_driver_end
# Create your views here.


class VisitViewSet(CustomModelViewSet):
    perms_map = {'*': '*'}
    queryset = Visit.objects.all()
    create_serializer_class = VisitCreateUpdateSerializer
    update_serializer_class = VisitCreateUpdateSerializer
    serializer_class = VisitSerializer
    retrieve_serializer_class = VisitDetailSerializer
    filterset_fields = ['state', 'create_by', 'purpose']
    select_related_fields = ['ticket', 'receptionist',
                             'ticket__workflow', 'ticket__state']

    def get_queryset(self):
        user = self.request.user
        queryset = super().get_queryset()
        if user.is_authenticated and user.type != 'employee':
            queryset = queryset.filter(create_by=user)
        return queryset

    def create(self, request, *args, **kwargs):
        user = self.request.user
        if hasattr(user, 'type') and user.type == 'visitor' and user.employee.photo is None:
            raise ParseError('请先完善个人信息')
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        obj = self.get_object()
        ticket = obj.ticket
        if ticket and ticket.state.type != 1:
            raise ParseError('项目在该状态不可更改')
        return super().update(request, *args, **kwargs)

    @transaction.atomic
    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj.state in [Visit.V_ENTER, Visit.V_DONE]:
            raise ParseError('该项目不可删除')
        elif obj.state == Visit.V_WORKING and Visitor.objects.filter(visit=obj).exists():
            raise ParseError('该项目人员在厂不可删除')
        if obj.ticket:
            obj.ticket.delete()
        obj.delete()
        return Response(status=204)

    @action(methods=['get'], detail=False, perms_map={'get': '*'}, serializer_class=Serializer)
    def export_excel(self, request, pk=None):
        return Response()


class VisitorViewSet(CustomModelViewSet):
    queryset = Visitor.objects.all()
    perms_map = {'*': '*'}
    create_serializer_class = VisitorCreateSerializer
    update_serializer_class = VisitorCreateSerializer
    serializer_class = VisitorSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = super().get_queryset().filter(create_by=user)
        # if user.type == 'visitor':
        #     queryset = queryset.filter(create_by=user)
        return queryset

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[],
            serializer_class=VisitorRegisterSerializer)
    @transaction.atomic
    def register(self, request, *args, **kwargs):
        """访客/司机账户注册

        访客/司机账户注册
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        vdata = serializer.validated_data
        name = vdata['name']
        phone = vdata['phone']
        code = vdata['code']
        # 校验短信验证码
        check_phone_code(phone, code)
        # 查询是否已注册
        user = User.objects.filter(phone=phone).first()
        ep = Employee.objects.get_queryset(all=True).filter(
            phone=phone, user__isnull=False).first()
        if user or ep:
            raise ParseError('该手机号已注册,请直接登录')
        # 访客/司机账户创建
        user = User()
        user.type = 'visitor'
        if vdata['type'] == 'driver':
            user.type = 'driver'
        user.name = name
        user.username = 'V_' + ranstr(10)
        user.phone = phone
        user.password = make_password(DEFAULT_PWD)
        user.wx_openid = vdata.get('wx_openid', None)
        user.wxmp_openid = vdata.get('wxmp_openid', None)
        user.save()
        ep2 = Employee.objects.get_queryset(all=True).filter(
            phone=phone, user__isnull=True).first()
        if ep2:
            ep2.user = user
            ep2.is_deleted = False
            ep2.save()
            sync_to_visitor(ep2)
        else:
            ep = Employee()
            ep.user = user
            ep.name = user.name
            ep.phone = user.phone
            ep.type = user.type
            ep.save()
        return Response(get_tokens_for_user(user))


class VpeopleViewSet(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, CustomGenericViewSet):
    perms_map = {'*': '*'}
    queryset = Vpeople.objects.all()
    create_serializer_class = VpeopleCreateSerializer
    serializer_class = VpeopleSerializer
    filterset_fields = ['visit']
    ordering = ['is_main', 'create_time']

    def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        ticket = obj.visit.ticket
        if ticket and ticket.state.type != 1:
            raise ParseError('项目在该状态不可新增成员')
        return super().destroy(request, *args, **kwargs)
