# coding=utf-8
from django.conf import settings
from django.db import transaction
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.decorators import action
from utils import response_ok, response_error
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsTenantUser, permission_required, isLogin, IsEmployee
from apps.tenant.repair_order.models import RepairOrder, RepairOrderRecord, RepairOrderComment, RepairOrderFinish
from apps.tenant.repair_order.filters import RepairOrderFilter
from apps.upload.models import Upload
from apps.log.models import BizLog
from apps.tenant import tenant_log
from apps.tenant.inspection_order.models import InspectionOrder
from apps.WechatApplet.models import WechatApplet
from apps.wxapp.models import CustomerWechat
from .serializers import (RepairOrderSerializer, RepairOrderListSerializer,
                          RepairOrderDetailSerializer)


class RepairOrderDetailView(generics.RetrieveAPIView):
    permission_classes = [isLogin, ]
    queryset = RepairOrder.objects.filter(delete=False)
    serializer_class = RepairOrderDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)


class RepairOrderMineView(generics.ListAPIView):
    permission_classes = [isLogin, ]
    queryset = RepairOrder.objects.filter(delete=False)
    serializer_class = RepairOrderListSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant, user=self.request.user)
        f = RepairOrderFilter(self.request.GET, queryset=queryset)
        return f.qs


class RepairOrderCountView(APIView):
    def get(self, request):
        queryset = RepairOrder.objects.filter(delete=False, tenant=self.request.user.employee.tenant)
        return response_ok({
            'NOT_CHECKED_COUNT': queryset.filter(status=settings.NOT_CHECKED).count(),
            'CHECKED_COUNT': queryset.filter(status=settings.CHECKED).count()
        })


class RepairOrderAllView(generics.ListAPIView):
    permission_classes = [isLogin, ]
    queryset = RepairOrder.objects.filter(delete=False)
    serializer_class = RepairOrderListSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = RepairOrderFilter(self.request.GET, queryset=queryset)
        return f.qs


class DispatchRepairOrderView(generics.ListAPIView):
    # 我的维修单
    permission_classes = [IsEmployee, ]
    # 查询维修工单记录状态为已派单的
    queryset = RepairOrder.objects.filter()
    serializer_class = RepairOrderDetailSerializer

    def get_queryset(self):
        queryset = self.queryset.filter(tenant=self.request.user.employee.tenant, repair_users=self.request.user)
        return queryset

    def filter_queryset(self, queryset):
        f = RepairOrderFilter(self.request.GET, queryset=queryset)
        return f.qs


