from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from console.organizations.models import Organization
from common.utils.return_structure import general_message, error_message
from rest_framework.response import Response
from common.utils.service_code import VERIFICATION_ERROR
from console.organizations.serializers import OrganizationInfoSerializer
from console.organizations.serializers import OrganizationListSerializer
from console.organizations.serializers import OrganizationAccsSerializer
from common.utils.serializers import serializer_assembly
from django.db import transaction
from common.utils.service_code import SERVICE_ERROR
from common.utils.service_code import PARAMETER_ERROR
from common.utils.views import BaseApiView
from console.electricityuser.models import ElectricityUser
from common.accounts.models import Accounts, UserEnterprise
from console.customer.models import Customer
from common.accounts.models import Users
from console.customer.models import CustomerAdmin

from console.organizations.serializers import OrganizationCreateSerializer

from common.utils.views import ManagerApiView


class OrganizationsInfo(ManagerApiView):
    '''
    组织管理
    '''
    @swagger_auto_schema(operation_description="组织管理-获取组织列表",
                         tags=["organizations"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationListSerializer,
                                                 many=False)
                         })
    def get(self, request, *args, **kwargs):
        organizations = Organization.objects.filter(
            deleted=False,
            enterprise_id__in=self.enterprise_ids,
            parent_id=None)
        serializer = OrganizationListSerializer(organizations, many=True)
        return Response(data=general_message(msg_show="数据请求成功",
                                             list=serializer.data),
                        status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="组织管理-修改组织信息",
                         request_body=OrganizationInfoSerializer,
                         tags=['organizations'],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationInfoSerializer)
                         })
    def put(self, request, *args, **kwargs):
        data = request.data
        serializer = OrganizationInfoSerializer(data=data)
        if serializer.is_valid():
            print('ok')
        org = Organization.objects.filter(id=kwargs.get("id"), deleted=0)
        if not org:
            raise ValueError("无对应的组织信息", code=PARAMETER_ERROR)
        org = org.first()
        org.name = str(data['name'])
        if not data['parent_id']:
            org.parent_id = None
        elif str(data['parent_id']) == '':
            org.parent_id = None
        else:
            try:
                org.parent_id = int(data['parent_id'])
            except Exception as e:
                print(e)
                org.parent_id = None
        try:
            org.save()
            return Response(data=general_message(msg_show="修改成功"))
        except Exception:
            pass
        return Response(
            data=error_message(code=VERIFICATION_ERROR, msg_show="无改动"))

    @swagger_auto_schema(operation_description="添加组织",
                         request_body=OrganizationInfoSerializer,
                         tags=['organizations'],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationInfoSerializer)
                         })
    def post(self, request, *args, **kwargs):
        serializer = OrganizationCreateSerializer(data=request.data,
                                                  context={'enterprise_id':self.enterprise.id})
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(data=general_message(msg_show="创建成功"))
        return Response(
            error_message(msg_show=serializer.errors, code=PARAMETER_ERROR))

    @swagger_auto_schema(operation_description="删除组织",
                         request_body=OrganizationInfoSerializer,
                         tags=["organizations"],
                         responses={status.HTTP_200_OK: {}})
    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        org_id = kwargs.get("id")
        try:
            org = Organization.objects.filter(id=org_id, deleted=0).first()
            if not org:
                raise ValueError("无对应的组织信息", code=PARAMETER_ERROR)
            org.deleted = 1
            org.save()
            return Response(data=general_message(msg_show="删除成功"))
        except Exception as e:
            print(e)
            return Response(
                data=error_message(code=SERVICE_ERROR, msg_show="删除失败"))


