# @Author    : Rocky
# @File      : InitController.py
# @Time      : 2023/4/11 17:26
import logging

from django.contrib.auth.hashers import check_password
from django.db import transaction
from django.http import HttpResponse
from django.views import View

from Model.models import Device_User, Device_Info, Order_Model, UidPushModel, UserExModel, UserOauth2Model, \
    UidUserModel, GrantCodeModel, UserAppFrequencyModel, \
    AppLogModel, UserFamily, FamilyMember, FamilyMemberJoin, SmartScene, DeviceSuperPassword, SceneLog
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Service.CommonService import CommonService


class InitView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, operation)

    def validation(self, request_dict, operation):
        if operation == 'health-check':  # 负载均衡器健康检测接口
            return self.health_check(request_dict)
        elif operation == 'delete-account':  # 网页删除账号
            return self.delete_account(request_dict)

    @staticmethod
    def health_check(request_dict):
        try:
            redis_obj = RedisObject()
            response = ResponseObject()
            Device_Info.objects.filter().values('id').first()
            SceneLog.objects.filter().values('id').first()
            return response.json(0)
        except Exception as e:
            return HttpResponse(repr(e), status=500)

    @staticmethod
    def delete_account(request_dict):
        """
        网页删除账号
        @param request_dict:输入
        @request_dict username:用户名
        @request_dict password:用户密码
        @return 输出
        """
        LOGGER = logging.getLogger('info')
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        response = ResponseObject()
        device_user_qs = Device_User.objects.filter(username=username).values('password', 'userID')
        if not device_user_qs.exists():
            return response.json(104)

        cipher_password, user_id = device_user_qs[0]['password'], device_user_qs[0]['userID']
        if password_version == 'V1':
            check_flag = check_password(password, cipher_password)
        else:
            check_flag = CommonService.check_password(password, cipher_password)
        if not check_flag:
            return response.json(111)
        try:
            with transaction.atomic():
                #  解绑用户与设备
                uid_push_qs = UidPushModel.objects.filter(userID=user_id)
                if uid_push_qs.exists():
                    uid_push_qs.delete()
                #  删除用户扩展信息
                user_ex_qs = UserExModel.objects.filter(userID=user_id)
                if user_ex_qs.exists():
                    user_ex_qs.delete()
                #  用户oauth2信息
                user_oauth2_qs = UserOauth2Model.objects.filter(userID=user_id)
                if user_oauth2_qs.exists():
                    user_oauth2_qs.delete()
                # 删除用户设备ap
                uid_user_qs = UidUserModel.objects.filter(userID=user_id)
                if uid_user_qs.exists():
                    uid_user_qs.delete()
                # 删除用户授权码
                grant_code_qs = GrantCodeModel.objects.filter(userID=user_id)
                if grant_code_qs.exists():
                    grant_code_qs.delete()
                #  删除用户使用APP频率
                user_app_Frequency_qs = UserAppFrequencyModel.objects.filter(user_id=user_id)
                if user_app_Frequency_qs.exists():
                    user_app_Frequency_qs.delete()
                #  删除APP（设备）日志表
                app_log_qs = AppLogModel.objects.filter(user_id=user_id)
                if app_log_qs.exists():
                    app_log_qs.delete()
                # 删除家庭成员
                family_qs = FamilyMember.objects.filter(user_id=user_id)
                if family_qs.exists():
                    family_qs.delete()
                # 删除家庭成员加入
                family_join_qs = FamilyMemberJoin.objects.filter(user_id=user_id)
                if family_join_qs.exists():
                    family_join_qs.delete()
                # 删除用户家庭
                user_family_qs = UserFamily.objects.filter(user_id=user_id)
                if user_family_qs.exists():
                    user_family_qs.delete()
                # 删除智能场景
                smart_scene_qs = SmartScene.objects.filter(user_id=user_id)
                if smart_scene_qs.exists():
                    smart_scene_qs.delete()
                # 删除超级密码请求信息
                device_super_qs = DeviceSuperPassword.objects.filter(userID=user_id)
                if device_super_qs.exists():
                    device_super_qs.delete()
                #  删除设备信息
                device_info_qs = Device_Info.objects.filter(userID=user_id)
                if device_info_qs.exists():
                    device_info_qs.delete()
                # 删除用户订单信息
                order_uid_qs = Order_Model.objects.filter(userID=user_id)
                if order_uid_qs.exists():
                    order_uid_qs.delete()
                Device_User.objects.filter(userID=user_id).delete()
                LOGGER.info('{}已注销'.format(username))
                return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500)
