# -*- encoding: utf-8 -*-
"""
@File    : UserDeviceShareController.py
@Time    : 2023/2/3 13:25
@Author  : guanhailong
@Email   : guanhailong@asj6.wecom.work
@Software: PyCharm
"""
import datetime
import time
import logging

from Model.models import Device_User, DeviceSuperPassword
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from django.views import View

from Service.CommonService import CommonService


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

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

    def validation(self, request_dict, request, operation):
        tko = TokenObject(
            request.META.get('HTTP_AUTHORIZATION'))
        lang = request_dict.get('lang', tko.lang)
        logger = logging.getLogger('info')
        logger.info("传参语言{}".format(lang))
        response = ResponseObject(lang)
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if operation == 'getAuthorizationCode':  # 用户提交请求
            return self.getAuthorizationCode(request_dict, response, userID)
        if operation == 'verifyTheVerificationCode':  # 检验验证码
            return self.verifyTheVerificationCode(request_dict, response, userID)
        else:
            return response.json(404)

    @staticmethod
    def getAuthorizationCode(request_dict, response, userID):
        """
        用户提交请求
        @param request_dict:请求参数
        @param response:响应对象
        @param userID:用户ID
        @return:
        """
        uid = request_dict.get('uid', None)
        # 需求描述
        describe = request_dict.get('describe', None)
        purchase_channel = request_dict.get('purchase_channel', None)
        orderID = request_dict.get('orderID', None)
        buyTime = request_dict.get('buyTime', None)
        lang = request_dict.get('lang', 'en')
        if not all([uid, describe]):
            return response.json(444, 'uid, describe')
        try:
            nowTime = int(time.time())
            device_user_qs = Device_User.objects.filter(userID=userID)
            if not device_user_qs.exists():
                return response.json(173)
            if buyTime:
                buyTime = datetime.datetime.strptime(buyTime, '%Y-%m-%d')
                buyTime = CommonService.str_to_timestamp(str_time=str(buyTime))
            DeviceSuperPassword.objects.create(uid=uid, orderID=orderID, describe=describe,
                                               purchase_channel=purchase_channel, addTime=nowTime, userID_id=userID,
                                               buyTime=buyTime, status=0, lang=lang)

            return response.json(0)
        except Exception as e:
            print('生成验证码异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def verifyTheVerificationCode(request_dict, response, userID):
        """
        检验验证码
        @param request_dict:请求参数
        @param response:响应对象
        @param userID:用户ID
        @return:
        """
        authcode = request_dict.get('authcode', None)
        if authcode:
            authcode = CommonService.decode_data(authcode)
            if not len(authcode) == 6:
                return response.json(121)
            super_password_id = 'super_password_' + userID
            redisObj = RedisObject()
            # redis里面的验证码
            redis_image_code = redisObj.get_data(key=super_password_id)
            # 验证用户输入的验证码和redis中的验证码
            if redis_image_code is False or authcode.lower() != redis_image_code.lower():
                return response.json(121)
            else:
                return response.json(0)
        else:
            return response.json(444)
