from rest_framework import status
from rest_framework.response import Response

from common.utils.views import BaseApiView
from common.utils.views import general_message
from crm.crm_users.serializers import ImportUsersSerializer

from crm.crm_users.services import crm_user_service


class CrmUsersLView(BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        page = request.GET.get("page", 1)
        page_size = request.GET.get("page_size", 10)
        rst, count = crm_user_service.get_users(self.enterprise.id, **query)
        data = general_message(list=rst, count=count, page=page, page_size=page_size)
        return Response(data, status=status.HTTP_200_OK)


class CrmUsersSimpleLView(BaseApiView):
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        rst = crm_user_service.get_users_simple(self.enterprise.id, **query)
        data = general_message(list=rst)
        return Response(data, status=status.HTTP_200_OK)

class CrmUsersRDView(BaseApiView):
    def get(self, request, user_id, *args, **kwargs):
        rst = crm_user_service.get_user_info(self.enterprise.id, user_id)
        data = general_message(bean=rst)
        return Response(data, status=status.HTTP_200_OK)

    def delete(self, request, user_id, *args, **kwargs):
        crm_user_service.delete_user(self.enterprise.id, user_id)
        data = general_message(msg_show="删除成功")
        return Response(data, status=status.HTTP_200_OK)


class CrmUsersImportView(BaseApiView):
    def post(self, request, *args, **kwargs):
        serializer = ImportUsersSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        crm_user_service.import_users(self.enterprise.id, serializer.data.get("user_list"))
        data = general_message(msg_show="导入成功")
        return Response(data, status=status.HTTP_200_OK)
