import datetime
from django.db.models import Q
from django.utils.decorators import method_decorator
from django.views.decorators.gzip import gzip_page
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from django.db import transaction

from rest_framework.response import Response

from common.utils.views import ManagerApiView
from common.utils.return_structure import general_message, error_message
from common.utils.serializers import serializer_assembly
from common.utils.service_code import VERIFICATION_ERROR
from common.utils.pagination import CustomPageNumberPagination
from common.utils.views import BaseApiView
from common.utils.excel_operations import ExcelOperator
from common.utils.exceptions import ValidationError

from console.inspection.serializers import (SpectPlanStationSerializer,
                                            InspectionStationSerializer,
                                            InspectionPlanUpdateSerializer,
                                            SpectTaskAssignSerializer,
                                            InspectionTaskSerializer,
                                            InspectionUpdateSerializer)
from console.inspection.models import InspectionPlan, InspectionTask, InspectionReport
from console.inspection.serializers import (SpectPlanCreateSerializer,
                                            InspectionPlanDeleteSerializer,
                                            ReportUploadSerializer)
from console.inspection.filters import InspectionStationFilter
from console.inspection.models import InspectionData, Defect
from console.inspection.serializers import (
    SpectionDataSerializer, DefectSerializer, DefectHandleSerializer,
    DefectCreateSerializer, SpectionDataCommitSerializer,
    DayInspectionTaskSerializer, TaskCreateSerializer,
    TaskManyAssignSerializer, PlansOfDateSerializer, TaskRecentSerialzier,
    InspectionTaskInfoSerializer)
from console.powerstation.models import PowerStation
from console.inspection.filters import (TaskFilter, InspectionPlanFilter,
                                        DefectFilter, TaskRecentFilter)
from console.inspection.serializers import InspectionTaskArriveSerializer
from console.inspection.serializers import DefectUpdateSerializer
from console.inspection.serializers import ConfirmSerializer
from console.inspection.serializers import TaskExportSerialzier
from console.inspection.services import (get_data_item_attribute,
                                         data_item_commit,
                                         send_defect_to_customer,
                                         inspection_task_filter)
from console.inspection.services import spection_task_notify, \
    export_inspection_report, send_message_to_customer

from console.team.models import Team

from console.inspection.models import PowerInspectionData

from console.inspection.serializers import PowerInspectionDataPowerSerializer

from console.inspection.serializers import DefectExportSerializer

from console.inspection.filters import DefectExportFilter

from console.inspection.models import SafetyEquipment

from console.inspection.serializers import SafetyEquipmentInfoSerializer


class SpectPlanCreate(ManagerApiView):
    '''
    添加巡检计划
    '''
    queryset = InspectionPlan.objects.filter()
    serializer_class = SpectPlanCreateSerializer

    @swagger_auto_schema(operation_description="添加巡检计划",
                         tags=["inspection"],
                         request_body=SpectPlanCreateSerializer,
                         responses={status.HTTP_200_OK: {}})
    def post(self, request, *args, **kwargs):
        serializer = SpectPlanCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="添加成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="添加失败",
                          code=VERIFICATION_ERROR))


