# coding=utf-8
from django.db import transaction
from rest_framework.decorators import action
from django.conf import settings
from rest_framework.views import APIView
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
from .serializers import RepairOrderSerializer
from .models import RepairOrder, RepairOrderRecord, RepairOrderFinish
from .filters import RepairOrderFilter
from apps.tenant import tenant_log
from apps.log.models import BizLog
from apps.tenant.area.serializers import AreaSerializer, AreaDepartmentSerializer, Area, Department
from apps.tenant.employee.serializers import Employee, EmployeeSerializer


class DictView(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        tenant = request.user.employee.tenant
        ret = {
            'status': settings.REPAIR_STATUS_CHOICES,
        }
        return response_ok(ret)

class GetEmployeeView(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        employees = EmployeeSerializer(
            Employee.objects.filter(status__lte=Employee.DAY_OFF, type=Employee.EMPLOYEE, ), many=True).data
        data = []
        for emp in employees:
            dict = {
                'id': emp['user'],
                'name': '{0}-{1}-{2}-{3}'.format(emp['name'], emp['tel'], emp['position'], emp['status_text'])
            }
            data.append(dict)
        return response_ok(data)

class OrderRecordView(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        order_id = request.GET.get('order_id')
        records = RepairOrderRecord.objects.filter(repair_order_id=order_id).order_by('-operation_time')
        data = []
        for record in records:
            dict = record.get_records(order_id)
            data.append(dict)
        return response_ok(data)

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

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

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            if instance.tenant != request.user.employee.tenant:
                raise CustomError(u'禁止跨租户操作！')
            super(RepairOrderViewSet, self).destroy(self, request, *args, **kwargs)
            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除报修单[%s]，id=%d' % (instance.no, instance.id))
        return response_ok()

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        try:
            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 dispatch_employee(self, request, pk):
        # 派工
        try:
            user_ids = self.request.data.get('user_ids')
            if not user_ids:
                return response_error('请选择维修工人！')
            user = self.request.user
            with transaction.atomic():
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                if not instance.status == settings.CHECKED:
                    return response_ok('当前报修工单状态非待派单状态，不能进行派单！')
                instance.dispatch_repair_order(user, user_ids)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok('派工完成！')

    @action(methods=['post'], detail=True)
    def turn_employee(self, request, pk):
        # 转单
        try:
            user_ids = self.request.data.get('user_ids')
            if not user_ids:
                return response_error('请选择维修工人！')
            user = self.request.user
            with transaction.atomic():
                instance = RepairOrder.get_instance_by_id(pk, user.employee.tenant)
                if not instance.status == settings.DISPATCH:
                    return response_ok('当前报修工单状态还未派单待派单，不能进行转单！')
                instance.repair_users.clear()
                for user_id in user_ids:
                    instance.repair_users.add(user_id)
                instance.save()
                # 记录操作
                RepairOrderRecord.objects.create(repair_order=instance, status=settings.TURN_EMPLOYEE, user=user,
                                                 repair_users=user_ids)
        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 cancel(self, request, pk):
        # 作废
        try:
            if not self.request.user.has_perm('repair_order.invalid_repair_order'):
                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('工单作废完成！')
