from drf_yasg.utils import swagger_auto_schema
from rest_framework import status

# Create your views here.
from rest_framework.response import Response

from common.utils.return_structure import general_message, error_message
from common.utils.service_code import VERIFICATION_ERROR
from common.utils.views import BaseApiView
from console.task.serializers import TaskCreateSerializer

from console.task.serializers import OrderCreateSerializer

from console.task.models import Task

from common.utils.pagination import CustomPageNumberPagination
from console.task.filters import TaskListFilter
from console.task.serializers import TaskCloseSerializer, TaskListSerializer, \
    TaskInfoSerializer, TaskPlanDateSerializer, TaskPlanCheckSerializer, \
    TaskConfirmSerializer, TaskRelateContractSerializer, \
    TaskExportSerializer, TaskEditSerializer, TaskEvaluateSerializer

from common.utils.serializers import serializer_assembly

from common.utils.service_code import API_ERROR
from common.utils.views import ManagerApiView
#
# from common.accounts.models import Users
# from console.customer.models import CustomerAdmin

from console.task.services import get_customer_list, get_customer_info, \
    task_data_filter

from common.utils.excel_operations import ExcelOperator

from console.task.services import task_create_calling


class TaskCreateView(BaseApiView):
    serializer_class = TaskCreateSerializer

    @swagger_auto_schema(operation_description="发起业务",
                         tags=["task"],
                         request_body=TaskCreateSerializer,
                         responses={status.HTTP_200_OK: {}})
    def post(self, request):
        request.data.update({"service_enterprise": self.enterprise})
        serializer = TaskCreateSerializer(data=request.data,
                                          context={"request": request})
        if serializer.is_valid():
            serializer.save()
            # 外呼提醒
            task_create_calling()
            return Response(data=general_message(msg_show="新增成功"))
        return Response(data=error_message(
            code=VERIFICATION_ERROR, msg_show="提交失败", msg=serializer.errors))


