from rest_framework import status
from rest_framework.response import Response

from common.utils import views
from common.utils.exceptions import ValidationError
from common.utils.return_structure import general_message
from console.electrical_info.repositories import (electrical_info_queryset,
                                                  electrical_info_repo)
from console.electrical_info.serializers import (ElectricalInfromationSerializer,
                                                 ElectricalInfromationCSerializer)
from console.electrical_info.services import electrical_info_service

from console.electrical_info.filters import EleInfoFilter

from console.electrical_info.services import create_outline

from console.powerstation.models import Outline

from console.electrical_info.filters import OutlineFilter
from console.electrical_info.serializers import OutLineSerializer


class ElectricalInfromationView(views.BaseApiView):
    """
    ElectricalInfromation view
    """
    queryset = electrical_info_queryset.get_all_electrical_info
    serializer_class = ElectricalInfromationSerializer
    filter_class = EleInfoFilter

    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        query = request.GET.copy()
        page = query.get("page")
        page_size = query.get("page_size")
        query.update({"page": page, "page_size": page_size})
        if id:
            query.update({"id": str(id)})
        dt, count = electrical_info_service.get_electrical_info(
            self.enterprise_ids, **query)
        if id:
            data = general_message(bean=dt[0])
        else:
            data = general_message(list=dt, count=count)
        return Response(data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        data = request.data.get('electrical_info_list')
        if not data:
            raise ValidationError('请传入电气信息数据')
        if not isinstance(data, list):
            raise ValidationError('需要传入一个数组')
        serializer = ElectricalInfromationCSerializer(data=data, many=True)
        serializer.is_valid(raise_exception=True)
        dt = electrical_info_service.create_electrical_info(serializer.data)
        # serializer.save()
        data = general_message(code=100000,
                               msg="success",
                               msg_show="创建成功",
                               list=dt)
        # 同步创建出线侧
        create_outline(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED)

    def put(self, request, *args, **kwargs):
        pk = kwargs.get('id')
        if not pk:
            raise ValidationError('需要传入id')
            # data = request.data.get('electrical_info_list')
            # if not data:
            #     raise ValidationError('请传入电气信息数据')
            # if not isinstance(data, list):
            #     raise ValidationError('需要传入一个数组')
            # pks = []
            # for dic in data:
            #     pk = dic.pop('id')
            #     pks.append(pk)
            # queryset = electrical_info_repo.get_electrical_infos(pks)
            # serializer = self.get_serializer(instance =queryset,
            # data=data, many=True)
            # serializer.is_valid(raise_exception=True)
            # serializer.save()
            # data = general_message(code=100000,
            #                        msg="success",
            #                        msg_show="创建成功",
            #                        list=serializer.data)
        else:
            instance = electrical_info_repo.get_electrical_info(pk)
            serializer = self.get_serializer(instance, request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            data = general_message(code=100000,
                                   msg="success",
                                   msg_show="更新成功",
                                   bean=serializer.data)
            return Response(data, status=status.HTTP_201_CREATED)

    def delete(self, request, *args, **kwargs):
        service = electrical_info_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_electrical_info(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 OutLineListView(views.BaseApiView):
    queryset = Outline.objects.filter(deleted=False)
    serializer_class = OutLineSerializer
    filter_class = OutlineFilter

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