class RepairOrderViewSet(CustomModelViewSet):
    permission_classes = (isLogin, )
    queryset = RepairOrder.objects.filter(delete=False)
    serializer_class = RepairOrderSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant, )
        if self.request.user.is_repair:
            queryset = queryset.filter(user=self.request.user)
        # user_ids = self.repair_users.split(',') or [] TODO 维修师傅一对一
        f = RepairOrderFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(RepairOrderViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加报修工单[%s]，id=%d' % (instance.name, instance.id),
                   validated_data)

    @action(methods=['post'], detail=False)
    def upload_image(self, request):
        file = self.request.FILES.get('file')
        user = self.request.user
        upload = Upload.objects._addnew(user.employee.tenant, user, Upload.REPAIR_IMAGE, file)
        if upload:
            return response_ok(upload.id)
        return response_error('上传失败，请重新上传！')

    @action(methods=['get'], detail=True)
    def check(self, request, pk):
        # 审核
        try:
            if not self.request.user.is_admin():
                raise CustomError(u"权限不足，禁止操作！")
            with transaction.atomic():
                user = self.request.user
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                instance.check_repair_order(user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')

    @action(methods=['post'], detail=True)
    def hang_up(self, request, pk):
        # 挂起
        try:
            if not self.request.user.is_employee():
                raise CustomError(u"权限不足，禁止操作！")
            reason = request.data.get('reason')
            if not reason:
                raise CustomError('请填写挂起原因')
            with transaction.atomic():
                user = self.request.user
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                instance.hange_up_repair_order(user, reason)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('成功挂起！')

    @action(methods=['get'], detail=True)
    def cancel_hang_up(self, request, pk):
        # 取消挂起，继续施工
        try:
            if not self.request.user.is_employee():
                raise CustomError(u"权限不足，禁止操作！")
            with transaction.atomic():
                user = self.request.user
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                instance.cancel_hange_up_repair_order(user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('成功取消挂起！')

    @action(methods=['get'], detail=True)
    def rob_repair(self, request, pk):
        # 抢单
        try:
            with transaction.atomic():
                user = self.request.user
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)

                if not instance.status == settings.CHECKED:
                    raise CustomError('当前报修工单状态非待派单状态，不能进行抢单！')

                instance.status = settings.DISPATCH
                instance.repair_users.add(user.id)
                instance.save()

                RepairOrderRecord.objects.create(repair_order=instance, status=settings.DISPATCH, user=user,
                                                 repair_users=user.id, notes='成功抢单')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('抢单成功！')

    @action(methods=['post'], detail=True)
    def finish(self, request, pk):
        # 完工
        if not self.request.user.is_employee():
            raise CustomError(u"权限不足，禁止操作！")
        try:
            content = request.data.get('content')
            images = request.data.get('images', None)
            quality_date = request.data.get('quality_date') or None
            fault_cause_id = request.data.get('fault_cause')
            user = self.request.user

            instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
            if not instance.status == settings.DISPATCH:
                raise CustomError('当前报修工单状态非派单状态，不能进行完工操作！')

            with transaction.atomic():
                # 更新工单状态为完工
                instance.status = settings.FINISH
                instance.save()
                # 写入完工表
                repair_order_finish = RepairOrderFinish.objects.create(repair_order_id=pk,
                                                                       fault_cause_id=fault_cause_id,
                                                                       quality_date=quality_date, content=content)
                if images:
                    for image in images.split(','):
                        repair_order_finish.images.add(image)
                repair_order_finish.save()
                # 增加工单记录
                RepairOrderRecord.objects.create(repair_order_id=pk, status=settings.FINISH, user=user, notes=content)
                # 判断是否为巡检转报修，更新巡检状态
                inspection_order = InspectionOrder.objects.filter(repair_order=instance).first()
                if inspection_order:
                    inspection_order.status = InspectionOrder.REPAIR
                    inspection_order.save()

                # 发送通知
                # CustomerWechat.sendMsg(instance.user, user.employee.name, instance.get_full_name(),
                #                        instance.fault_des, instance.no)

        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('完工完成！')

    @action(methods=['get'], detail=True)
    def invalid(self, request, pk):
        # 作废
        try:
            if not self.request.user.is_admin():
                raise CustomError(u"权限不足，禁止操作！")
            with transaction.atomic():
                user = self.request.user
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                instance.invalid(user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('工单作废完成！')

    @action(methods=['post'], detail=True)
    def comment(self, request, pk):
        # 评价
        try:
            content = request.data.get('content')
            start = request.data.get('start', 5)
            if not content:
                return response_error('评价内容不能为空！')
            user = self.request.user
            instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
            if not instance.status == settings.FINISH:
                raise CustomError('当前报修工单状态非派单状态，不能进行评价操作！')

            with transaction.atomic():
                instance.status = settings.APPRAISE
                instance.save()
                RepairOrderComment.objects.create(repair_order=instance, content=content, start=start, user=user)
                # 增加工单记录
                RepairOrderRecord.objects.create(repair_order_id=pk, status=settings.APPRAISE, user=user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('工单评价完成！')

    @action(methods=['get'], detail=True)
    def repair_order_record(self, request, pk):
        # 维修工单记录
        user = self.request.user
        instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
        records = RepairOrderRecord.objects.filter(repair_order=instance).order_by('-operation_time')
        data = []
        for record in records:
            dict = record.get_records(instance.id)
            data.append(dict)
        return response_ok(data)

    def destroy(self, request, *args, **kwargs):
        try:
            if not self.request.user.is_admin():
                raise CustomError(u"权限不足，禁止操作！")
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                tenant_log(self.request.user.employee, BizLog.DELETE,
                           u'删除报修工单[%s]，id=%d' % (instance.name, instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()
