import logging
import datetime

from django.views.decorators.gzip import gzip_page
from django.utils.decorators import method_decorator
from rest_framework import status
from rest_framework.response import Response

from common.accounts.serializers import UsersLCSerializer
from common.third_party_api.amap.openapi import AmapApi
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, error_message
from .filters import CustomerFilter, CustomerReportPDFFilter
from .models import Customer, CustomerReport
from .repositories import (customer_queryset, custom_admin_queryset)
from .serializers import (CustomerListSerializer, ContactSerializer,
                          CustomerAdminSerializer, CustomerCSerializer,
                          CustomerUSerializer, CustomerReportUploadSerializer,
                          CustomerReportInfoSerializer, BasicConfirmSerializer,
                          SupperConfirmSerializer)
from .services import customer_service, custom_admin_service
from ..electricityuser.models import ElectricityUser

logger = logging.getLogger('')


@method_decorator(gzip_page, name='dispatch')
class CustomerView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        query = request.GET.copy()
        page = query.get("page", 1)
        page_size = query.get("page_size", 10)
        query.update({"page": page, "page_size": page_size})
        if id:
            query.update({"id": str(id)})
            rst = customer_service.customers_info(
                self.enterprise_ids, **query)
            data = general_message(bean=rst)
        else:
            rst, count = customer_service.get_customers(
                self.enterprise_ids, **query)
            data = general_message(list=rst, count=count)
        return Response(data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        serializer = CustomerCSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        customer = customer_service.create_customer_info(serializer.data)
        customers_info= customer_service.customers_info(
            self.enterprise_ids, id=str(customer.id))
        data = general_message(bean=customers_info)
        return Response(data, status=status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        serializer = CustomerUSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        customer_service.update_customer_info(serializer.data)
        customers_info= customer_service.customers_info(
            self.enterprise_ids, id=serializer.data.get("id"))
        data = general_message(msg_show='修改成功', bean=customers_info)
        return Response(data, status=status.HTTP_200_OK)

    def delete(self, request, *args, **kwargs):
        pk_list = request.data['id'].strip(',').split(',')
        if not pk_list:
            raise ValidationError("没有id")
        if not isinstance(pk_list, list):
            raise ValidationError('需要一个列表')
        customer_service.delete_customer(pk_list)
        data = general_message(msg='success', msg_show='删除成功')
        return Response(data, status=status.HTTP_200_OK)


@method_decorator(gzip_page, name='dispatch')
class CustomerInfoView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        page = query.get("page", 1)
        page_size = query.get("page_size", 10)
        query.update({"page": page, "page_size": page_size})
        customers_info, count = customer_service.get_customers(
            self.enterprise_ids, **query)
        data = general_message(list=customers_info, count=count)
        return Response(data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        serializers = CustomerCSerializer(data=request.data)
        serializers.is_valid(raise_exception=True)
        customer = customer_service.create_customer_info(serializers.data)
        customers_info, count = customer_service.get_customers(
            self.enterprise_ids, id=str(customer.id))
        data = general_message(bean=customers_info[0])
        return Response(data, status=status.HTTP_200_OK)


class CustomerAdminView(views.BaseApiView):
    """Customer view"""
    queryset = custom_admin_queryset.get_all_customer_admin
    serializer_class = CustomerAdminSerializer

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

    def post(self, request, *args, **kwargs):
        if 'customer_admin_list' not in request.data:
            raise ValidationError("参数错误")
        data = request.data['customer_admin_list']
        if not isinstance(data, list):
            raise ValidationError("参数类型错误")
        req_data = custom_admin_service.trans_data(data)
        serializer = UsersLCSerializer(data=req_data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        data = general_message(code=100000,
                               msg="success",
                               msg_show="创建成功",
                               list=serializer.data)
        return Response(data, status=status.HTTP_201_CREATED)

    def delete(self, request, *args, **kwargs):
        pk_list = request.data['id'].strip(',').split(',')
        logger.info('pk_list: <%s>', pk_list)
        if not pk_list:
            raise ValidationError("没有id")
        if not isinstance(pk_list, list):
            raise ValidationError('需要一个列表')
        try:
            custom_admin_service.delete_customer_admin(pk_list,
                                                       self.enterprise_entids)
            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 CustomerAdminDView(views.BaseApiView):
    def delete(self, request, customer_id, id, *args, **kwargs):
        custom_admin_service.delete_customer_admin_by_id(id, customer_id)
        data = general_message(msg='success', msg_show='删除成功')
        return Response(data, status=status.HTTP_200_OK)


class CustomerFileView(views.BaseApiView):
    queryset = customer_queryset.get_all_customer
    serializer_class = CustomerListSerializer
    filter_class = CustomerFilter

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


class GetDistrictView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        province = request.query_params.get('province')
        city = request.query_params.get('city')
        if province is None:
            if city:
                raise ValidationError("请输入省份")
            province_data = []
            districts = AmapApi().district()['districts'][0]['districts']
            for item in districts:
                if item['level'] == 'province':
                    province_data.append(item['name'])
            data = general_message(msg='success',
                                   msg_show='查询成功',
                                   list=province_data)
        else:
            city = request.query_params.get('city')
            if city is None:
                city_data = []
                districts = AmapApi().district(
                    keywords=province)['districts'][0]['districts']
                for item in districts:
                    if item['level'] == 'city':
                        city_data.append(item['name'])
                data = general_message(msg='success',
                                       msg_show='查询成功',
                                       list=city_data)
            else:
                area_data = []
                districts = AmapApi().district(
                    keywords=city)['districts'][0]['districts']
                for item in districts:
                    if item['level'] == 'district':
                        area_data.append(item['name'])
                data = general_message(msg='success',
                                       msg_show='查询成功',
                                       list=area_data)
        return Response(data, status=status.HTTP_200_OK)


@method_decorator(gzip_page, name='dispatch')
class ContactView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        rst = customer_service.get_contacts(**query)
        data = general_message(list=rst)
        return Response(data, status=200)

    def post(self, request, *args, **kwargs):
        serializer = ContactSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        contact = customer_service.create_customer_contact(serializer.data)
        rst = customer_service.get_contacts(customer_id=str(
            serializer.data.get("customer_id")),
            id=str(contact.id))
        data = general_message(bean=rst)
        return Response(data, status=200)

    def put(self, request, *args, **kwargs):
        serializer = ContactSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        contact = customer_service.update_customer_contact(serializer.data)
        rst = customer_service.get_contacts(customer_id=str(
            serializer.data.get("customer_id")),
            id=str(contact.id))
        data = general_message(bean=rst)
        return Response(data, status=200)

    def delete(self, request, *args, **kwargs):
        contact_id = request.data.get("id")
        customer_service.delete_customer_contact(contact_id)
        data = general_message(msg_show="删除成功")
        return Response(data, status=200)


class ContactDView(views.BaseApiView):
    def delete(self, request, customer_id, id, *args, **kwargs):
        customer_service.delete_customer_contact(id)
        data = general_message(msg_show="删除成功")
        return Response(data, status=200)


@method_decorator(gzip_page, name='dispatch')
class ReportLView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        if self.is_customer:
            customer = Customer.objects.filter(enterprise_id=self.enterprise_ids[0]).first()
            self.enterprise_ids = [str(customer.service_enterprise.id)] if \
                customer and customer.service_enterprise else []
        year_month = request.GET.get("year_month")
        customer_ids = request.GET.getlist("customer_id", [])
        if not year_month:
            raise ValidationError("缺少year_month参数")
        rst, count = customer_service.customers_report(self.enterprise_ids,
                                                       year_month,
                                                       customer_ids)
        data = general_message(list=rst, count=count, page_size=0, page=0)
        return Response(data, status=200)


class ReportRView(views.BaseApiView):
    def get(self, request, electrical_user_id, *args, **kwargs):
        year_month = request.GET.get("year_month")
        if not year_month:
            raise ValidationError("缺少year_month参数")
        old_month = str(
            datetime.datetime.strptime(year_month, '%Y-%m').date() +
            datetime.timedelta(days=-1))[:7]
        rst = customer_service.customers_report_info(electrical_user_id,
                                                     year_month, old_month)
        data = general_message(bean=rst)
        return Response(data, status=200)


class ReportExportView(views.BaseApiView):
    def post(self, request, *args, **kwargs):
        year_month = request.data.get("year_month")
        if not year_month:
            raise ValidationError("缺少year_month参数")
        electrical_user_ids = request.data.get("electrical_user_ids")
        if not electrical_user_ids:
            raise ValidationError("electrical_user_ids")
        old_month = str(
            datetime.datetime.strptime(year_month, '%Y-%m').date() +
            datetime.timedelta(days=-1))[:7]
        rst = customer_service.customers_report_list_info(electrical_user_ids,
                                                          year_month, old_month)
        data = general_message(list=rst)
        return Response(data, status=200)


@method_decorator(gzip_page, name='dispatch')
class CustomerMapView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        query.update({"enterprise_ids": self.enterprise_ids})
        rst = customer_service.get_customer_map(**query)
        data = general_message(list=rst)
        return Response(data, status=200)


@method_decorator(gzip_page, name='dispatch')
class CustomerElectricMapView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        strict = int(request.GET.get("strict", 1))
        if strict == 1:
            rst = customer_service.get_customer_electric_map(**query)
        else:
            rst = customer_service.get_ele_map(**query)
        data = general_message(list=rst)
        return Response(data, status=200)


@method_decorator(gzip_page, name='dispatch')
class MapLView(views.BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        rst = customer_service.get_map(self.enterprise_ids, **query)
        data = general_message(list=rst)
        return Response(data, status=200)


class CustomerReportUploadView(views.BaseApiView):
    queryset = CustomerReport.objects.filter()
    serializer_class = CustomerReportUploadSerializer

    def post(self, request, *args, **kwargs):
        ele_user = ElectricityUser.objects.filter(id=request.data.get("ele_user_id")).first()
        customer_report = self.get_queryset().filter(customer_id=request.data.get("customer_id"),
                                                     report_id=request.data.get("report_id"),
                                                     year_month=request.data.get("year_month"),
                                                     power_number=ele_user.number if ele_user else None).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 CustomerReportPDFView(views.BaseApiView):
    queryset = CustomerReport.objects.filter()
    filter_class = CustomerReportPDFFilter
    serializer_class = CustomerReportInfoSerializer

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = CustomerReportInfoSerializer(queryset, many=True)
        ele_user = ElectricityUser.objects.filter(customer_id=request.GET.get("customer_id"))
        result = []
        for item in ele_user:
            customer_report = CustomerReport.objects.filter(
                power_number=item.number,
                year_month=request.GET.get("year_month")).first()
            result.append({"url": "https://report-1302976931.cos.ap-shanghai.myqcloud.com/{}/{}_{}.pdf".format(
                request.GET.get("year_month"), item.number, request.GET.get("year_month")
            ),
                "power_number": item.number,
                "confirm": customer_report.supper_confirm if customer_report else None,
                "confirm_time": customer_report.supper_confirm_time if customer_report else None})
        return Response(general_message(list=serializer.data, bean=result if serializer.data else []))


class BasicConfirmView(views.BaseApiView):

    def put(self, request, *args, **kwargs):
        instance = CustomerReport.objects.filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=400, msg_show="客户报告不存在"))
        serializer = BasicConfirmSerializer(instance, 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 SupperConfirmView(BasicConfirmView):
    def put(self, request, *args, **kwargs):
        instance = CustomerReport.objects.filter(power_number=request.data.get("power_number"),
                                                 year_month=request.data.get("year_month")).first()
        if not instance:
            return Response(error_message(code=400, msg_show="客户报告不存在"))
        serializer = SupperConfirmSerializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("确认成功"))
        return Response(error_message(code=400, msg_show="确认失败", msg=serializer.errors))