class OrganizationsAccsInfo(BaseApiView):
    '''
    组织管理-客户服务平台
    '''
    @swagger_auto_schema(operation_description="组织管理-获取账号列表",
                         tags=["organizations"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationAccsSerializer,
                                                 many=False)
                         })
    def get(self, request, *args, **kwargs):
        user = self.user
        if not user:
            raise ValueError("无用户信息", code=PARAMETER_ERROR)
        ue = UserEnterprise.objects.filter(user_id=self.user.id, deleted=0)
        if not ue:
            raise ValueError("无用户对应的企业信息", code=PARAMETER_ERROR)
        users = UserEnterprise.objects.filter(
            enterprise_id=ue.first().enterprise_id)
        res = []
        for u in users:
            one = {}
            acc = Accounts.objects.filter(id=u.user.id)
            if not acc:
                continue
            one['account_id'] = acc.first().id
            one['user_id'] = u.user.id
            one['nickname'] = u.user.nickname
            one['username'] = acc.first().username
            one['phone'] = u.user.phone
            ca = CustomerAdmin.objects.filter(user_id=one['account_id'])
            if not ca:
                one['customers'] = ''
                one['customer_id'] = ''
            else:
                try:
                    cid = ca.first().customer.id
                    one['customer_id'] = cid
                    eu = ElectricityUser.objects.filter(customer_id=cid)
                    one['customers'] = ','.join([str(x.number) for x in eu])
                except Exception:
                    one['customer_id'] = None
                    one['customers'] = None
            res.append(one)
        return Response(data=general_message(msg_show="数据请求成功", list=res),
                        status=status.HTTP_200_OK)

    @swagger_auto_schema(operation_description="删除组织",
                         request_body=OrganizationInfoSerializer,
                         tags=["organizations"],
                         responses={status.HTTP_200_OK: {}})
    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        user_id, account_id = request.data['user_id'], request.data[
            'account_id']
        try:
            user = Users.objects.filter(id=user_id, deleted=0)
            if not user:
                raise ValueError("无对应的组织信息", code=PARAMETER_ERROR)
            user = user.first()
            user.deleted = 1
            user.save()
            acc = Accounts.objects.filter(id=account_id)
            if not acc:
                raise ValueError("无对应的组织信息", code=PARAMETER_ERROR)
            acc = acc.first()
            acc.delete()
            acc.save()
            return Response(data=general_message(msg_show="删除成功"))
        except Exception as e:
            print(e)
            return Response(
                data=error_message(code=SERVICE_ERROR, msg_show="删除失败"))

    @swagger_auto_schema(operation_description="组织管理-修改组织信息",
                         request_body=OrganizationInfoSerializer,
                         tags=['organizations'],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationInfoSerializer)
                         })
    def put(self, request, *args, **kwargs):
        data = request.data
        try:
            customer_id = data['customer_id']
        except Exception as e:
            print(e)
        try:
            username = data['username']
        except Exception as e:
            print(e)
        try:
            phone = data['phone']
        except Exception as e:
            print(e)
        try:
            nickname = data['nickname']
        except Exception as e:
            print(e)
        try:
            user_id = data['user_id']
        except Exception as e:
            print(e)
        try:
            account_id = data['account_id']
        except Exception as e:
            print(e)
        try:
            customer = str(data['customer'])
        except Exception as e:
            print(e)
        user = Users.objects.filter(id=user_id)
        if user:
            user = user.first()
            user.phone = str(phone)
            user.nickname = str(nickname)
            user.save()
            try:
                accounts = Accounts.objects.filter(id=str(account_id))
                if accounts:
                    accounts = accounts.first()
                    try:
                        password = data['password']
                        if password and str(password) != '':
                            accounts.set_password(password)
                    except Exception:
                        pass
                    accounts.username = username
                    accounts.save()
                    for x in str(customer).split(','):
                        ca = ElectricityUser.objects.filter(
                            customer_id=customer_id, number=x, deleted=0)
                        if not ca:
                            cus = Customer.objects.filter(
                                id=customer_id).first()
                            c = ElectricityUser()
                            c.customer = cus
                            c.number = x
                            c.deleted = 0
                            c.save()
                    cas = ElectricityUser.objects.filter(
                        customer_id=customer_id, deleted=0)
                    for c in cas:
                        if customer.find(str(c.customer.id)) == -1:
                            c.deleted = 1
                            c.save()
            except Exception as e:
                print(e)
            return Response(data=general_message(msg_show="修改成功"))
        return Response(
            data=error_message(code=VERIFICATION_ERROR, msg_show="修改失败"))

    def post(self, request, *args, **kwargs):
        data = request.data
        try:
            phone = data['phone']
            nickname = data['nickname']
            user = Users()
            user.phone = str(phone)
            user.deleted = 0
            user.nickname = str(nickname)
            user.save()
        except Exception as e:
            print(e)
        try:
            username = data['username']
            password = data['password']
            customer_info = str(data['customer'])

            account = Accounts()
            account.username = username
            account.set_password(password)
            account.save()
            customer = Customer()
            customer.name = username
            customer.type = 1
            customer.deleted = 0
            customer.save()
            for x in str(customer_info).split(','):
                ca = ElectricityUser()
                ca.customer = customer
                ca.number = x
                ca.deleted = 0
                ca.save()
            return Response(data=general_message(msg_show="新增成功"))
        except Exception as e:
            print(e)
        return Response(
            data=error_message(code=VERIFICATION_ERROR, msg_show="新增失败"))


class OrganizationsEusInfo(BaseApiView):
    '''
    组织管理-获取可选户号列表
    '''
    @swagger_auto_schema(operation_description="组织管理-获取可选户号列表",
                         tags=["organizations"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationAccsSerializer,
                                                 many=False)
                         })
    def get(self, request, *args, **kwargs):
        user = self.user
        if not user:
            raise ValueError("无用户信息", code=PARAMETER_ERROR)
        ue = UserEnterprise.objects.filter(user_id=self.user.id, deleted=0)
        if not ue:
            raise ValueError("无用户对应的企业信息", code=PARAMETER_ERROR)
        cs = Customer.objects.filter(enterprise=ue.first().enterprise.id)
        css = [c.id for c in cs]
        eu = ElectricityUser.objects.filter(customer_id__in=css)
        one = []
        if eu:
            one = [{'customer_id': str(x.number)} for x in eu]
        return Response(data=general_message(msg_show="数据请求成功", list=one),
                        status=status.HTTP_200_OK)


class OrganizationsAccInfo(BaseApiView):
    '''
    组织管理-客户服务平台
    '''
    @swagger_auto_schema(operation_description="组织管理-获取账号列表",
                         tags=["organizations"],
                         responses={
                             status.HTTP_200_OK:
                             serializer_assembly(OrganizationAccsSerializer,
                                                 many=False)
                         })
    def get(self, request, *args, **kwargs):
        user_id, _ = kwargs.get("user_id"), kwargs.get("account_id")
        user = Users.objects.filter(id=user_id)
        one = {}
        if user:
            one['nickname'] = user.first().nickname
            one['phone'] = user.phone
        acc = Accounts.objects.filter(id=user_id)
        if acc:
            one['username'] = acc.first().username
        ca = CustomerAdmin.objects.filter(user_id=user_id)
        if not ca:
            one['customers'] = ''
            one['customer_id'] = ''
        else:
            cid = ca.first().customer.id
            one['customer_id'] = cid
            eu = ElectricityUser.objects.filter(customer_id=cid)
            one['customers'] = ','.join([str(x.number) for x in eu])
        return Response(data=general_message(msg_show="数据请求成功", bean=one),
                        status=status.HTTP_200_OK)
