# Create your views here.
from common.utils.views import BaseApiView

from console.sim_card.models import SimCard

from console.sim_card.serializers import SimCardSerializer
from rest_framework.response import Response

from common.utils.return_structure import general_message, error_message

from common.utils.service_code import PARAMETER_ERROR

from console.sim_card.services import import_sim_card

from console.sim_card.services import get_sim_card_list


class SimCardListView(BaseApiView):

    def get(self, request, *args, **kwargs):
        data = get_sim_card_list(**{
            "keyword": request.GET.get("keyword"),
            "end_time": request.GET.get("end_time"),
            "order_by": request.GET.get("order_by")
        })

        return Response(general_message(list=data))


class SimCardInfoView(BaseApiView):
    queryset = SimCard.objects.filter(deleted=False)
    serializer_class = SimCardSerializer

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


class SimCardCreateView(BaseApiView):
    serializer_class = SimCardSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("新增成功"))
        return Response(
            error_message(code=PARAMETER_ERROR,
                          msg_show="新增失败",
                          msg=serializer.errors))


class SimCardUpdateView(BaseApiView):
    serializer_class = SimCardSerializer

    def put(self, request, *args, **kwargs):
        sim_card = SimCard.objects.filter(id=kwargs.get("id")).first()
        if not sim_card:
            return Response(
                error_message(code=PARAMETER_ERROR, msg_show="sim卡不存在"))
        serializer = self.get_serializer(sim_card, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("修改成功"))
        return Response(
            error_message(code=PARAMETER_ERROR,
                          msg=serializer.errors,
                          msg_show="修改失败"))


class SimCardDeleteView(BaseApiView):
    queryset = SimCard.objects.filter(deleted=False)

    def delete(self, request, *args, **kwargs):
        sim_card = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not sim_card:
            return Response(
                error_message(code=PARAMETER_ERROR, msg_show="sim卡不存在"))
        sim_card.deleted = True
        sim_card.save()
        return Response(general_message("删除成功"))


class SimCardImport(BaseApiView):
    def post(self, request, *args, **kwargs):
        file = request.FILES.get('file')
        import_sim_card(file)
        return Response(general_message("导入成功"))