class SpectPlanStation(ManagerApiView):
    '''
    获取待安排巡检计划的电站
    '''
    queryset = PowerStation.objects.filter(
        deleted=False,
        end_time__gte=datetime.datetime.now()).exclude(inspections_number=0)
    serializer_class = SpectPlanStationSerializer

    @swagger_auto_schema(operation_description="待排计划的电站列表",
                         manual_parameters=[
                             openapi.Parameter("leader",
                                               openapi.IN_QUERY,
                                               description="客户代表id",
                                               required=True,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("month",
                                               openapi.IN_QUERY,
                                               description="年月",
                                               required=True,
                                               type=openapi.TYPE_STRING)
                         ],
                         tags=["inspection"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(SpectPlanStationSerializer,
                                                     many=True)
                         })
    def get(self, request, *args, **kwargs):
        leader = request.GET.get("leader")
        month = request.GET.get("month")
        if not leader:
            raise ValidationError("请传递客户代表id")
        if not month:
            raise ValidationError("请传递日期")
        queryset = self.get_queryset()
        stations = queryset.filter(
            Q(customer__service_staff_id=leader)
            | Q(electricity_user__customer__service_staff_id=leader),
            deleted=False)
        serializer = SpectPlanStationSerializer(stations,
                                                context={
                                                    "request": self.request,
                                                    "leader": leader,
                                                    "month": month
                                                },
                                                many=True)
        return Response(
            general_message(msg_show="数据请求成功",
                            list=serializer.data,
                            count=stations.count(),
                            page=request.GET.get("page", 1),
                            page_size=request.GET.get("page_size", 10)))


class SpectionStation(ManagerApiView):
    '''
    获取巡检计划列表
    '''
    queryset = InspectionPlan.objects.filter().extra(
        select={
            "plan_date": "DATE_FORMAT(plan_date, '%%Y-%%m-%%d')"
        }).values("plan_date").distinct()
    serializer_class = InspectionStationSerializer
    filter_class = InspectionStationFilter

    @swagger_auto_schema(operation_description="获取巡检计划列表",
                         manual_parameters=[
                             openapi.Parameter("leader",
                                               openapi.IN_QUERY,
                                               description="客户代表id",
                                               required=True,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("month",
                                               openapi.IN_QUERY,
                                               description="年月",
                                               required=True,
                                               type=openapi.TYPE_STRING)
                         ],
                         tags=["inspection"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(InspectionStationSerializer,
                                                     many=True)
                         })
    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset,
                                         many=True,
                                         context={"request": request})
        return Response(general_message(list=serializer.data))


class InspectionPlanDelete(ManagerApiView):
    '''
    删除巡检计划
    '''
    queryset = InspectionPlan.objects.filter()
    serializer_class = InspectionPlanDeleteSerializer

    @swagger_auto_schema(operation_description="删除巡检计划",
                         request_body=InspectionPlanDeleteSerializer,
                         tags=["inspection"],
                         responses={status.HTTP_200_OK: {}})
    @transaction.atomic()
    def delete(self, request, *args, **kwargs):
        plan_ids = request.data
        serializer = InspectionPlanDeleteSerializer(data=plan_ids)
        if serializer.is_valid():
            try:
                sid = transaction.savepoint()
                # 同步删除巡检任务
                InspectionTask.objects.filter(
                    plan_id__in=plan_ids.get("data")).delete()
                InspectionPlan.objects.filter(
                    id__in=plan_ids.get("data")).delete()

            except Exception as e:
                transaction.rollback(sid)
                return Response(
                    error_message(msg=e,
                                  msg_show="删除失败",
                                  code=VERIFICATION_ERROR))
            transaction.savepoint_commit(sid)
            return Response(general_message("删除成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="删除失败",
                          code=VERIFICATION_ERROR))


class InspectionPlanUpdate(ManagerApiView):
    '''
    修改巡检计划
    '''
    queryset = InspectionPlan.objects.filter()
    serializer_class = InspectionPlanUpdateSerializer

    @swagger_auto_schema(operation_description="修改巡检计划",
                         request_body=InspectionPlanUpdateSerializer,
                         tags=["inspection"],
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        serializer = InspectionPlanUpdateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="修改成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="修改失败",
                          code=VERIFICATION_ERROR))


class SpectTaskAssign(ManagerApiView):
    """
    巡检任务分派/修改日期
    """
    queryset = InspectionTask.objects.filter()
    lookup_field = 'id'
    serializer_class = SpectTaskAssignSerializer
    permission_classes = (IsAuthenticated,)

    @swagger_auto_schema(operation_description="巡检任务分派、修改日期",
                         request_body=SpectTaskAssignSerializer,
                         tags=["inspection"],
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        task = InspectionTask.objects.filter(~Q(status="completed"),
                                             id=kwargs.get("id")).first()
        if not task:
            return Response(
                error_message(code=VERIFICATION_ERROR,
                              msg_show="当前任务不存在或不可被派发"))
        serializer = SpectTaskAssignSerializer(task,
                                               data=request.data,
                                               context={
                                                   "user": self.user,
                                                   "plan": task.plan
                                               })
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("操作成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="操作失败",
                          code=VERIFICATION_ERROR))


