from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.response import Response

from common.utils import views
from common.utils.excel_operations import ExcelOperator
from common.utils.exceptions import ValidationError
from common.utils.return_structure import general_message
from common.utils.serializers import serializer_assembly

from console.electricityuser.filters import ElectricityUserFilter
from console.electricityuser.repositories import (electricityuser_queryset,
                                                  electricityuser_repo)
from console.electricityuser.serializers import (
    ElectricityUserSerializer, ElectricityUserListSerializer,
    ElectricityUserDetailSerializer, ElectricityUserUpdateSerializer)
from console.electricityuser.repositories import electricityuser_sql_repo
from console.electricityuser.services import electricity_service
from console.customer.models import Customer


class ElectricityUserView(views.BaseApiView):
    """ElectricityUser view"""

    queryset = electricityuser_queryset.get_all_electricityuser
    serializer_class = ElectricityUserSerializer
    filter_class = ElectricityUserFilter

    @swagger_auto_schema(operation_description="户号列表",
                         manual_parameters=[
                             openapi.Parameter("keywords",
                                               openapi.IN_QUERY,
                                               description="关键字",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                         ],
                         tags=["ElectricityUser"],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(ElectricityUserSerializer,
                                                     many=True)
                         })
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')

        if not pk:
            # queryset = self.filter_queryset(self.get_queryset())
            # # 管理员账号根据公司做数据隔离
            # if self.is_manager:
            #     queryset = queryset.filter(
            #         customer__service_enterprise=self.enterprise)
            # page = self.paginate_queryset(queryset)
            # if page:
            #     serializer = ElectricityUserListSerializer(page, many=True)
            #     return self.get_paginated_response(serializer.data)
            # serializer = ElectricityUserListSerializer(queryset, many=True)
            # data = general_message(msg='success',
            #                        msg_show='获取列表成功',
            #                        list=serializer.data)
            # return Response(data, status=status.HTTP_200_OK)
            query = request.GET.copy()
            page = query.get("page", 1)
            page_size = query.get("page_size", 10)
            query.update({"page": page, "page_size": page_size})
            rst, count = electricityuser_sql_repo.get_electricity_user(
                self.enterprise_ids, **query)
            data = general_message(msg='success',
                                   msg_show='获取列表成功',
                                   list=rst,
                                   count=count,
                                   page_size=page_size,
                                   page=page)
            return Response(data, status=status.HTTP_200_OK)
        else:
            queryset = electricityuser_repo.get_electricity_user(pk)
            serializer = ElectricityUserDetailSerializer(queryset)
            data = general_message(msg='success',
                                   msg_show='获取详情成功',
                                   bean=serializer.data)
            return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="添加户号",
                         request_body=ElectricityUserSerializer,
                         tags=['ElectricityUser'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(ElectricityUserSerializer)
                         })
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        queryset = electricityuser_repo.get_electricity_user(
            serializer.data['id'])
        res_serializer = ElectricityUserDetailSerializer(queryset)
        data = general_message(code=100000,
                               msg="success",
                               msg_show="创建成功",
                               bean=res_serializer.data)
        return Response(data, status=status.HTTP_201_CREATED)

    @swagger_auto_schema(operation_description="修改户号",
                         request_body=ElectricityUserSerializer,
                         tags=['ElectricityUser'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(ElectricityUserSerializer)
                         })
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        if not pk:
            raise ValidationError("参数错误")
        else:
            instance = electricityuser_repo.get_electricity_user(pk)
            if not instance:
                raise ValidationError("参数错误")
            else:
                serializer = ElectricityUserUpdateSerializer(instance, request.data)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                queryset = electricityuser_repo.get_electricity_user(
                    kwargs.get("id"))
                res_serializer = ElectricityUserDetailSerializer(queryset)
                data = general_message(code=100000,
                                       msg="success",
                                       msg_show="修改成功",
                                       bean=res_serializer.data)
                return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="修删除户号",
                         manual_parameters=[
                             openapi.Parameter("id",
                                               openapi.IN_QUERY,
                                               description="户号ID",
                                               required=True,
                                               type=openapi.TYPE_STRING),
                         ],
                         tags=['ElectricityUser'],
                         responses={status.HTTP_200_OK: "删除成功"})
    def delete(self, request, *args, **kwargs):
        service = electricity_service
        pk_list = request.data['id'].strip(',').split(',')
        if not pk_list:
            raise ValidationError("没有id")
        if not isinstance(pk_list, list):
            raise ValidationError('需要一个列表')
        try:
            service.delete_electricty_user(pk_list)
            data = general_message(msg='success', msg_show='删除成功')
            return Response(data, status=status.HTTP_200_OK)
        except Exception as e:
            data = general_message(msg='fail', msg_show=e)
            return Response(data, status=status.HTTP_400_BAD_REQUEST)


class ElectricityUserFileView(views.BaseApiView):
    queryset = electricityuser_queryset.get_all_electricityuser
    serializer_class = ElectricityUserSerializer

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        if pk:
            raise ValidationError('无效参数')
        else:
            excel_operator_obj = ExcelOperator()
            queryset = self.filter_queryset(self.get_queryset())
            if request.GET.get("page"):
                page = self.paginate_queryset(queryset)
                serializer = ElectricityUserListSerializer(page, many=True)
                url = excel_operator_obj.excel_export(
                    serializer.data, 'ElectricityUserList',
                    'ElectricityUserList_map')
                data = general_message(msg='success',
                                       msg_show='导出列表成功',
                                       bean=url)
                return Response(data, status=status.HTTP_200_OK)
            serializer = ElectricityUserListSerializer(queryset, many=True)
            url = excel_operator_obj.excel_export(serializer.data,
                                                  'ElectricityUserList',
                                                  'ElectricityUserList_map')
            data = general_message(msg='success', msg_show='导出列表成功', bean=url)
            return Response(data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        url = request.data.get('url')
        if url is None:
            raise ValidationError("需要传入url")
        excel_operator_obj = ExcelOperator()
        data_list = excel_operator_obj.excel_import(url,
                                                    'ElectricityUserDetail')
        for data in data_list:
            pk = data['id']
            if data['id'] == '':
                data['customer'] = Customer.objects.filter(
                    id=data['customer']).first().id
                serializer = self.get_serializer(data=data)
                serializer.is_valid(raise_exception=True)
                serializer.save()
            else:
                pk = int(float(pk))
                data['customer'] = Customer.objects.filter(
                    id=data['customer']).first().id
                instance = electricityuser_repo.get_electricity_user(pk)
                if not instance:
                    raise ValidationError("参数错误")
                else:
                    serializer = self.get_serializer(instance, data)
                    serializer.is_valid(raise_exception=True)
                    # data = serializer.validated_data
                    serializer.save()
        return self.get_list(request, *args, **kwargs)


class ElectricityUserLView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET
        rst, count = electricityuser_sql_repo.get_electricity_user(
            self.enterprise_ids, **query)
        data = general_message(msg='success',
                               msg_show='获取列表成功',
                               list=rst,
                               count=count)
        return Response(data, status=status.HTTP_200_OK)
