import logging
from time import strptime

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 .repositories import (team_queryset, team_repo, teamschedule_queryset,
                           teamschedule_repo, handoverrecord_queryset)
from .serializers import (TeamSerializer, TeamScheduleSerializer,
                          HandOverRecordSerializer,
                          HandOverRecordListSerializer, TeamFileSerializer,
                          TeamScheduleFileSerializer,
                          HandOverRecordFileSerializer,
                          HandOverRecordDutySerializer,
                          HandOverRecordDispatchSerializer, TeamIDSerializer)
from .filters import (TeamFilter, TeamScheduleFilter, HandOverFilter)
from .services import team_service, team_schedule_service

logger = logging.getLogger('')


class TeamView(views.ManagerApiView):
    """
    Team View
    """
    queryset = team_queryset.get_all_team
    serializer_class = TeamSerializer
    filter_class = TeamFilter

    @swagger_auto_schema(operation_description="班组列表",
                         manual_parameters=[
                             openapi.Parameter("keyword",
                                               openapi.IN_QUERY,
                                               description="关键字",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("type",
                                               openapi.IN_QUERY,
                                               description="类型",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                         ],
                         tags=["Team"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(TeamSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        self.queryset = self.queryset.filter(
            enterprise_id__in=self.enterprise_ids)
        if not pk:
            return self.get_list(request, *args, **kwargs)
        queryset = self.queryset.filter(id=pk)
        if not queryset:
            raise ValidationError("没有找到该id")
        serializer = TeamIDSerializer(queryset.first())
        data = general_message(msg='success',
                               msg_show='获取详情成功',
                               bean=serializer.data)
        return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(
        operation_description="Team",
        request_body=TeamSerializer,
        tags=['Team'],
        responses={status.HTTP_200_OK: serializer_assembly(TeamSerializer)})
    def post(self, request, *args, **kwargs):
        request.data.update(enterprise=self.enterprise.id)
        return self.create(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_description="修改班组",
        request_body=TeamSerializer,
        tags=['Team'],
        responses={status.HTTP_200_OK: serializer_assembly(TeamSerializer)})
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        if not pk:
            raise ValidationError("没有传入id")
        if not request.data.get('id'):
            raise ValidationError('请在数据中传入id')
        instance = self.queryset.filter(enterprise_id__in=self.enterprise_ids,
                                        id=pk).first()
        if not instance:
            raise ValidationError("没有找到对象")
        else:
            serializer = TeamIDSerializer(instance, request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            data = general_message(msg='success',
                                   msg_show='修改成功',
                                   bean=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_ARRAY,
                                               items=openapi.TYPE_INTEGER),
                         ],
                         tags=['Team'],
                         responses={status.HTTP_200_OK: "删除成功"})
    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:
            team_service.delete_team(pk_list, self.enterprise_ids)
            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 TeamScheduleView(views.BaseApiView):
    queryset = teamschedule_queryset.get_all_teamschedule
    serializer_class = TeamScheduleSerializer
    filter_class = TeamScheduleFilter

    @swagger_auto_schema(operation_description="排班列表",
                         manual_parameters=[
                             openapi.Parameter("team",
                                               openapi.IN_QUERY,
                                               description="班组",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("month",
                                               openapi.IN_QUERY,
                                               description="月份",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                         ],
                         tags=["TeamSchedule"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(TeamScheduleSerializer,
                                                 many=True)
                         })
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        if not pk:
            if not (request.query_params.get('team_name')
                    or request.query_params.get('team')):
                raise ValidationError("需要输入班组名称或id")
            if not request.query_params.get('schedule_date'):
                raise ValidationError("需要输入月份")
            return self.get_list(request, *args, **kwargs)
        else:
            queryset = teamschedule_repo.get_team_schedule(pk)
            serializer = TeamScheduleSerializer(queryset)
            data = general_message(msg='success',
                                   msg_show='获取详情成功',
                                   list=serializer.data)
            return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="新建排班",
                         request_body=TeamScheduleSerializer,
                         tags=['TeamSchedule'],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(TeamScheduleSerializer)
                         })
    def post(self, request, *args, **kwargs):
        data = request.data['teamschedule_list']
        if not isinstance(data, list):
            raise ValidationError("参数类型错误")
        else:
            team = data[0]['team']
            date = strptime((data[0]['schedule_date']), "%Y-%m-%d")
            team_schedule_service.delete_team(team, date)
            serializer = self.get_serializer(data=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):
        team_id = request.data.get('team_id')
        date = request.data.get('schedule_data')
        if not team_id:
            raise ValidationError('需要输入班组id')
        if not date:
            raise ValidationError('需要输入排班月份')
        try:
            team_schedule_service.delete_team_schedule(team_id, date)
            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 HandOverView(views.BaseApiView):
    """
    HandOver View
    """
    queryset = handoverrecord_queryset.get_all_handoverrecord
    serializer_class = HandOverRecordSerializer
    filter_class = HandOverFilter

    @swagger_auto_schema(operation_description="交接班列表",
                         manual_parameters=[
                             openapi.Parameter("powerstation",
                                               openapi.IN_QUERY,
                                               description="电站",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("data",
                                               openapi.IN_QUERY,
                                               description="日期",
                                               required=False,
                                               type=openapi.TYPE_INTEGER),
                             openapi.Parameter("transfer_team",
                                               openapi.IN_QUERY,
                                               description="交班班组",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("recieve_team",
                                               openapi.IN_QUERY,
                                               description="接班班组",
                                               required=False,
                                               type=openapi.TYPE_STRING),
                         ],
                         tags=["HandOver"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(HandOverRecordListSerializer,
                                                 many=True)
                         })
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        self.queryset = self.queryset.filter(
            transfer_team__enterprise=self.enterprise)
        if not pk:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            if page:
                serializer = HandOverRecordListSerializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            serializer = HandOverRecordListSerializer(queryset, many=True)
            data = general_message(msg='success',
                                   msg_show='获取列表成功',
                                   list=serializer.data)
            return Response(data, status=status.HTTP_200_OK)
        else:
            queryset = self.queryset.filter(id=pk).first()
            type = queryset.type
            if not type:
                return ValidationError("需要出入交接班类型")
            if type == '1':
                serializer = HandOverRecordDutySerializer(queryset)
            elif type == '0':
                serializer = HandOverRecordDispatchSerializer(queryset)
            else:
                raise ValidationError("需要出入正确的交接班类型")
            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=HandOverRecordSerializer,
        tags=['HandOver'],
        responses={status.HTTP_200_OK: serializer_assembly(TeamSerializer)})
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class TeamFileView(views.BaseApiView):
    queryset = team_queryset.get_all_team
    serializer_class = TeamFileSerializer
    filter_class = TeamFilter

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        self.queryset = self.queryset.filter(
            enterprise_id__in=self.enterprise_ids)
        excel_operator_obj = ExcelOperator()
        if pk:
            raise ValidationError('无效参数id')
        else:
            id = request.data.get('id')
            if not id:
                queryset = self.filter_queryset(self.get_queryset())
            else:
                pk_list = request.data['id'].strip(',').split(',')
                logger.info('pk_list: <%s>', pk_list)
                if not isinstance(pk_list, list):
                    raise ValidationError('需要一个列表')
                queryset = team_repo.get_teams(pk_list)
            # page = self.paginate_queryset(queryset)
            # if page:
            #     serializer = TeamFileSerializer(page, many=True)
            #     url = excel_operator_obj.excel_export(serializer.data,
            #                                           'TeamList',
            #                                           key_map='Team_map')
            #     data = general_message(msg='success',
            #                            msg_show='导出列表成功',
            #                            bean=url)
            #     return Response(data, status=status.HTTP_200_OK)
            serializer = TeamFileSerializer(queryset, many=True)
            url = excel_operator_obj.excel_export(serializer.data,
                                                  'TeamList',
                                                  key_map='Team_map')
            data = general_message(msg='success', msg_show='导出列表成功', bean=url)
            return Response(data, status=status.HTTP_200_OK)


class TeamScheduleFileView(views.BaseApiView):
    queryset = teamschedule_queryset.get_all_teamschedule
    serializer_class = TeamScheduleFileSerializer
    filter_class = TeamScheduleFilter

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        self.queryset = self.queryset.filter(team__enterprise=self.enterprise)
        excel_operator_obj = ExcelOperator()
        if pk:
            raise ValidationError('无效参数id')
        else:
            queryset = self.filter_queryset(self.get_queryset())
            if not queryset.exists():
                raise ValidationError('输入的列表为空')
            page = self.paginate_queryset(queryset)
            if page:
                serializer = TeamScheduleFileSerializer(page, many=True)
                url = excel_operator_obj.excel_export(
                    serializer.data,
                    'TeamScheduleList',
                    key_map='TeamSchedule_map')
                data = general_message(msg='success',
                                       msg_show='导出列表成功',
                                       bean=url)
                return Response(data, status=status.HTTP_200_OK)
            serializer = TeamScheduleFileSerializer(queryset, many=True)
            url = excel_operator_obj.excel_export(serializer.data,
                                                  'TeamScheduleList',
                                                  key_map='TeamSchedule_map')
            data = general_message(msg='success', msg_show='导出列表成功', bean=url)
            return Response(data, status=status.HTTP_200_OK)


class HandOverFileView(views.BaseApiView):
    queryset = handoverrecord_queryset.get_all_handoverrecord
    serializer_class = HandOverRecordFileSerializer
    filter_class = HandOverFilter

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        self.queryset = self.queryset.filter(
            transfer_team__enterprise=self.enterprise)
        excel_operator_obj = ExcelOperator()
        if pk:
            raise ValidationError('无效参数id')
        else:
            queryset = self.filter_queryset(self.get_queryset())
            if not queryset.exists():
                raise ValidationError('输入的列表为空')
            page = self.paginate_queryset(queryset)
            if page:
                serializer = HandOverRecordFileSerializer(page, many=True)
                url = excel_operator_obj.excel_export(serializer.data,
                                                      'HandOverList',
                                                      key_map='HandOver_map')
                data = general_message(msg='success',
                                       msg_show='导出列表成功',
                                       bean=url)
                return Response(data, status=status.HTTP_200_OK)
            serializer = HandOverRecordFileSerializer(queryset, many=True)
            url = excel_operator_obj.excel_export(serializer.data,
                                                  'HandOverList',
                                                  key_map='HandOver_map')
            data = general_message(msg='success', msg_show='导出列表成功', bean=url)
            return Response(data, status=status.HTTP_200_OK)