class SpectionTask(BaseApiView):
    queryset = InspectionTask.objects.filter().prefetch_related(
        "plan",
        "team",
        "plan__station",
        "plan__station__service_enterprise",
        "plan__station__customer",
        "plan__station__customer__service_staff",
        "plan__station__electricity_user__customer",
        "plan__station__electricity_user__customer__service_staff",
    )
    serializer_class = InspectionTaskSerializer
    filter_class = TaskFilter
    pagination_class = CustomPageNumberPagination

    @swagger_auto_schema(operation_description="巡检任务列表",
                         tags=["insoection"],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("status",
                                               openapi.IN_QUERY,
                                               description="状态",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("team",
                                               openapi.IN_QUERY,
                                               description="班组id",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("name",
                                               openapi.IN_QUERY,
                                               description="名称",
                                               required=False,
                                               type=openapi.TYPE_STRING)
                         ])
    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(
            self.get_queryset().order_by("-created_time"))
        if self.user.account.account_type == "customer":
            station = PowerStation.objects.filter(
                Q(customer_id__in=[self.customer.id])
                | Q(electricity_user__customer_id__in=[self.customer.id]))
            queryset = queryset.filter(plan__station__in=station)
        else:
            queryset = queryset.filter(
                plan__station__service_enterprise__in=self.enterprise_ids)
            queryset = inspection_task_filter(queryset, self.user)
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        bean = {
            "total": queryset.count(),
            "finish_num": queryset.filter(status="completed").count()
        }
        data = serializer.data
        return Response(
            general_message(msg_show="数据请求成功",
                            list=data,
                            bean=bean,
                            count=queryset.count(),
                            page=int(request.GET.get("page", 1)),
                            page_size=int(request.GET.get("page_size", 10))))


class SpectTaskInfo(BaseApiView):
    queryset = InspectionTask.objects.filter().prefetch_related("team", "plan")
    serializer_class = InspectionTaskInfoSerializer
    lookup_field = "id"

    @swagger_auto_schema(operation_description="巡检任务详情",
                         tags=["insoection"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(InspectionTaskSerializer)
                         })
    def get(self, request, *args, **kwargs):
        return super(SpectTaskInfo, self).get_info(request, *args, **kwargs)


class SpectTaskRecord(BaseApiView):
    queryset = InspectionTask.objects.all()
    serializer_class = SpectionDataSerializer

    @swagger_auto_schema(operation_description="巡检记录详情",
                         tags=["spection"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(SpectionDataSerializer)
                         })
    def get(self, request, *args, **kwargs):
        id = kwargs.get("id")
        queryset = self.get_queryset().filter(id=id).first()
        inspection_data = InspectionData.objects.filter(
            inspection_task=queryset).first()
        data = SpectionDataSerializer(inspection_data).data
        return Response(data=general_message(msg_show="数据请求成功", bean=data),
                        status=status.HTTP_200_OK)


class DefectList(BaseApiView):
    '''
    缺陷列表
    '''
    queryset = Defect.objects.filter()
    serializer_class = DefectSerializer
    filter_class = DefectFilter

    @swagger_auto_schema(operation_description="缺陷列表",
                         tags=["inspection"],
                         manual_parameters=[
                             openapi.Parameter("status",
                                               openapi.IN_QUERY,
                                               description="状态",
                                               type=openapi.TYPE_STRING,
                                               required=False),
                             openapi.Parameter("name",
                                               openapi.IN_QUERY,
                                               description="名称，模糊匹配",
                                               type=openapi.TYPE_STRING,
                                               required=False),
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(DefectSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        self.queryset = self.queryset.filter(
            customer__service_enterprise_id__in=self.enterprise_ids)
        return self.get_list(request, *args, **kwargs)


class DefectInfo(BaseApiView):
    '''
    缺陷详情
    '''
    queryset = Defect.objects.all()
    serializer_class = DefectSerializer

    @swagger_auto_schema(
        operation_description="缺陷详情",
        tags=['inspection'],
        responses={status.HTTP_200_OK: serializer_assembly(DefectSerializer)})
    def get(self, request, *args, **kwargs):
        id = kwargs.get("id")
        defect = self.get_queryset().filter(id=id).first()
        data = self.get_serializer(defect).data
        return Response(data=general_message(msg_show="数据请求成功", bean=data),
                        status=status.HTTP_200_OK)


class DefectHandle(ManagerApiView):
    '''
    处理缺陷
    '''
    queryset = Defect.objects.all()
    serializer_class = DefectHandleSerializer

    @swagger_auto_schema(operation_description="缺陷处理",
                         tags=["inspection"],
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        id = kwargs.get("id")
        queryset = self.get_queryset().filter(id=id).first()
        serializer = self.get_serializer(queryset, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data=general_message(msg_show="数据请求成功"),
                            status=status.HTTP_200_OK)
        return Response(data=error_message(
            code=VERIFICATION_ERROR, msg_show="处理失败", msg=serializer.error))


class DefectCreate(ManagerApiView):
    serializer_class = DefectCreateSerializer

    @swagger_auto_schema(request_body=DefectCreateSerializer,
                         operation_description="缺陷登记",
                         tags=['inspection'],
                         responses={status.HTTP_200_OK: {}})
    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        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 SpectionDataCommit(ManagerApiView):
    serializer_class = SpectionDataCommitSerializer

    @swagger_auto_schema(operation_description="巡检抄表数据提交",
                         request_body=SpectionDataCommitSerializer,
                         tags=['inspetion'],
                         responses={status.HTTP_200_OK: {}})
    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        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 InspectionTaskArrive(ManagerApiView):
    queryset = InspectionTask.objects.filter()
    serializer_class = InspectionTaskArriveSerializer

    @swagger_auto_schema(operation_description="到达现场",
                         request_body=SpectionDataCommitSerializer,
                         tags=['inspetion'],
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        inspection_task = self.get_queryset().filter(
            id=kwargs.get("id")).first()
        if not inspection_task:
            return Response(
                error_message(msg_show="巡检任务{}不存在".format(kwargs.get("id")),
                              code=VERIFICATION_ERROR))
        serializer = self.get_serializer(inspection_task, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="签到成功"))
        return Response(
            error_message(msg_show="签到失败",
                          msg=serializer.errors,
                          code=VERIFICATION_ERROR))


class InsepectionTaskRecent(ManagerApiView):
    queryset = InspectionTask.objects.filter().prefetch_related(
        "plan", "team", "plan__station", "plan__station__customer",
        "plan__station__electricity_user",
        "plan__station__electricity_user__customer", "team__team_headman",
        "team__member")
    serializer_class = TaskRecentSerialzier
    filter_class = TaskRecentFilter

    @swagger_auto_schema(operation_description="巡检任务列表",
                         tags=["insoection"],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("status",
                                               openapi.IN_QUERY,
                                               description="状态",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("team",
                                               openapi.IN_QUERY,
                                               description="班组id",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("name",
                                               openapi.IN_QUERY,
                                               description="名称",
                                               required=False,
                                               type=openapi.TYPE_STRING)
                         ])
    @method_decorator(gzip_page, name='dispatch')
    def get(self, request, *args, **kwargs):
        team = Team.objects.filter(Q(team_headman=self.user)
                                   | Q(member=self.user)).first()
        if not team:
            return Response(general_message(list=[]))
        queryset = self.filter_queryset(
            self.get_queryset().order_by("-created_time"))
        serializer = self.get_serializer(queryset, many=True)
        bean = {
            "total": queryset.count(),
            "finish_num": queryset.filter(status="completed").count()
        }
        data = serializer.data
        return Response(
            general_message(
                msg_show="数据请求成功",
                list=data,
                bean=bean,
            ))


class DefectUpdateView(ManagerApiView):
    queryset = Defect.objects.filter()
    serializer_class = DefectUpdateSerializer

    @swagger_auto_schema(operation_description="修改缺陷",
                         tags=["inspection"],
                         request_body=DefectUpdateSerializer,
                         responses={status.HTTP_200_OK: {}})
    def put(self, request, *args, **kwargs):
        defect = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not defect:
            return Response(
                error_message(msg="defect is not exits!",
                              msg_show="该缺陷不存在",
                              code=VERIFICATION_ERROR))
        serializer = self.get_serializer(defect, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="修改成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="修改失败",
                          code=VERIFICATION_ERROR))


class ConfirmView(BaseApiView):
    queryset = InspectionTask.objects.filter()
    serializer_class = ConfirmSerializer

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


class TaskExportView(ManagerApiView):
    queryset = InspectionTask.objects.filter()
    serializer_class = TaskExportSerialzier
    filter_class = TaskFilter

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


class InspectionTaskOfDayInfo(BaseApiView):
    queryset = InspectionTask.objects.filter(type=1)
    serializer_class = DayInspectionTaskSerializer

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


class DataItemInfoView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        table = request.GET.get("table")
        if not table:
            raise ValidationError("table is required!")
        inspection_task = request.GET.get("inspection_task")
        if not inspection_task:
            raise ValidationError("inspection_task id is required!")
        data = get_data_item_attribute(table, inspection_task)
        return Response(
            general_message(list=data.get("attribute"), bean=data.get("data")))


class DataItemCommitView(ManagerApiView):
    def post(self, request, *args, **kwargs):
        data_item_commit(request.data)
        return Response(general_message("提交成功"))


class TaskCreateView(ManagerApiView):
    def post(self, request, *args, **kwargs):
        serializer = TaskCreateSerializer(
            data=request.data, context={"enterprise_id": self.enterprise_ids})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("新增成功"))
        return Response(
            error_message(code=VERIFICATION_ERROR,
                          msg=serializer.errors,
                          msg_show="新增失败"))


class TaskManyAssignView(ManagerApiView):
    def put(self, request, *args, **kwargs):
        serializer = TaskManyAssignSerializer(data=request.data)
        if serializer.is_valid():
            InspectionTask.objects.filter(
                ~Q(status="completed"),
                id__in=request.data.get("task_list")).update(
                team_id=request.data.get("team_id"),
                assign_date=datetime.datetime.now(),
                status="pending")
            data = request.data
            data.update({"user": request.user, "enterprise_id": self.enterprise.id})
            spection_task_notify(**data)
            return Response(general_message("派发成功"))
        return Response(
            error_message(code=VERIFICATION_ERROR,
                          msg=serializer.errors,
                          msg_show="派发失败"))


class PlansOfDate(ManagerApiView):
    queryset = InspectionPlan.objects.filter().extra(
        select={
            "plan_date": "DATE_FORMAT(plan_date, '%%Y-%%m-%%d')"
        }).values("station", "plan_date").distinct()
    filter_class = InspectionPlanFilter
    pagination_class = CustomPageNumberPagination
    serializer_class = PlansOfDateSerializer

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        queryset = self.filter_queryset(queryset)
        serializer = self.get_serializer(queryset, many=True)
        return Response(general_message(list=serializer.data))


class UpdateInspectionDataView(ManagerApiView):
    serializer_class = InspectionUpdateSerializer
    queryset = InspectionTask.objects.filter()

    def put(self, request, *args, **kwargs):
        inspection_task = self.get_queryset().filter(
            id=request.data.get("inspection_task")).first()
        serializer = self.get_serializer(inspection_task, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("修改成功"))
        return Response(
            error_message(code=VERIFICATION_ERROR,
                          msg=serializer.errors,
                          msg_show="修改失败，请检查参数是否正确"))


class DefectSendCustomer(ManagerApiView):
    queryset = Defect.objects.filter()

    def post(self, request, *args, **kwargs):
        defect = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not defect:
            return Response(
                error_message(code=VERIFICATION_ERROR,
                              msg_show="缺陷%s不存在" % kwargs.get("id")))
        send_defect_to_customer(self.enterprise.id, defect)
        return Response(general_message("发送成功"))


class ExportInspectionReportView(BaseApiView):
    def get(self, request, *args, **kwargs):
        station = PowerStation.objects.filter(
            id=request.GET.get("station_id")).first()
        if not station:
            return Response(
                error_message(code=VERIFICATION_ERROR,
                              msg_show="电站%s不存在" %
                                       request.GET.get("station_id")))
        data = {
            "station_id": station.id,
            "station_name": station.name,
            "type": request.GET.get("type", "month"),
            "start_time": request.GET.get("start_time"),
            "end_time": request.GET.get("end_time"),
            "year_month": request.GET.get("year_month")
        }
        url = export_inspection_report(**data)

        return Response(general_message(bean=url.replace("\\", "/")))


class PDFStreamView(BaseApiView):
    def get(self, request, *args, **kwargs):
        ele_number = request.GET.get("ele_number")
        year_month = request.GET.get("year_month")
        url = "https://report-1302976931.cos.ap-shanghai.myqcloud.com/"
        return Response(
            general_message(bean=url + ele_number + "_" + year_month + ".pdf"))


class SendMessageToCustomer(ManagerApiView):
    def post(self, request, *args, **kwargs):
        send_message_to_customer(request.data.get("customer_id"))
        return Response(general_message("发送成功"))


class LastMonthPowerDataView(BaseApiView):
    queryset = PowerInspectionData.objects.filter()
    serializer_class = PowerInspectionDataPowerSerializer

    def get(self, request, *args, **kwargs):
        power_number = request.GET.get("power_number")
        work_date = request.GET.get("work_date")
        date = datetime.datetime.strptime(work_date, "%Y-%m-%d")
        year = date.year
        month = date.month - 1
        if month == 0:
            year -= 1
            month = 12
        instance = PowerInspectionData.objects.filter(
            power_number=power_number,
            inspection_task__work_date__year=year,
            inspection_task__work_date__month=month).order_by("-created_time").first()
        serializer = self.get_serializer(instance)
        return Response(general_message(bean=serializer.data))


class DefectExportView(BaseApiView):
    queryset = Defect.objects.filter()
    serializer_class = DefectExportSerializer
    filter_class = DefectExportFilter

    def post(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)
        excel = ExcelOperator()
        data = excel.excel_export(serializer.data,
                                  "DefectList",
                                  key_map="Defect_map")
        return Response(general_message(msg_show="导出成功", bean=data))


class StationSafetyEquipmentView(BaseApiView):
    queryset = SafetyEquipment.objects.filter().prefetch_related("station")
    serializer_class = SafetyEquipmentInfoSerializer

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(station_id=request.GET.get("station_id")).first()
        serializer = self.get_serializer(queryset)
        return Response(general_message(bean=serializer.data))


class ReportUploadView(BaseApiView):
    queryset = InspectionReport.objects.filter()
    serializer_class = ReportUploadSerializer

    def post(self, request, *args, **kwargs):
        customer_report = self.get_queryset().filter(task_id=request.data.get("task_id")).first()
        serializer = self.get_serializer(customer_report, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("发送成功"))
        return Response(error_message(code=400, msg_show="发送失败", msg=serializer.errors))


class TaskConfirmView(BaseApiView):
    def put(self, request, *args, **kwargs):
        task = InspectionTask.objects.filter(id=kwargs.get("id")).first()
        if not task:
            return Response(error_message(code=400, msg_show="巡检任务%s不存在" % kwargs.get("id")))
        task.confirm = True
        task.save()
        return Response(general_message("确认成功"))
