#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import logging

from django.contrib import auth
from django.db.transaction import atomic
from django.db.models import F
from django.views.decorators.gzip import gzip_page
from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework import status, mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import (JSONWebTokenAPIView,
                                      jwt_response_payload_handler)

from common.utils.views import BaseApiView, ManagerApiView, ManagerUserApiView
from common.utils.serializers import serializer_assembly
from common.utils.exceptions import ValidationError
from common.utils.return_structure import general_message
from common.utils.perms_conf import CONFIG
from console.customer.services import customer_service

from .models import Users
from .serializers import (CustomJWTSerializer, JWTSerializer, LogoutSerializer,
                          AccountUpdateSerializer, UsersLCSerializer,
                          RoleLCSerializer, UserRolesLCSerializer,
                          UserRolesMultiCSerializer, TagsLCSerializer,
                          TagsRSerializer, UserTagsLCSerializer,
                          UserTagsMultiCSerializer, UsersRSerializer,
                          TagUsersLSerializer, RolePermsSerializer,
                          UserCSerializer, UserUSerializer, UserPasswordSerializer,
                          UserCenterUSerializer)
from .repositories import user_queryset
from .services import user_service
from .filters import (UsersLFilter, RolesFilter, TagsFilter)

logger = logging.getLogger('')


class JWTTokenView(JSONWebTokenAPIView):
    serializer_class = CustomJWTSerializer

    @swagger_auto_schema(
        operation_description="登录",
        request_body=CustomJWTSerializer,
        responses={200: JWTSerializer()},
        tags=['account'],
    )
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid()
        user = serializer.object.get('user') or request.user
        token = serializer.object.get('token')
        response_data = jwt_response_payload_handler(token, user, request)
        rst_data = JWTSerializer(data=response_data)
        rst_data.is_valid(raise_exception=True)
        response = Response(rst_data.data, status=status.HTTP_200_OK)
        if api_settings.JWT_AUTH_COOKIE:
            expiration = (datetime.datetime.now() +
                          api_settings.JWT_EXPIRATION_DELTA)
            response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                token,
                                expires=expiration,
                                httponly=True)
        return response


class LogoutView(BaseApiView):
    permission_classes = (IsAuthenticated,)
    serializer_class = LogoutSerializer

    @swagger_auto_schema(
        operation_description="登出",
        responses={},
        tags=['account'],
    )
    def post(self, request):
        auth.logout(request)
        logger.info('User <%s> logout success', request.user.username)
        response = Response(status=status.HTTP_200_OK)
        response.delete_cookie(api_settings.JWT_AUTH_COOKIE)
        return response


class SetPassword(BaseApiView, mixins.UpdateModelMixin):
    serializer_class = AccountUpdateSerializer
    permission_classes = ()
    queryset = user_queryset.set_password
    renderer_classes = (JSONRenderer, BrowsableAPIRenderer)
    lookup_field = 'id'

    @swagger_auto_schema(
        tags=['account'], )
    def put(self, request, *args, **kwargs):
        super(SetPassword, self).update(self, request, *args, **kwargs)

    @swagger_auto_schema(
        tags=['account'], )
    def patch(self, request, *args, **kwargs):
        super(SetPassword, self).partial_update(self, request, *args, **kwargs)