class OrderCreateView(BaseApiView):
    serializer_class = OrderCreateSerializer

    @swagger_auto_schema(operation_description="发起工单",
                         tags=["task"],
                         request_body=OrderCreateSerializer,
                         responses={status.HTTP_200_OK: {}})
    def post(self, request):
        serializer = OrderCreateSerializer(data=request.data,
                                           context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(data=general_message(msg_show="发起成功"))
        return Response(data=error_message(code=VERIFICATION_ERROR,
                                           msg_show="当前任务状态无法发起工单",
                                           msg=serializer.errors))


class TaskRelateContract(BaseApiView):
    @swagger_auto_schema(operation_description="关联合同",
                         tags=["task"],
                         request_body=TaskRelateContractSerializer,
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        task = Task.objects.filter(id=kwargs.get("id")).first()
        serializer = TaskRelateContractSerializer(task,
                                                  data=request.data,
                                                  context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(data=general_message(msg_show="关联成功"))
        return Response(data=error_message(
            code=VERIFICATION_ERROR, msg_show="关联失败", msg=serializer.errors))


class TaskCloseView(ManagerApiView):
    @swagger_auto_schema(operation_description="关闭任务",
                         tags=["task"],
                         request_body=TaskCloseSerializer,
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        task = Task.objects.filter(id=kwargs.get("id")).first()
        request.data.update({"task_id": kwargs.get("id")})
        serializer = TaskCloseSerializer(task,
                                         data=request.data,
                                         context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(data=general_message(msg_show="任务已关闭"))
        return Response(data=error_message(
            msg_show="任务关闭失败", msg=serializer.errors, code=VERIFICATION_ERROR))


class TaskListView(BaseApiView):
    serializer_class = TaskListSerializer
    queryset = Task.objects.filter().prefetch_related(
        "contract", "customer",
        "customer__service_staff").order_by("-created_time")
    filter_class = TaskListFilter
    pagination_class = CustomPageNumberPagination

    def get(self, request, *args, **kwargs):
        if self.is_manager:
            queryset = self.get_queryset().filter(
                customer__service_enterprise__in=self.enterprise_ids)
            queryset = task_data_filter(queryset, self.user)
        else:
            queryset = self.get_queryset().filter(customer_id__in=[self.customer.id])
        queryset = self.filter_queryset(queryset)
        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data
        return Response(general_message(list=data, count=len(data)))


class TaskInfoView(BaseApiView):
    queryset = Task.objects.filter().prefetch_related("contract", "customer",
                                                      "station", "equipment")
    serializer_class = TaskInfoSerializer

    @swagger_auto_schema(operation_description="任务详情",
                         tags=["task"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(TaskInfoSerializer)
                         })
    def get(self, request, *args, **kwargs):
        task = self.get_queryset().filter(id=kwargs.get("id")).first()
        serializer = TaskInfoSerializer(task)
        return Response(
            data=general_message(bean=serializer.data, msg_show="数据请求成功"))


class TaskPlanDateView(ManagerApiView):
    queryset = Task.objects.all()
    serializer_class = TaskPlanDateSerializer

    def put(self, request, *args, **kwargs):
        task = Task.objects.filter(id=kwargs.get("id")).first()
        serializer = TaskPlanDateSerializer(task,
                                            data=request.data,
                                            context={
                                                "task": task,
                                                "request": request
                                            })
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="排期成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="排期失败",
                          code=API_ERROR))


class TaskPlanCheckView(ManagerApiView):
    queryset = Task.objects.all()
    serializer_class = TaskPlanCheckSerializer

    def put(self, request, *args, **kwargs):
        task = Task.objects.filter(id=kwargs.get("id")).first()
        serializer = TaskPlanCheckSerializer(task,
                                             data=request.data,
                                             context={
                                                 "task": task,
                                                 "request": request
                                             })
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="提交成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="提交失败",
                          code=API_ERROR))


class TaskConfirmView(BaseApiView):
    queryset = Task.objects.filter()
    serializer_class = TaskConfirmSerializer

    def put(self, request, *args, **kwargs):
        task = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not task:
            return Response(error_message("任务{}不存在".format(kwargs.get("id"))))
        serializer = self.get_serializer(task,
                                         data=request.data,
                                         context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("确认成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="确认失败",
                          code=VERIFICATION_ERROR))


class TaskCreateCustomerListView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        keyword = request.GET.get("keyword")
        page = request.GET.get("page", 1)
        page_size = request.GET.get("papge_size", 10)
        data = get_customer_list(keyword,
                                 page=page,
                                 page_size=page_size,
                                 enterprise=self.enterprise_ids)
        return Response(
            general_message(list=data,
                            page=page,
                            page_size=page_size,
                            count=len(data)))


class TaskCreateCustomerInfoView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        customer_id = kwargs.get("id")
        ele_user_id = request.GET.get("ele_user_id")
        data = get_customer_info(customer_id, ele_user_id)
        return Response(general_message(bean=data))


class TaskExportView(ManagerApiView):
    serializer_class = TaskExportSerializer
    queryset = Task.objects.filter(deleted=False)
    filter_class = TaskListFilter

    def post(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        if request.data.get("task_id"):
            queryset = queryset.filter(id__in=request.data.get("task_id"))
        serializer = self.get_serializer(queryset, many=True)
        excel = ExcelOperator()
        data = excel.excel_export(serializer.data,
                                  "TaskList",
                                  key_map="TaskListMap")
        return Response(general_message(msg_show="导出成功", bean=data))


class TaskEditView(BaseApiView):
    queryset = Task.objects.filter(deleted=False)
    serializer_class = TaskEditSerializer

    def put(self, request, *args, **kwargs):
        task = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not task:
            return Response(
                error_message(code=VERIFICATION_ERROR,
                              msg_show="任务{}不存在".format(kwargs.get("id"))))
        serializer = self.get_serializer(task, data=request.data)
        if serializer.is_valid():
            task = serializer.save()
            return Response(
                general_message(bean=TaskInfoSerializer(task).data))
        return Response(
            error_message(code=VERIFICATION_ERROR,
                          msg=serializer.errors,
                          msg_show="修改失败"))


class TaskEvaluateView(BaseApiView):
    queryset = Task.objects.filter()
    serializer_class = TaskEvaluateSerializer

    def put(self, request, *args, **kwargs):
        instance = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=API_ERROR, msg_show="任务%s不存在" % kwargs.get("id")))
        serializer = self.get_serializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("评价成功"))
        return Response(error_message(code=API_ERROR, msg_show="评价失败", msg=serializer.errors))
