from django.shortcuts import render

# Create your views here.
from common.utils.views import BaseApiView
from crm.plan.serializers import CreatePlanSerialzier
from rest_framework.response import Response

from common.utils.return_structure import general_message, error_message
from crm.plan.models import Plan

from crm.plan.filters import PlanFilter
from crm.plan.serializers import PlanInfoSerializer

from crm.plan.serializers import CreateCustomerClueSerializer

from crm.plan.models import CrmTask
from crm.plan.serializers import CreateTaskSerializer, TaskSerializer, SignInListSerializer

from crm.plan.serializers import TaskApproveSerializer

from crm.plan.filters import TaskFilter, SignInFilter

from crm.plan.serializers import SignInSerializer

from console.contract.serialisers import ContractInfoSerializer

from crm.plan.services import send_message

from crm.plan.serializers import MessageSerialzier

from crm.plan.models import SignIn


class CreatePlanView(BaseApiView):
    serializer_class = CreatePlanSerialzier

    def post(self, request, *args, **kwargs):
        request.data.update({"user": self.user})
        serialzier = self.get_serializer(data=request.data, context={"request": request})
        if serialzier.is_valid():
            serialzier.save()
            return Response(general_message("新增计划成功"))
        return Response(error_message(code=400, msg_show="添加计划失败", msg=serialzier.errors))


class UpdatePlanView(BaseApiView):
    serializer_class = CreatePlanSerialzier

    def put(self, request, *args, **kwargs):
        instance = Plan.objects.filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=400, msg_show="计划不存在"))
        serialzier = self.get_serializer(instance, data=request.data, context={"request": request})
        if serialzier.is_valid():
            serialzier.save()
            return Response(general_message("修改计划成功"))
        return Response(error_message(code=400, msg_show="修改计划失败", msg=serialzier.errors))


class DeletePlanView(BaseApiView):
    def delete(self, request, *args, **kwargs):
        Plan.objects.filter(id=kwargs.get("id")).delete()
        return Response(error_message(msg_show="删除成功"))


class PlanInfoView(BaseApiView):
    queryset = Plan.objects.filter()
    serializer_class = PlanInfoSerializer
    filter_class = PlanFilter

    def get(self, request, *args, **kwargs):
        if not kwargs.get("id"):
            return self.get_list(request, *args, **kwargs)
        else:
            return self.get_info(request, *args, **kwargs)


class CreateCustomerClueView(BaseApiView):
    serializer_class = CreateCustomerClueSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            return Response(general_message("提交成功"))
        return Response(error_message(code=400, msg=serializer.errors, msg_show="提交失败"))


class CreateTaskView(BaseApiView):
    def post(self, request, *args, **kwargs):
        serializer = CreateTaskSerializer(data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("任务创建成功"))
        return Response(error_message(code=400, msg=serializer.errors, msg_show="任务创建失败"))


class UpdateTaskView(BaseApiView):
    def put(self, request, *args, **kwargs):
        instance = CrmTask.objects.filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=400, msg_show="任务不存在"))
        serializer = CreateTaskSerializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("提交成功"))
        return Response(general_message(error_message(code=400, msg=serializer.errors,
                                                      msg_show="提交失败")))


class TaskListView(BaseApiView):
    queryset = CrmTask.objects.filter().prefetch_related(
        "plan", "customer", "customer__customer", "submitter", "code"
    )
    serializer_class = TaskSerializer
    filter_class = TaskFilter

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        # 销售人员
        if self.role and "销售" in self.role.name:
            queryset = queryset.filter(submitter=self.user)
        if kwargs.get("id"):
            queryset = self.get_queryset().filter(id=kwargs.get("id")).first()
            return Response(general_message(bean=self.get_serializer(queryset).data))
        return Response(general_message(list=self.get_serializer(queryset, many=True).data))


class TaskApproveView(BaseApiView):
    def put(self, request, *args, **kwargs):
        instance = CrmTask.objects.filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=400, msg_show="任务不存在"))
        serializer = TaskApproveSerializer(instance, data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("审核成功"))
        return Response(error_message(code=400, msg=serializer.errors, msg_show="审核失败"))


class SignInView(BaseApiView):
    def post(self, request, *args, **kwargs):
        serializer = SignInSerializer(data=request.data, context={"user": self.user, "request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("打卡成功"))
        return Response(error_message(code=400, msg=serializer.errors,
                                      msg_show="打卡失败"))


class SignInListView(BaseApiView):
    queryset = SignIn.objects.filter()
    serializer_class = SignInListSerializer
    filter_class = SignInFilter

    def get(self, request, *args, **kwargs):
        return self.get_list(request, *args, **kwargs)


class PlanContractView(BaseApiView):
    def get(self, request, *args, **kwargs):
        plan = Plan.objects.filter(id=kwargs.get("id")).first()
        if not plan:
            return Response(error_message(code=400, msg_show="计划不存在"))
        serializer = ContractInfoSerializer(plan.contract)
        return Response(general_message(bean=serializer.data))


class TaskUrgeView(BaseApiView):
    def put(self, request, *args, **kwargs):
        task = CrmTask.objects.filter(id=kwargs.get("id")).first()
        task.urgent = True
        task.save()
        send_message(**{
            "title": "任务催办",
            "content": "有一个任务在催办，请您尽快处理",
            "user": self.user,
            "customer_id": task.customer.id if task.customer else None,
            "plan_id": task.plan.id if task.plan else None,
            "task_id": task.id,
            "type": 2
        })
        return Response(general_message("操作成功"))


class MessageView(BaseApiView):
    serializer_class = MessageSerialzier

    def post(self, request, *args, **kwargs):
        request.data.update({"user": self.user})
        serializer = self.get_serializer(data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("创建成功"))
        return Response(error_message(code=400, msg=serializer.errors, msg_show="创建失败"))