class UserLCView(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 = user_service.get_user(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)

    def post(self, request, *args, **kwargs):
        serializer = UserCSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = user_service.create_user(self.enterprise, self.user, serializer.data)
        rst = user_service.get_user_info(self.enterprise_id, user.id)
        data = general_message(bean=rst, msg_show="创建成功")
        return Response(data, status=status.HTTP_200_OK)


class UserRUDView(BaseApiView):
    def get(self, request, user_id, *args, **kwargs):
        rst = user_service.get_user_info(self.enterprise_id, user_id)
        data = general_message(bean=rst)
        return Response(data, status=status.HTTP_200_OK)

    def put(self, request, user_id, *args, **kwargs):
        serializer = UserUSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user_service.update_user(self.enterprise, user_id, serializer.data)
        rst = user_service.get_user_info(self.enterprise_id, user_id)
        data = general_message(bean=rst, msg_show="编辑成功")
        return Response(data, status=status.HTTP_200_OK)

    def delete(self, request, user_id, *args, **kwargs):
        user_service.del_user(user_id, self.enterprise_id)
        data = general_message(msg_show="删除成功")
        return Response(data, status=status.HTTP_200_OK)


class UserCenterRUDView(BaseApiView):
    def get(self, request, *args, **kwargs):
        rst = user_service.get_user_center_info(self.enterprise_id, self.user.id)
        data = general_message(bean=rst)
        return Response(data, status=status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        serializer = UserCenterUSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user_service.update_user(self.enterprise, self.user.id, serializer.data)
        rst = user_service.get_user_center_info(self.enterprise_id, self.user.id)
        data = general_message(bean=rst, msg_show="编辑成功")
        return Response(data, status=status.HTTP_200_OK)


class UserCenterSetPassword(BaseApiView):
    def put(self, request, *args, **kwargs):
        serializer = UserPasswordSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user_service.set_password(self.user.id, serializer.data.get("password"))
        data = general_message(msg_show="修改密码成功")
        return Response(data, status=status.HTTP_200_OK)


class PasswordUView(BaseApiView):
    def put(self, request, user_id, *args, **kwargs):
        serializer = UserPasswordSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user_service.set_password(user_id, serializer.data.get("password"))


@method_decorator(gzip_page, name='dispatch')
class UsersLCView(BaseApiView):
    serializer_class = UsersLCSerializer
    queryset = user_queryset.users_lc
    filter_class = UsersLFilter

    @swagger_auto_schema(operation_description="获取用户列表",
                         tags=['user'],
                         manual_parameters=[
                             openapi.Parameter("user_id",
                                               openapi.IN_QUERY,
                                               description="用户id",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UsersRSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        choices = request.GET.get("choices", 0)
        self.serializer_class = UsersRSerializer
        if self.enterprise_id:
            self.queryset = self.queryset.prefetch_related("ent_user").filter(
                ent_user__deleted=False,
                ent_user__enterprise_id=self.enterprise_id)
        queryset = self.filter_queryset(self.get_queryset())
        if choices:
            rst = self.queryset.values("id",
                                       "nickname",
                                       username=F("account__username"))
            data = general_message(msg='success',
                                   msg_show='获取列表成功',
                                   list=rst,
                                   count=len(rst))
        else:
            page = self.paginate_queryset(queryset)
            if page:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            serializer = self.get_serializer(instance=queryset, many=True)
            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=UsersLCSerializer,
        tags=['user'],
        responses={status.HTTP_200_OK: serializer_assembly(UsersRSerializer)})
    @atomic()
    def post(self, request, *args, **kwargs):
        role_ids = request.data.get("role_ids")
        tag_ids = request.data.get("tag_ids")
        organization_ids = request.data.get("organization_ids")
        customer_id = request.data.get("customer_id")
        customer = request.data.get("customer", False)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        if customer:
            if customer_id:
                enterprise = customer_service.get_customer_enterprise(
                    customer_id)
                if not enterprise:
                    raise ValidationError("客户公司不存在")
                user_service.create_user_enterprises(serializer.data["id"],
                                                     enterprise.enterprise_id)
                customer_service.bind_customer_admin(customer_id,
                                                     serializer.data["id"])
            else:
                user_service.disabled_account(serializer.data["id"])
        else:
            user_service.create_user_enterprises(serializer.data["id"],
                                                 self.enterprise.enterprise_id)
            user_service.create_user_roles(serializer.data["id"], role_ids)
            user_service.create_user_tags(serializer.data["id"], tag_ids)
            user_service.create_user_organizations(serializer.data["id"],
                                                   organization_ids)
        print(serializer.data["id"])
        queryset = user_queryset.users_c.filter(
            id=serializer.data["id"]).first()
        print(queryset.to_dict())
        serializer = UsersRSerializer(instance=queryset)
        data = general_message(msg_show="创建成功", bean=serializer.data)
        return Response(data, status=status.HTTP_201_CREATED)


class UsersRUDView(BaseApiView):
    serializer_class = UsersRSerializer
    queryset = Users.objects.filter(deleted=False, account__is_active=True)

    def get(self, request, user_id, *args, **kwargs):
        self.queryset = self.queryset.filter(
            id=user_id).prefetch_related("ent_user").filter(
            ent_user__deleted=False,
            ent_user__enterprise_id__in=self.enterprise_entids)
        obj = self.get_queryset().first()
        if obj:
            serializer = UsersRSerializer(instance=obj)
            data = serializer.data
        else:
            data = {}
        data = general_message(bean=data)
        return Response(data, status=status.HTTP_200_OK)

    @atomic()
    def put(self, request, user_id, *args, **kwargs):
        data = request.data
        customer_id = data.get("customer_id")
        if customer_id:
            enterprise = customer_service.get_customer_enterprise(customer_id)
            if not enterprise:
                raise ValidationError("客户公司不存在")
            self.queryset = self.queryset.filter(
                id=user_id).prefetch_related("ent_user").filter(
                ent_user__deleted=False,
                ent_user__enterprise_id=enterprise.enterprise_id)
        else:
            self.queryset = self.queryset.filter(
                id=user_id).prefetch_related("ent_user").filter(
                ent_user__deleted=False,
                ent_user__enterprise_id=self.enterprise_id)
        obj = Users.objects.filter(deleted=False, account__is_active=True).filter(id=user_id).first()
        email = data.get("email")
        phone = data.get("phone")
        nickname = data.get("nickname")
        username = None
        account = data.get("account")
        if account:
            username = account.get("username")
        customer_id = data["customer_id"]
        user_service.user_info_validate(username, email, phone, user_id,
                                        obj.account_id)
        obj.nickname = nickname
        obj.phone = phone
        obj.email = email
        obj.save()
        password = data.get("password")
        if password is not None:
            obj.account.set_password(password)
        if username is not None:
            obj.account.username = username
        obj.account.save()
        if not customer_id:
            user_service.create_user_roles(user_id, data.get("role_ids"))
            user_service.create_user_tags(user_id, data.get("tag_ids"))
            user_service.create_user_organizations(
                user_id, data.get("organization_ids"))
        queryset = self.queryset.filter(id=user_id).first()
        serializer = UsersRSerializer(instance=queryset)
        data = general_message(msg_show="更新成功", bean=serializer.data)
        return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="删除账号",
                         tags=['user'],
                         manual_parameters=[
                             openapi.Parameter("user_id",
                                               openapi.IN_PATH,
                                               description="用户id",
                                               type=openapi.TYPE_INTEGER)
                         ],
                         responses={status.HTTP_200_OK: None})
    @atomic()
    def delete(self, request, user_id, *args, **kwargs):
        customer_id = request.data.get("customer_id")
        if customer_id:
            enterprise = customer_service.get_customer_enterprise(customer_id)
            if not enterprise:
                raise ValidationError("客户公司不存在")
            user_service.delete_user(user_id, [enterprise.enterprise_id])
        else:
            user_service.delete_user(user_id, self.enterprise_entids)
        data = general_message(msg_show="删除成功")
        return Response(data, status=status.HTTP_200_OK)


class UsersSearchView(BaseApiView):
    @swagger_auto_schema(operation_description="搜索用户",
                         tags=['user'],
                         manual_parameters=[
                             openapi.Parameter("organization_id",
                                               openapi.IN_QUERY,
                                               description="组织id",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("role_id",
                                               openapi.IN_QUERY,
                                               description="角色id",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("tag_id",
                                               openapi.IN_QUERY,
                                               description="职位id",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("team_headman",
                                               openapi.IN_QUERY,
                                               description="组长",
                                               type=openapi.TYPE_BOOLEAN,
                                               required=False),
                             openapi.Parameter("service_staff",
                                               openapi.IN_QUERY,
                                               description="客户代表",
                                               type=openapi.TYPE_BOOLEAN,
                                               required=False),
                             openapi.Parameter("value",
                                               openapi.IN_QUERY,
                                               description="名字、邮箱、手机号、职位",
                                               type=openapi.TYPE_STRING,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UsersLCSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        organization_id = request.GET.get("organization_id")
        role_id = request.GET.get("role_id")
        tag_id = request.GET.get("tag_id")
        value = request.GET.get("value")
        team_headman = request.GET.get("team_headman", False)
        choices = request.GET.get("choices", False)
        if team_headman in ("true", "True", "1"):
            team_headman = True
        service_staff = request.GET.get("service_staff", False)
        if service_staff in ("true", "True", "1"):
            service_staff = True
        if choices in ("true", "True", "1"):
            choices = True
        users = user_service.search_users(self.enterprise_ids, organization_id,
                                          role_id, tag_id, team_headman,
                                          service_staff, value, choices)
        data = general_message(list=users)
        return Response(data, status=status.HTTP_200_OK)


class RolesLCView(ManagerApiView):
    serializer_class = RoleLCSerializer
    queryset = user_queryset.roles_lc
    filter_class = RolesFilter

    @swagger_auto_schema(operation_description="获取企业角色列表",
                         tags=['role'],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(RoleLCSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        self.queryset = self.queryset.filter(kind="enterprise",
                                             kind_id=self.enterprise_id)
        return self.get_list(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_description="添加企业角色",
        request_body=RoleLCSerializer,
        tags=['role'],
        responses={status.HTTP_200_OK: serializer_assembly(RoleLCSerializer)})
    def post(self, request, *args, **kwargs):
        perms_codes = request.data.get("perms_codes")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        perms_tree = user_service.create_role_perms(serializer.data.get("id"),
                                                    perms_codes)
        rst = dict(serializer.data)
        rst.update({"perms": perms_tree})
        data = general_message(msg="success", msg_show="创建成功", bean=rst)
        return Response(data, status=status.HTTP_201_CREATED)


# 获取、绑定登录用户所属公司的任意用户的角色列表
class UsersRolesMultiLCView(ManagerUserApiView):
    serializer_class = UserRolesLCSerializer
    queryset = user_queryset.user_roles_lc

    @swagger_auto_schema(operation_description="获取用户角色列表",
                         tags=['role'],
                         manual_parameters=[
                             openapi.Parameter("user_id",
                                               openapi.IN_PATH,
                                               description="用户id",
                                               type=openapi.TYPE_STRING),
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UserRolesLCSerializer,
                                                     many=True)
                         })
    def get(self, request, user_id, *args, **kwargs):
        self.queryset = user_queryset.user_roles_lc.filter(
            user_id=self.tar_user_id)
        return self.get_list(request, user_id, *args, **kwargs)

    @swagger_auto_schema(operation_description="批量添加用户角色",
                         request_body=UserRolesMultiCSerializer,
                         tags=['role'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UserRolesLCSerializer,
                                                     many=True)
                         })
    def post(self, request, user_id, *args, **kwargs):
        serializer = UserRolesMultiCSerializer(data=request.data)
        serializer.is_valid()
        instance = user_service.create_user_roles(
            self.tar_user_id, serializer.data.get("role_ids", []))
        serializer = UserRolesLCSerializer(instance=instance, many=True)
        data = general_message(msg_show="获取列表成功", list=serializer.data)
        return Response(data, status=status.HTTP_200_OK)


class RolesRUDView(ManagerApiView):
    serializer_class = RoleLCSerializer
    queryset = user_queryset.roles_lc
    filter_class = RolesFilter

    @swagger_auto_schema(operation_description="获取企业角色信息",
                         tags=['role'],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(RoleLCSerializer, many=True)
                         })
    def get(self, request, role_id, *args, **kwargs):
        self.queryset = self.queryset.filter(kind="enterprise",
                                             kind_id=self.enterprise_id)
        obj = self.queryset.filter(id=role_id).first()
        if not obj:
            raise ValidationError("该角色不存在")
        serializer = RoleLCSerializer(obj)
        perms = user_service.get_role_perms(obj.id)
        data = serializer.data
        data.update(({"perms_codes": perms}))
        return Response(
            general_message(msg="success", msg_show="数据请求成功", bean=data))

    @swagger_auto_schema(
        operation_description="更新角色信息",
        request_body=RoleLCSerializer,
        tags=['role'],
        responses={status.HTTP_200_OK: serializer_assembly(RoleLCSerializer)})
    def put(self, request, role_id, *args, **kwargs):
        self.queryset = self.queryset.filter(kind="enterprise",
                                             kind_id=self.enterprise_id)
        obj = self.queryset.filter(id=role_id).first()
        perms_codes = request.data.get("perms_codes", [])
        if not obj:
            raise ValidationError("该角色不存在")
        serializer = RoleLCSerializer(data=request.data,
                                      context={
                                          "view": self,
                                          "role_id": role_id
                                      })
        serializer.is_valid(raise_exception=True)
        obj.name = serializer.data["name"]
        obj.comments = serializer.data["comments"]
        obj.save()
        serializer = RoleLCSerializer(obj)
        user_service.create_role_perms(serializer.data.get("id"), perms_codes)
        perms = user_service.get_role_perms(obj.id)
        rst = dict(serializer.data)
        rst.update({"perms_codes": perms})
        return Response(
            general_message(msg="success", msg_show="数据更新成功", bean=rst))

    @swagger_auto_schema(operation_description="更新角色信息",
                         request_body=RoleLCSerializer,
                         tags=['role'],
                         responses={status.HTTP_200_OK: None})
    def delete(self, request, role_id, *args, **kwargs):
        self.queryset = self.queryset.filter(kind="enterprise",
                                             kind_id=self.enterprise_id)
        obj = self.queryset.filter(id=role_id).first()
        if not obj:
            raise ValidationError("该角色不存在")
        obj.delete()
        user_service.delete_role_perms(role_id)
        return Response(general_message(msg="success", msg_show="数据删除成功"))


class TagsLCView(BaseApiView):
    serializer_class = TagsLCSerializer
    queryset = user_queryset.tags_lc
    filter_class = TagsFilter

    @swagger_auto_schema(operation_description="获取标签列表信息",
                         tags=['tags'],
                         manual_parameters=[
                             openapi.Parameter("tag_id",
                                               openapi.IN_PATH,
                                               description="标签id",
                                               type=openapi.TYPE_INTEGER,
                                               required=True),
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("name",
                                               openapi.IN_QUERY,
                                               description="名称",
                                               type=openapi.TYPE_STRING,
                                               required=False),
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(TagsLCSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        return self.get_list(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_description="创建标签",
        tags=['tags'],
        manual_parameters=[
            openapi.Parameter("tag_id",
                              openapi.IN_PATH,
                              description="标签id",
                              type=openapi.TYPE_INTEGER,
                              required=True),
        ],
        request_body=TagsLCSerializer,
        responses={status.HTTP_200_OK: serializer_assembly(TagsLCSerializer)})
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class TagsRUDView(BaseApiView):
    serializer_class = TagsRSerializer
    queryset = user_queryset.tags_lc

    @swagger_auto_schema(
        operation_description="获取标签信息",
        tags=['tags'],
        manual_parameters=[
            openapi.Parameter("tag_id",
                              openapi.IN_PATH,
                              description="标签id",
                              type=openapi.TYPE_INTEGER,
                              required=True),
        ],
        responses={status.HTTP_200_OK: serializer_assembly(TagsLCSerializer)})
    def get(self, request, tag_id, *args, **kwargs):
        self.serializer_class = TagsLCSerializer
        kwargs.update({"id": tag_id})
        return self.get_info(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_description="创建标签",
        tags=['tags'],
        manual_parameters=[
            openapi.Parameter("tag_id",
                              openapi.IN_PATH,
                              description="标签id",
                              type=openapi.TYPE_INTEGER,
                              required=True),
        ],
        request_body=TagsRSerializer,
        responses={status.HTTP_200_OK: serializer_assembly(TagsRSerializer)})
    def put(self, request, tag_id, *args, **kwargs):
        obj = self.queryset.filter(id=tag_id).first()
        if not obj:
            raise ValidationError("该标签不存在")
        serializer = TagsRSerializer(data=request.data,
                                     context={"tag_id": tag_id})
        serializer.is_valid(raise_exception=True)
        obj.name = serializer.data.get("name")
        obj.save()
        serializer = TagsRSerializer(instance=obj)
        return Response(general_message(msg_show="更新成功", bean=serializer.data))

    @swagger_auto_schema(operation_description="删除标签信息",
                         manual_parameters=[
                             openapi.Parameter("tag_id",
                                               openapi.IN_PATH,
                                               description="标签id",
                                               type=openapi.TYPE_INTEGER,
                                               required=True),
                         ],
                         tags=['role'],
                         responses={status.HTTP_200_OK: None})
    def delete(self, request, tag_id, *args, **kwargs):
        obj = self.queryset.filter(id=tag_id).first()
        if not obj:
            raise ValidationError("该标签不存在")
        obj.delete()
        return Response(general_message(msg_show="数据删除成功"))


class UserTagsLCView(BaseApiView):
    serializer_class = UserTagsLCSerializer
    queryset = user_queryset.user_tags_lc

    @swagger_auto_schema(operation_description="获取用户标签信息",
                         tags=['tags'],
                         manual_parameters=[
                             openapi.Parameter("user_id",
                                               openapi.IN_PATH,
                                               description="用户id",
                                               type=openapi.TYPE_INTEGER,
                                               required=True),
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UserTagsLCSerializer,
                                                     many=True)
                         })
    def get(self, request, user_id, *args, **kwargs):
        self.queryset.filter(user_id=user_id)
        return self.get_list(request, *args, **kwargs)

    @swagger_auto_schema(operation_description="批量添加用户标签",
                         request_body=UserTagsMultiCSerializer,
                         tags=['tags'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(UserTagsLCSerializer,
                                                     many=True)
                         })
    def post(self, request, user_id, *args, **kwargs):
        serializer = UserTagsMultiCSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = user_service.create_user_tags(
            user_id, serializer.data.get("tag_ids", []))
        serializer = UserTagsLCSerializer(instance=instance, many=True)
        data = general_message(msg_show="编辑成功", list=serializer.data)
        return Response(data, status=status.HTTP_200_OK)


class TagUsersLView(BaseApiView):
    @swagger_auto_schema(operation_description="获取标签用户列表",
                         tags=['tags'],
                         manual_parameters=[
                             openapi.Parameter("tag_id",
                                               openapi.IN_PATH,
                                               description="标签id",
                                               type=openapi.TYPE_INTEGER,
                                               required=True),
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(TagUsersLSerializer)
                         })
    def get(self, request, tag_id, *args, **kwargs):
        users = user_service.get_tag_users(tag_id, self.enterprise_id)
        return Response(users, status=200)


@method_decorator(gzip_page, name='dispatch')
class PermsLView(BaseApiView):
    @swagger_auto_schema(operation_description="获取权限列表",
                         tags=['perms'],
                         manual_parameters=[],
                         responses={status.HTTP_200_OK: {}})
    def get(self, request, *args, **kwargs):
        data = general_message(bean=CONFIG)
        return Response(data, status=200)


class RolePermsLCView(BaseApiView):
    @swagger_auto_schema(operation_description="获取权限列表",
                         tags=['perms'],
                         manual_parameters=[],
                         responses={status.HTTP_200_OK: {}})
    def get(self, request, role_id, *args, **kwargs):
        rst = user_service.get_role_perms_tree(role_id)
        data = general_message(list=rst)
        return Response(data, status=200)

    @swagger_auto_schema(
        operation_description="获取权限列表",
        tags=['perms'],
        request_body=RolePermsSerializer,
        manual_parameters=[],
    )
    def post(self, request, role_id, *args, **kwargs):
        serializer = RolePermsSerializer(data=request.data)
        serializer.is_valid()
        rst = user_service.create_role_perms(
            role_id, serializer.data.get("perms_codes"))
        data = general_message(list=rst)
        return Response(data, status=200)


class OrganizationLCView(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 = user_service.get_user(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)

    def post(self, request, *args, **kwargs):
        serializer = UserCSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = user_service.create_user(self.enterprise, self.user, serializer.data)
        rst = user_service.get_user_info(self.enterprise_id, user.id)
        data = general_message(bean=rst, msg_show="创建成功")
        return Response(data, status=status.HTTP_200_OK)

