import base64
import datetime
import logging
import random
import threading
import time
import traceback
from io import BytesIO

import jwt
import requests
import simplejson
import simplejson as json
from PIL import Image, ImageDraw, ImageFont
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import HttpResponse
from django.utils.decorators import method_decorator
from django.utils.timezone import utc
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from django.views.generic import View
from jwt.algorithms import RSAAlgorithm
from ratelimit import limits

from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, TUTK_PUSH_DOMAIN, \
    LOGGER, CONFIG_US, APP_MAPPING, DETECT_PUSH_DOMAINS
from Ansjer.config import BASE_DIR, CONFIG_EUR, CONFIG_INFO, SERVER_DOMAIN_EUR, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
from Controller.CheckUserData import DataValid, date_handler, RandomStr
from Controller.UserDevice.UserSubscriptionController import UserSubscriptionControllerView
from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
    UserAppFrequencyModel, CountryIPModel, CountryModel, UidChannelSetModel, Order_Model, UID_Bucket, Unused_Uid_Meal, \
    GatewayPush, CountryLanguageModel, LanguageModel, IcloudUseDetails, IcloudStorageRecord, VodBucketModel, LogModel, \
    UserEmailSubscriptions
from Object.AWS.AmazonS3Util import AmazonS3Util
from Object.AWS.SesClassObject import SesClassObject
from Object.AliSmsObject import AliSmsObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UVerifyObject import UVerifyObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Service.TemplateService import TemplateService
from Object.AWS.S3Email import S3Email


# 获取验证码
class authCodeView(TemplateView):

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        # testtest11111111111111
        return super(authCodeView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        username = request.POST.get('userName', None)
        useremail = request.POST.get('userEmail', None)
        return self.ValidationError(username, useremail, response)

    # @limits(calls=2, period=60)
    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        username = request.GET.get('userName', None)
        email = request.GET.get('userEmail', None)
        return self.ValidationError(username, email, response)

    def ValidationError(self, username, email, response):
        if username:
            username = username.strip()
            return self.phoneCode(username, response)
        elif email:
            email = email.strip()
            return self.emailCode(email, response)
        else:
            return response.json(800)

    def phoneCode(self, phone, response):
        dataValid = DataValid()
        if dataValid.mobile_validate(phone):
            reds = RedisObject()
            identifyingCode = reds.get_data(key=phone + '_identifyingCode')
            if identifyingCode is False:
                user_qs = Device_User.objects.filter(username=phone)
                if user_qs.exists():
                    return response.json(101)
                else:
                    identifyingCode = RandomStr(6, True)
                    if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=600):
                        return response.json(0, {'identifyingCode': identifyingCode})
                    else:
                        return response.json(10, '生成缓存系统错误')

            else:
                return response.json(0, {'identifyingCode': identifyingCode})
        else:
            return response.json(107)

    def emailCode(self, email, response):
        dataValid = DataValid()
        if dataValid.email_validate(email):
            reds = RedisObject()
            identifyingCode = reds.get_data(key=email + '_identifyingCode')
            if identifyingCode is False:
                user_qs = Device_User.objects.filter(username=email)
                email_qs = Device_User.objects.filter(userEmail=email)
                if user_qs.exists():
                    return response.json(103)
                elif email_qs.exists():
                    return response.json(103)
                else:
                    identifyingCode = RandomStr(6, True)
                    if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=AuthCode_Expire):
                        send_data = TemplateService.email_message(type='register_code', language=response.lang)
                        ses = SesClassObject()
                        send_res = ses.send_email(
                            send_address_list=[email],
                            subject=send_data['title'],
                            body=send_data['body'].replace("{username}", email).replace("{captcha}",
                                                                                        str(identifyingCode))
                        )
                        if send_res:
                            return response.json(0, {'identifyingCode': identifyingCode})
                        else:
                            reds.del_data(key=email + '_identifyingCode')
                            return response.json(44)
                    else:
                        return response.json(10, '生成缓存系统错误')

            else:
                return response.json(89, {'identifyingCode': identifyingCode})
        else:
            return response.json(107)


# 验证码注册
class registerView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(registerView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        username = request_dict.get('userName', None)
        userEmail = request_dict.get('userEmail', None)
        password = request_dict.get('userPwd', None)
        authCode = request_dict.get('identifyingCode', None)
        language = request_dict.get('language', None)
        unique = request_dict.get('unique', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        salt = request_dict.get('salt', None)
        if unique:
            delete_local_account(unique)
        response = ResponseObject(language)
        if username and password and authCode:
            # 过滤空格
            username = username.strip()
            if userEmail:
                userEmail = userEmail.strip()
            return self.register(username, userEmail, password, authCode, response, password_version, salt)
        else:
            return response.json(800)

    def register(self, username, userEmail, password, authCode, response, password_version, salt):
        dataValid = DataValid()
        reds = RedisObject()
        identifyingCode = reds.get_data(key=username + '_identifyingCode')
        if identifyingCode is False:
            if userEmail:
                identifyingCode = reds.get_data(key=userEmail + '_identifyingCode')
                if identifyingCode is False:
                    return response.json(120)
                else:
                    username = userEmail
            else:
                return response.json(120)
        if authCode != identifyingCode:
            return response.json(121)
        if password_version == 'V1':
            password = make_password(password)
            re_flag = dataValid.password_validate(password)
        else:
            re_flag = True
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
        if re_flag:
            if dataValid.email_validate(username):
                if userEmail:
                    print(userEmail)
                    emailValid = Device_User.objects.filter(userEmail=userEmail)
                    if emailValid.exists():
                        return response.json(103)
                else:
                    userEmail = username
                if username:
                    nameValid = Device_User.objects.filter(username=username)
                    if nameValid.exists():
                        return response.json(101)
                try:
                    create_data = {
                        "username": username,
                        "NickName": username,
                        "userEmail": userEmail,
                        "password": password,
                        "userID": CommonService.getUserID(μs=False, setOTAID=True),
                        "is_active": True,
                        "user_isValid": True,
                    }
                    users = Device_User.objects.create(**create_data)
                except Exception as e:
                    errorInfo = traceback.format_exc()
                    print(errorInfo)
                    return response.json(424, repr(e))
                else:
                    if reds.del_data(key=username + '_identifyingCode'):
                        return response.json(0, {
                            "user": {
                                "userID": users.userID,
                                "username": users.username,
                                "userEmail": users.userEmail,
                                "NickName": users.NickName,
                                "userIconUrl": str(users.userIconUrl),
                                "is_superuser": users.is_superuser,
                                "is_active": users.is_active,
                                "data_joined": date_handler(users.data_joined),
                                "last_login": date_handler(users.last_login),
                            }
                        })
                    else:
                        return response.json(10, '删除缓存验证码错误')

            elif dataValid.mobile_validate(username):
                nameValid = Device_User.objects.filter(username=username)
                if nameValid:
                    return response.json(101)
                try:
                    create_data = {
                        "username": username,
                        "NickName": username,
                        "userEmail": userEmail,
                        "password": password,
                        "userID": CommonService.getUserID(μs=False, setOTAID=True),
                        "is_active": True,
                        "user_isValid": True,
                    }
                    users = Device_User.objects.create(**create_data)
                except Exception as e:
                    errorInfo = traceback.format_exc()
                    print(errorInfo)
                    return response.json(424, repr(e))
                else:
                    if reds.del_data(key=username + '_identifyingCode'):
                        return response.json(0, {
                            "user": {
                                "userID": users.userID,
                                "username": users.username,
                                "userEmail": users.userEmail,
                                "NickName": users.NickName,
                                "userIconUrl": str(users.userIconUrl),
                                "is_superuser": users.is_superuser,
                                "is_active": users.is_active,
                                "data_joined": date_handler(users.data_joined),
                                "last_login": date_handler(users.last_login),
                            }
                        })
                    else:
                        return response.json(10, '删除缓存验证码错误')

            else:
                return response.json(107)
        else:
            return response.json(109)


# 登出
class LogoutView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(LogoutView, self).dispatch(*args, **kwargs)

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

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

    def Logout(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token')
        tko = TokenObject(token)
        if tko.code != 0:
            return response.json(tko.code)

        m_code = request_dict.get('m_code', None)
        try:
            with transaction.atomic():
                Device_User.objects.filter(userID=tko.userID).update(online=False)
                Device_Info.objects.filter(userID=tko.userID).update(NotificationMode=0)
                userID = tko.userID
                if m_code:
                    UidPushModel.objects.filter(userID_id=userID, m_code=m_code).delete()
                    GatewayPush.objects.filter(user_id=userID, m_code=m_code).update(logout=True)
                # 记录操作日志
                username = CommonService.get_username(userID)
                now_time = int(time.time())
                content = json.loads(json.dumps(request_dict))
                log = {
                    'user_id': 1,
                    'status': 200,
                    'time': now_time,
                    'content': json.dumps(content),
                    'url': 'account/logout',
                    'operation': '{}退出登录,m_code:{}'.format(username, m_code),
                }
                LogModel.objects.create(**log)
            return response.json(0)
        except Exception as e:
            LOGGER.info('退出登录异常:error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


# 修改密码
class ChangePwdView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ChangePwdView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        token = request_dict.get('token', None)
        oldPwd = request_dict.get('oldPwd', None)
        newPwd = request_dict.get('newPwd', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        new_salt = request_dict.get('newSalt', None)
        old_salt = request_dict.get('oldSalt', None)
        iterations = request_dict.get('iterations', None)
        response = ResponseObject()
        if oldPwd is None and newPwd is None:
            return response.json(800)
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        return self.updatePwd(tko.userID, oldPwd, newPwd, response, password_version, new_salt, old_salt, iterations)

    def updatePwd(self, userID, oldPwd, newPwd, response, password_version, new_salt, old_salt, iterations):
        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        if password_version == 'V1':
            c_p = check_password(oldPwd, user_qs[0].password)
        else:
            if not all([iterations, old_salt]):
                return response.json(444)
            oldPwd = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), old_salt, oldPwd)
            c_p = CommonService.check_password(oldPwd, user_qs[0].password)
        # 密码是否正确
        if not c_p:
            return response.json(111)
        if password_version == 'V1':
            newPwd = make_password(newPwd)
        else:
            if not new_salt:
                return response.json(111)
            newPwd = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, new_salt, newPwd)
        update = user_qs.update(password=newPwd)
        if update:
            return response.json(0)
        else:
            return response.json(177)


# 修改密码v3
class v3ChangePwdView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v3ChangePwdView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        token = request_dict.get('token', None)
        oldPwd = request_dict.get('oldPwd', None)
        newPwd = request_dict.get('newPwd', None)
        new_salt = request_dict.get('newSalt', None)
        old_salt = request_dict.get('oldSalt', None)
        iterations = request_dict.get('iterations', None)
        lang = request_dict.get('lang', 'en')
        password_version = request_dict.get('pwdVersion', 'V1')
        response = ResponseObject(lang)
        # 解密
        try:
            if password_version == 'V1':
                for i in range(1, 4):
                    if i == 1:
                        oldPwd = base64.b64decode(oldPwd)
                        oldPwd = oldPwd.decode('utf-8')
                        oldPwd = oldPwd[1:-1]
                    if i == 2:
                        oldPwd = base64.b64decode(oldPwd)
                        oldPwd = oldPwd.decode('utf-8')
                        oldPwd = oldPwd[2:-2]
                    if i == 3:
                        oldPwd = base64.b64decode(oldPwd)
                        oldPwd = oldPwd.decode('utf-8')
                        oldPwd = oldPwd[3:-3]
                for i in range(1, 4):
                    if i == 1:
                        newPwd = base64.b64decode(newPwd)
                        newPwd = newPwd.decode('utf-8')
                        newPwd = newPwd[1:-1]
                    if i == 2:
                        newPwd = base64.b64decode(newPwd)
                        newPwd = newPwd.decode('utf-8')
                        newPwd = newPwd[2:-2]
                    if i == 3:
                        newPwd = base64.b64decode(newPwd)
                        newPwd = newPwd.decode('utf-8')
                        newPwd = newPwd[3:-3]
                if oldPwd is None or newPwd is None or len(newPwd) < 6:
                    return response.json(111)
                data_valid = DataValid()
                if not data_valid.password_validate(newPwd):
                    return response.json(109)
        except Exception as e:
            print(repr(e))
            return response.json(111)
        else:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            return self.updatePwd(tko.userID, oldPwd, newPwd, response, password_version, new_salt, old_salt,
                                  iterations)

    def updatePwd(self, userID, oldPwd, newPwd, response, password_version, new_salt, old_salt, iterations):
        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        if password_version == 'V1':
            c_p = check_password(oldPwd, user_qs[0].password)
        else:
            if not all([iterations, old_salt]):
                return response.json(444)
            oldPwd = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), old_salt, oldPwd)
            c_p = CommonService.check_password(oldPwd, user_qs[0].password)
        # 密码是否正确
        if not c_p:
            return response.json(111)
        if password_version == 'V1':
            newPwd = make_password(newPwd)
        else:
            if not new_salt:
                return response.json(111)
            newPwd = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, new_salt, newPwd)
        update = user_qs.update(password=newPwd)
        if update:
            return response.json(0)
        else:
            return response.json(177)


# 创建密码接口
class createPwd(TemplateView):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.validation(request.GET)

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

    def validation(self, request_dict):
        token = request_dict.get('token', None)
        password = request_dict.get('password', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        response = ResponseObject()

        if not all([token, password]):
            return response.json(444)

        try:
            # 解密token获取userID
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            userID = tko.userID

            # 解密
            if password_version == 'V1':
                for i in range(1, 4):
                    password = base64.b64decode(password)
                    password = password.decode('utf-8')
                    password = password[i:-i]
                password = make_password(password)
            else:
                if not salt:
                    return response.json(111)
                password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            update = Device_User.objects.filter(userID=userID).update(password=password)
            if update:
                return response.json(0)
            else:
                return response.json(177)
        except Exception as e:
            djangoLogger = logging.getLogger('django')
            djangoLogger.exception(e)
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


class ForgetPwdView(TemplateView):
    '''
    忘记密码
    '''

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ForgetPwdView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        response = ResponseObject()
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        userName = request.GET.get('userName', None)
        return self.ValidationError(userName, response)

    @limits(calls=2, period=60)
    def post(self, request):
        request.encoding = 'utf-8'
        userName = request.POST.get('userName', None)
        response = ResponseObject()
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(userName, response)

    def ValidationError(self, userName, response):
        if userName is not None:
            userName = userName.strip()
            return self.ForgetPwd(userName, response)
        else:
            return response.json(800)

    def ForgetPwd(self, userName, response):
        dataValid = DataValid()
        if dataValid.mobile_validate(userName):
            User = Device_User.objects.filter(username=userName)
        elif dataValid.email_validate(userName):
            User = Device_User.objects.filter(username=userName)
            if not User.exists():
                User = Device_User.objects.filter(userEmail=userName)
        else:
            return response.json(104)
        if User:
            email = User[0].userEmail
            userID = User[0].userID
            if email:
                redisObj = RedisObject()
                reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
                if reset_pwd is False:
                    tko = TokenObject()
                    rest = tko.generate(data={'userID': userID, 'user': userName})
                    token = rest['access_token']
                    reset_pwd = CommonService.RandomStr(6)
                    send_data = TemplateService.email_message(type='forget', language='en')
                    reset_link = '{server_host}account/email-re-pwd?token={token}'.format(
                        server_host=SERVER_DOMAIN, token=token)
                    send_body = send_data['body'].format(username=email, reset_pwd=reset_pwd, reset_link=reset_link)
                    ses = SesClassObject()
                    send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
                    if send_res is True:
                        if redisObj.set_data(key=userID + '_email_reset_pwd', val=reset_pwd, expire=3600):
                            return response.json(0)
                        else:
                            return response.json(10, '存储验证失败')
                else:
                    return response.json(89)
            else:
                return response.json(103)
        else:
            return response.json(104)


class EmailResetPwdView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(EmailResetPwdView, self).dispatch(*args, **kwargs)

    # 查询
    def get(self, request, *args, **kwargs):
        response = ResponseObject()
        request_dict = request.GET
        return self.validate(request_dict, response, *args, **kwargs)

    # 认证登录
    def post(self, request, *args, **kwargs):
        response = ResponseObject()
        try:
            print(request.body.decode("utf-8"))
            json_data = json.loads(request.body.decode("utf-8"))
        except Exception as e:
            return response.json(10, repr(e))
        else:
            request_dict = json_data
            return self.validate(request_dict, response, *args, **kwargs)

    def validate(self, request_dict, response, *args, **kwargs):
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            redisObj = RedisObject()
            userID = tko.userID
            reset_pwd = redisObj.get_data(key=userID + '_email_reset_pwd')
            if reset_pwd is not False:
                user_qs = Device_User.objects.filter(userID=userID)
                if user_qs.exists():
                    redisObj.del_data(key=userID + '_email_reset_pwd')
                    is_update = user_qs.update(password=make_password(reset_pwd))
                    if is_update:
                        return HttpResponseRedirect(
                            "http://www.zositechc.cn/web/html/paw_update_success.html?code=" + reset_pwd)
                    else:
                        return response.json(10)
                else:
                    return response.json(104)
            else:
                return HttpResponseRedirect('http://www.zositechc.cn/web/html/paw_update_unsuccessful.html?lang=en')
        else:
            return HttpResponseRedirect('http://www.zositechc.cn/web/html/paw_update_unsuccessful.html?lang=en')


class refreshTokenView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(refreshTokenView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        content_type = request.META.get('CONTENT_TYPE', None)
        if content_type == 'application/json':
            request_dict = json.loads(request.body.decode('utf-8'))
        else:
            request_dict = request.POST
        return self.validation(request_dict)

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

    def validation(self, request_dict):
        token = request_dict.get('token', None)
        lang = request_dict.get('lang', None)
        language = request_dict.get('language', None)
        if lang is None:
            lang = language
        response = ResponseObject(lang)
        if token is not None:
            tko = TokenObject(token)
            tko.lang = lang
            res = tko.refresh()
            userID = tko.userID
            if tko.code == 0:
                # 更新用户扩展信息语言
                try:
                    user_ex_qs = UserExModel.objects.filter(userID_id=userID)
                    if user_ex_qs.exists():
                        nowTime = int(time.time())
                        update_dict = {
                            'updTime': nowTime,
                            'region': lang
                        }
                        user_ex_qs.update(**update_dict)
                except Exception as e:
                    print(repr(e))
                return response.json(0, res)
            else:
                return response.json(tko.code)
        else:
            return response.json(444, 'token')


class refreshTokenViewV3(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(refreshTokenViewV3, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        content_type = request.META.get('CONTENT_TYPE', None)
        if content_type == 'application/json':
            request_dict = json.loads(request.body.decode('utf-8'))
        else:
            request_dict = request.POST
        return self.validation(request_dict)

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

    @staticmethod
    def delete_user_and_device(user_id):
        # 删除不同区域相同用户
        data = {'userID': user_id}
        url_list = CommonService.get_orders_domain_name_list()
        if SERVER_DOMAIN_EUR in url_list:
            url_list.remove(SERVER_DOMAIN_EUR)
        if CONFIG_INFO != CONFIG_EUR:
            for url in url_list:
                requests.post(url=url + 'v3/account/deleteUser', data=data, timeout=3)

    def validation(self, request_dict):
        access_token = request_dict.get('access_token', None)
        refresh_token = request_dict.get('refresh_token', None)
        lang = request_dict.get('lang', None)
        language = request_dict.get('language', None)
        password = request_dict.get('userPwd', None)
        salt = request_dict.get('salt', None)
        iterations = request_dict.get('iterations', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        response = ResponseObject(lang)
        if not all([access_token, refresh_token]):
            return response.json(444, 'access_token, refresh_token')

        if lang is None:
            lang = language

        try:
            # 校验access_token
            access_token_obj = TokenObject(access_token)
            if access_token_obj.code != 0:
                return response.json(access_token_obj.code)
            # 校验refresh_token
            refresh_token_obj = TokenObject(refresh_token)
            res = refresh_token_obj.refresh()  # 更新refresh_token
            if refresh_token_obj.code != 0:
                return response.json(refresh_token_obj.code)
            userID = refresh_token_obj.userID
            refresh_token_obj.lang = lang

            # 国外正式服,判断是否需要重新登陆
            user_qs = Device_User.objects.filter(userID=userID).values('password', 'region_country')
            if CONFIG_INFO == CONFIG_US or CONFIG_INFO == CONFIG_EUR:
                country_id = user_qs[0]['region_country']
                LOGGER.info('刷新token, country_id:{}'.format(country_id))
                country_qs = CountryModel.objects.filter(id=country_id).values('region_id')
                if country_qs.exists():
                    region_id = country_qs[0]['region_id']
                    if (CONFIG_INFO == CONFIG_US and region_id == 4) or \
                            (CONFIG_INFO == CONFIG_EUR and region_id != 4):
                        LOGGER.info('用户地区与请求的服务器配置不一致')
                        return response.json(309)

            if password:  # 检验密码
                if not user_qs.exists():
                    return response.json(104)
                password = password.strip()
                # 解密
                if password_version == 'V1':
                    for i in range(1, 4):
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[i:-i]
                    if not check_password(password, list(user_qs)[0]['password']):
                        return response.json(111)
                else:
                    if not all([iterations, salt]):
                        return response.json(444)
                    password = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), salt, password)
                    if not CommonService.check_password(password, list(user_qs)[0]['password']):
                        return response.json(111)
                now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
                user_qs.update(last_login=now_time)
            # 更新用户扩展信息语言
            user_ex_qs = UserExModel.objects.filter(userID_id=userID)
            if user_ex_qs.exists():
                nowTime = int(time.time())
                update_dict = {
                    'updTime': nowTime,
                    'region': lang
                }
                user_ex_qs.update(**update_dict)
            # # 删除相同用户
            # request_thread = threading.Thread(target=self.delete_user_and_device, args=(userID,))
            # request_thread.start()
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


# 获取验证码
class v2authCodeView(TemplateView):

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v2authCodeView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        phone = request_dict.get('phone', None)
        if phone is not None:
            was_limited = getattr(request, 'limited', False)
            if was_limited is True:
                return response.json(5)
        return self.ValidationError(request_dict, response)

    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        request_dict = request.GET
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        email = request_dict.get('email', None)
        phone = request_dict.get('phone', None)
        country_code = request_dict.get('country_code', None)
        sign_name = request_dict.get('sign_name', None)
        if email is not None:
            email = email.strip()
            # 阿里云的发送邮箱的调用方法
            return self.aliyun_emailCode(email, response)

            # return self.emailCode(email, response)
        elif phone is not None:
            phone = phone.strip()
            # 短信签名
            sign_name = CommonService.confirm_msg_sign_name(sign_name, phone)

            if country_code is None:
                return self.phoneCode(phone, response, sign_name)
            else:
                country_code = str(country_code.strip())
                return self.phoneCodeV2(country_code, phone, response, sign_name)
        else:
            return response.json(444)

    def emailCode(self, email, response):

        dataValid = DataValid()
        # 邮箱匹配
        if dataValid.email_validate(email) is False:
            return response.json(107)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=email + '_identifyingCode')
        # 是否以获取邮箱验证码
        if identifyingCode:
            return response.json(89)
        user_qs = Device_User.objects.filter(username=email)
        email_qs = Device_User.objects.filter(userEmail=email)
        # 邮箱用户是否已存在
        if user_qs.exists():
            return response.json(103)
        elif email_qs.exists():
            return response.json(103)
        # 生成随机6位数
        identifyingCode = RandomStr(6, True)
        # 设置随机数缓存生命周期
        send_data = TemplateService.email_message(type='register_code', language=response.lang)
        ses = SesClassObject()
        # 发送邮件
        send_res = ses.send_email(
            send_address_list=[email],
            subject=send_data['title'],
            body=send_data['body'].replace("{username}", email).replace("{captcha}",
                                                                        str(identifyingCode))
        )
        if send_res is not True:
            return response.json(44)
        if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=300) is not True:
            return response.json(10, 'error')
        return response.json(0)
        # return response.json(0, {'identifyingCode': identifyingCode})

    # 阿里云获取邮箱验证码
    def aliyun_emailCode(self, email, response):
        try:
            print('阿里云开始')
            dataValid = DataValid()
            # 邮箱匹配
            if dataValid.email_validate(email) is False:
                return response.json(107)
            reds = RedisObject()
            code_key = f'ZOSI:BASIC:USER:EMAIL:{email}'
            code = reds.get_data(key=code_key)
            # 是否以获取邮箱验证码
            if code:
                return response.json(0)
            user_qs = Device_User.objects.filter(username=email)
            email_qs = Device_User.objects.filter(userEmail=email)
            # 邮箱用户是否已存在
            if user_qs.exists():
                return response.json(103)
            elif email_qs.exists():
                return response.json(103)
            # 生成随机6位数
            identifyingCode = RandomStr(6, True)
            # 设置随机数缓存生命周期
            send_data = TemplateService.email_message(type='register_code', language=response.lang)
            start_time = time.time()
            send_res = self.send_email(send_data, email, identifyingCode)  # 发送验证码到用户邮箱
            end_time = time.time()
            LOGGER.info(
                '{}阿里云邮箱发送验证码执行时间: {:.3f} 秒,email:{}'.format(CONFIG_INFO, (end_time - start_time),
                                                                            email))
            if send_res is not True:
                return response.json(44)
            # 单个邮箱验证码有效期5分钟
            if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=300) is not True:
                return response.json(10, 'error')
            # 单个邮箱一分钟发送一次验证码
            reds.set_data(key=code_key, val=identifyingCode, expire=60)
            return response.json(0)
        except Exception as e:
            LOGGER.info('aliyun_emailCode error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(0)

    @classmethod
    def send_email(cls, send_data, user_email, identifyingCode):
        ses = SesClassObject()
        body = send_data['body'].replace("{username}", user_email).replace("{captcha}", str(identifyingCode))
        title = send_data['title']
        if CONFIG_INFO == CONFIG_EUR or CONFIG_INFO == CONFIG_US:
            send_res = S3Email().send_email(send_data['title'], send_data['body'].replace("{username}", user_email)
                                            .replace("{captcha}", str(identifyingCode)), user_email)
            return send_res
        # 发送邮件
        send_res = ses.alyEmailCode(
            send_address_list=[user_email],
            subject=title,
            body=body
        )
        return send_res

    def phoneCode(self, phone, response, sign_name):
        dataValid = DataValid()
        if dataValid.mobile_validate(phone) is not True:
            return response.json(107)
        reds = RedisObject()
        reds_key = str(phone) + '_identifyingCode'
        identifyingCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and identifyingCode:
            # if identifyingCode :
            return response.json(90)
        user_qs = Device_User.objects.filter(username=phone)
        phone_qs = Device_User.objects.filter(phone=phone)
        if user_qs.exists() or phone_qs.exists():
            return response.json(101)
        identifyingCode = RandomStr(6, True)
        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name=sign_name,
                                   temp_msg='SMS_151600991')
        print(res)
        code = res["Code"]
        if code == "OK":
            if reds.set_data(key=reds_key, val=identifyingCode, expire=300) is not True:
                # if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=60) is not True:

                return response.json(10, '生成缓存系统错误')
            return response.json(0)
        else:
            msg = res["Message"]
            if code == "isv.MOBILE_NUMBER_ILLEGAL":
                if response.lang == "cn":
                    msg = phone + "非法手机"
            return response.json(10, msg)

    def phoneCodeV2(self, country_code, phone, response, sign_name):
        dataValid = DataValid()
        if dataValid.mobile_validate(phone) is not True:
            return response.json(107)
        reds = RedisObject()
        reds_key = str(phone) + '_identifyingCode'
        identifyingCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and identifyingCode:
            # if identifyingCode :
            return response.json(90)
        user_qs = Device_User.objects.filter(username=phone)
        phone_qs = Device_User.objects.filter(phone=phone)
        if user_qs.exists() or phone_qs.exists():
            return response.json(101)
        identifyingCode = RandomStr(6, True)
        if country_code == '86':
            # 国内短信推送模板
            temp_msg = 'SMS_151600991'
            rec_phone = phone
        else:
            # 国际短信推送模板
            temp_msg = 'SMS_172165867'
            rec_phone = country_code + phone
            sign_name = 'Ansjer'

        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=rec_phone, code=identifyingCode, sign_name=sign_name,
                                   temp_msg=temp_msg)
        print(res)
        if res["Code"] == "OK":
            # if reds.set_data(key=reds_key, val=identifyingCode, expire=60) is not True:
            if reds.set_data(key=reds_key, val=identifyingCode, expire=300) is not True:
                return response.json(10, '生成缓存系统错误')
            return response.json(0)
        else:
            return response.json(10, res["Message"])


# 验证码注册
class v2registerView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v2registerView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        authcode = request_dict.get('authcode', None)
        lang = request_dict.get('lang', None)
        unique = request_dict.get('unique', None)
        number = request_dict.get('number', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        if unique:
            delete_local_account(unique)
        response = ResponseObject(lang)
        if not lang:
            lang = request_dict.get('language', None)
        if password is None:
            return response.json(444, 'password')
        if authcode is None:
            return response.json(444, 'identifyingCode')
        if phone is not None:
            return self.do_phone_register(phone, password, authcode, number, response, password_version, salt)
        elif email is not None:
            return self.do_email_register(email, password, authcode, number, response, password_version, salt)
        else:
            return response.json(444, 'phone or email')

    def do_phone_register(self, phone, password, authcode, number, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=phone + '_identifyingCode')
        # 判断验证码是否过期
        if identifyingCode is False:
            return response.json(120)
        # 验证码是否正确
        if authcode != identifyingCode:
            return response.json(121)
        phone_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        # 是否已存在
        if phone_qs.exists():
            return response.json(101)

        try:
            create_data = {
                "username": phone,
                "NickName": phone,
                "phone": phone,
                "password": password,
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number

            Device_User.objects.create(**create_data)
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            if not reds.del_data(key=phone + '_identifyingCode'):
                return response.json(10, '删除缓存验证码错误')
            return self.do_login(phone_qs, response)

    def do_login(self, user_qs, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        user_qs.update(last_login=now_time, online=True)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        return response.json(0, res)

    def do_email_register(self, email, password, authcode, number, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if password_version == 'V1':
            re_flag = data_valid.email_validate(email)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=email + '_identifyingCode')
        # 判断验证码是否过期
        if identifyingCode is False:
            return response.json(120)
        # 验证码是否正确
        if authcode != identifyingCode:
            return response.json(121)
        email_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
        # 是否已存在
        if email_qs.exists():
            return response.json(103)
        try:
            create_data = {
                "username": email,
                "NickName": email,
                "userEmail": email,
                "password": password,
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number
            Device_User.objects.create(**create_data)
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            if not reds.del_data(key=email + '_identifyingCode'):
                return response.json(10, '删除缓存验证码错误')
            return self.do_login(email_qs, response)


class v3registerView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v3registerView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        """
        V3注册接口
        @param request_dict: 请求数据
        @request_dict phone: 手机
        @request_dict email: 邮箱
        @request_dict password: 密码
        @request_dict authcode: 验证码
        @request_dict lang: 语言
        @request_dict unique: 手机唯一标识
        @request_dict number: 国家id号
        @request_dict region_status: 地区选择状态
        @return: response
        """
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        authcode = request_dict.get('authcode', None)
        lang = request_dict.get('lang', None)
        unique = request_dict.get('unique', None)
        number = request_dict.get('number', None)
        salt = request_dict.get('salt', None)
        region_status = request_dict.get('region_status', None)
        email_scription = request_dict.get('email_scription', None)
        push_scription = request_dict.get('push_scription', None)

        if unique:
            delete_local_account(unique)
        region_status = int(region_status) if region_status else 0
        response = ResponseObject(lang)
        # 解密
        try:
            if password_version == 'V1':
                for i in range(1, 4):
                    if i == 1:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[1:-1]
                    if i == 2:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[2:-2]
                    if i == 3:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[3:-3]
                print(password)
        except Exception as e:
            print(repr(e))
            return response.json(111)
        try:
            for i in range(1, 4):
                if i == 1:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[1:-1]
                if i == 2:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[2:-2]
                if i == 3:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[3:-3]
        except Exception as e:
            print(repr(e))
            return response.json(121)
        else:
            if password is None:
                return response.json(444, 'password')
            if authcode is None:
                return response.json(444, 'identifyingCode')

            if phone is not None:
                return self.do_phone_register(phone, password, authcode, number, region_status, response,
                                              password_version, salt, push_scription)
            elif email is not None:
                return self.do_email_register(email, password, authcode, number, region_status, response,
                                              password_version, salt, email_scription, push_scription)
            else:
                return response.json(444, 'phone or email')

    def do_phone_register(self, phone, password, authcode, number, region_status, response, password_version, salt,
                          push_scription):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            re_flag = True
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=phone + '_identifyingCode')
        # 判断验证码是否过期
        if identifyingCode is False:
            return response.json(120)
        # 验证码是否正确
        if authcode != identifyingCode:
            return response.json(121)
        phone_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        # 是否已存在
        if phone_qs.exists():
            return response.json(101)
        try:
            userID = CommonService.getUserID(μs=False, setOTAID=True)
            create_data = {
                "username": phone,
                "NickName": phone,
                "phone": phone,
                "password": password,
                "userID": userID,
                "is_active": True,
                "user_isValid": True,
                "region_status": region_status
            }
            if number:
                create_data["region_country"] = number
            Device_User.objects.create(**create_data)
            if push_scription:
                UserEmailSubscriptions.objects.create(phone=phone, user_id=userID, push_sub_status=1,
                                                      created_time=int(time.time()), updated_time=int(time.time()))
            else:
                UserEmailSubscriptions.objects.create(phone=phone, user_id=userID, push_sub_status=0,
                                                      created_time=int(time.time()), updated_time=int(time.time()))

        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            if not reds.del_data(key=phone + '_identifyingCode'):
                return response.json(10, '删除缓存验证码错误')
            return self.do_login(phone_qs, response)

    def do_login(self, user_qs, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        user_qs.update(last_login=now_time, online=True)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        return response.json(0, res)

    def do_email_register(self, email, password, authcode, number, region_status, response, password_version, salt,
                          email_scription, push_scription):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            re_flag = True
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=email + '_identifyingCode')
        # 判断验证码是否过期
        if identifyingCode is False:
            return response.json(120)
        # 验证码是否正确
        if authcode != identifyingCode:
            return response.json(121)

        email_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
        # 是否已存在
        if email_qs.exists():
            return response.json(103)
        try:
            userID = CommonService.getUserID(μs=False, setOTAID=True)
            create_data = {
                "username": email,
                "NickName": email,
                "userEmail": email,
                "password": password,
                "userID": userID,
                "is_active": True,
                "user_isValid": True,
                "region_status": region_status
            }
            if number:
                create_data["region_country"] = number
            Device_User.objects.create(**create_data)
            if push_scription:
                UserEmailSubscriptions.objects.create(user_id=userID, email=email, push_sub_status=1)
            else:
                UserEmailSubscriptions.objects.create(user_id=userID, email=email, push_sub_status=0)
            if email_scription:
                subscribers = {
                    "userEmail": email,
                    "region_country": number
                }
                subscription_thread = threading.Thread(target=UserSubscriptionControllerView.subscription,
                                                       args=(subscribers,))
                subscription_thread.start()

        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            if not reds.del_data(key=email + '_identifyingCode'):
                return response.json(10, '删除缓存验证码错误')
            return self.do_login(email_qs, response)


# 重置密码
# 忘记密码获取验证码v2
class v2forgetPwdCodeView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v2forgetPwdCodeView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        lang = request_dict.get('lang')
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    @limits(calls=2, period=60)
    def post(self, request):
        request.encoding = 'utf-8'
        request_dict = request.POST
        lang = request_dict.get('lang')
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        country_code = request_dict.get('country_code', None)
        sign_name = request_dict.get('sign_name', None)
        number = request_dict.get('number', None)
        lang = request_dict.get('lang', None)
        if lang is None:
            return response.json(444, 'lang')
        if phone is not None:
            phone = phone.strip()
            # 短信签名
            sign_name = CommonService.confirm_msg_sign_name(sign_name, phone)
            if country_code is None:
                return self.do_send_phone_code(phone, response, sign_name, number, lang)
            else:
                return self.do_v2_send_phone_code(country_code, phone, response, sign_name, number, lang)
        elif email is not None:
            return self.do_send_email_code(email, response, number, lang)
        else:
            return response.json(444, 'phone')

    def do_send_phone_code(self, phone, response, sign_name, number, lang):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        if not user_qs.exists():
            return response.json(102)
        users = user_qs.values().first()
        reds = RedisObject()
        reds_key = str(phone) + '_forgetPwdResetCode'
        resetCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and resetCode:
            return response.json(90)
        resetCode = RandomStr(6, True)

        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        region_country = users['region_country']
        lang_id = LanguageModel.objects.filter(lang=lang).values('id')
        region_qs = CountryLanguageModel.objects.filter(country_id=region_country, language_id=lang_id[0]['id']).values(
            'country_name')

        aliSms = AliSmsObject()
        if not number or number == '0':
            user_qs.update(last_login=now_time, language=lang)
            msg_res = aliSms.send_code_sms(phone=phone, code=resetCode, sign_name=sign_name, temp_msg='SMS_151675019')
            if msg_res["Code"] == "OK":
                if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                    return response.json(10, '生成缓存错误')
            else:
                if '触发天级流控' in msg_res['Message']:
                    return response.json(91)
                else:
                    return response.json(10, msg_res['Message'])
        else:
            number = int(number)
            if number != region_country and region_country != 0:
                user_qs.update(last_login=now_time, language=lang)
            else:
                user_qs.update(last_login=now_time, language=lang, region_country=number)
                msg_res = aliSms.send_code_sms(phone=phone, code=resetCode, sign_name=sign_name,
                                               temp_msg='SMS_151675019')
                if msg_res["Code"] == "OK":
                    if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                        return response.json(10, '生成缓存错误')
                else:
                    if '触发天级流控' in msg_res['Message']:
                        return response.json(91)
                    else:
                        return response.json(10, msg_res['Message'])
        return response.json(0)

    def do_v2_send_phone_code(self, country_code, phone, response, sign_name, number, lang):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        if not user_qs.exists():
            return response.json(102)
        users = user_qs.values().first()
        reds = RedisObject()
        reds_key = str(phone) + '_forgetPwdResetCode'
        resetCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and resetCode:
            # if identifyingCode :
            return response.json(90)
        # if resetCode is True:
        #     return response.json(120)
        resetCode = RandomStr(6, True)
        aliSms = AliSmsObject()
        if country_code == '86':
            rec_phone = phone
            temp_msg = 'SMS_151675019'
        else:
            temp_msg = 'SMS_172200051'
            rec_phone = str(country_code) + str(phone)
            sign_name = 'Ansjer'
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        region_country = users['region_country']
        lang_id = LanguageModel.objects.filter(lang=lang).values('id')
        region_qs = CountryLanguageModel.objects.filter(country_id=region_country, language_id=lang_id[0]['id']).values(
            'country_name')
        if not number or number == '0':
            user_qs.update(last_login=now_time, language=lang)
            msg_res = aliSms.send_code_sms(phone=rec_phone, code=resetCode, sign_name=sign_name,
                                           temp_msg=temp_msg)
            if msg_res["Code"] == "OK":
                if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                    return response.json(10, '生成缓存错误')
            else:
                if '触发天级流控' in msg_res['Message']:
                    return response.json(91)
                else:
                    return response.json(10, msg_res['Message'])
        else:
            number = int(number)
            if number != region_country and region_country != 0:
                user_qs.update(last_login=now_time, language=lang)
            else:
                user_qs.update(last_login=now_time, language=lang, region_country=number)
                msg_res = aliSms.send_code_sms(phone=rec_phone, code=resetCode, sign_name=sign_name,
                                               temp_msg=temp_msg)
                if msg_res["Code"] == "OK":
                    if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                        return response.json(10, '生成缓存错误')
                else:
                    if '触发天级流控' in msg_res['Message']:
                        return response.json(91)
                    else:
                        return response.json(10, msg_res['Message'])

        return response.json(0)

    def do_send_email_code(self, email, response, number, lang):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        user_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
        if not user_qs.exists():
            return response.json(104)
        users = user_qs.values().first()
        res = {}
        reds = RedisObject()
        resetCode = reds.get_data(key=email + '_forgetPwdResetCode')
        if resetCode is True:
            return response.json(120)
        resetCode = RandomStr(6, True)
        if not reds.set_data(key=email + '_forgetPwdResetCode', val=resetCode, expire=600):
            return response.json(10, '生成缓存错误')
        send_data = TemplateService.email_message(type='forgetCode', language=response.lang)
        send_body = send_data['body'].format(userEmail=email, email_valid_code=resetCode)
        ses = SesClassObject()
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        region_country = users['region_country']
        # 语言不存在返回英文
        language_qs = LanguageModel.objects.filter(lang=lang).values('id')
        if not language_qs.exists():
            language_qs = LanguageModel.objects.filter(lang='en').values('id')
        region_qs = CountryLanguageModel.objects.filter(country_id=region_country, language_id=language_qs[0]['id']). \
            values('country_name')
        res['region'] = region_qs[0]['country_name'] if region_qs.exists() else ''

        if not number or number == '0':
            res['status'] = 0
            user_qs.update(last_login=now_time, language=lang)
            send_res = ses.alyEmailCode(send_address_list=[email], subject=send_data['title'], body=send_body)
            if send_res is not True:
                reds.del_data(key=email + '_forgetPwdResetCode')
                res['Message'] = '发送邮件失败'
                return response.json(44, res)
        else:
            number = int(number)
            if number != region_country and region_country != 0:
                res['status'] = 1
                user_qs.update(last_login=now_time, language=lang)
            else:
                res['status'] = 0
                user_qs.update(last_login=now_time, language=lang, region_country=number)
                send_res = ses.alyEmailCode(send_address_list=[email], subject=send_data['title'], body=send_body)
                if send_res is not True:
                    reds.del_data(key=email + '_forgetPwdResetCode')
                    res['Message'] = '发送邮件失败'
                    return response.json(44, res)

        return response.json(0, res)


# 忘记密码v2
class v2resetPwdByCodeView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v2resetPwdByCodeView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def post(self, request):
        request.encoding = 'utf-8'
        request_dict = request.POST
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        authcode = request_dict.get('authcode', None)
        print("1111111111111111111111")
        if password is None or authcode is None:
            return response.json(444, 'password,authcode')
        authcode = authcode.strip()
        password = password.strip()
        if phone is not None:
            phone = phone.strip()
            return self.do_phone_pwd_reset(phone, authcode, password, response, password_version, salt)
        elif email is not None:
            email = email.strip()
            return self.do_email_pwd_reset(email, authcode, password, response, password_version, salt)
        else:
            return response.json(444, 'phone')

    def do_email_pwd_reset(self, email, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        user_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
        if not user_qs.exists():
            return response.json(104)
        reds = RedisObject()
        resetCode = reds.get_data(key=email + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(90)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=email + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(password=password)
        if not reds.del_data(email + '_forgetPwdResetCode'):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    def do_phone_pwd_reset(self, phone, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        if not user_qs.exists():
            return response.json(102)
        reds = RedisObject()
        resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(90)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(password=password)
        if not reds.del_data(phone + '_forgetPwdResetCode'):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    def do_login(self, user_qs, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        user_qs.update(last_login=now_time, online=True)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        return response.json(0, res)


# 忘记密码v3
class v3resetPwdByCodeView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v3resetPwdByCodeView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def post(self, request):
        request.encoding = 'utf-8'
        request_dict = request.POST
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        authcode = request_dict.get('authcode', None)
        if password is None or authcode is None:
            return response.json(444, 'password,authcode')
        authcode = authcode.strip()
        password = password.strip()
        # 解密
        try:
            if password_version == 'V1':
                for i in range(1, 4):
                    if i == 1:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[1:-1]
                    if i == 2:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[2:-2]
                    if i == 3:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[3:-3]
        except Exception as e:
            print(repr(e))
            return response.json(111)
        try:
            for i in range(1, 4):
                if i == 1:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[1:-1]
                if i == 2:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[2:-2]
                if i == 3:
                    authcode = base64.b64decode(authcode)
                    authcode = authcode.decode('utf-8')
                    authcode = authcode[3:-3]
        except Exception as e:
            print(repr(e))
            return response.json(121)
        if phone is not None:
            phone = phone.strip()
            return self.do_phone_pwd_reset(phone, authcode, password, response, password_version, salt)
        elif email is not None:
            email = email.strip()
            return self.do_email_pwd_reset(email, authcode, password, response, password_version, salt)
        else:
            return response.json(444, 'phone')

    def do_email_pwd_reset(self, email, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        user_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
        if not user_qs.exists():
            return response.json(104)
        reds = RedisObject()
        resetCode = reds.get_data(key=email + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(92)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=email + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(password=password)
        if not reds.del_data(email + '_forgetPwdResetCode'):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    def do_phone_pwd_reset(self, phone, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
        if not user_qs.exists():
            return response.json(102)
        reds = RedisObject()
        resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(92)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(password=password)
        if not reds.del_data(phone + '_forgetPwdResetCode'):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    def do_login(self, user_qs, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        user_qs.update(last_login=now_time, online=True)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        return response.json(0, res)


# 登录
class v2LoginView(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(v2LoginView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        language = request_dict.get('language', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response)

    def get(self, request, *args, **kwargs):
        print("进来了")
        request.encoding = 'utf-8'
        request_dict = request.GET
        language = request_dict.get('language', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response)

    def validates(self, request_dict, response):
        username = request_dict.get('userName', None)
        password = request_dict.get('userPwd', None)
        salt = request_dict.get('salt', None)
        iterations = request_dict.get('iterations', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        number = request_dict.get('number', None)
        if not username or not password:
            return response.json(111)
        username = username.strip()
        password = password.strip()
        data_valid = DataValid()
        if data_valid.email_validate(username):
            return self.do_email_login(username, password, number, response, password_version, salt, iterations)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, password, number, response, password_version, salt, iterations)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, password, number, response, password_version, salt, iterations)
        else:
            return response.json(107)

    def do_email_login(self, email, password, number, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        return self.valid_login(user_qs, password, number, response, password_version, salt, iterations)

    def do_phone_login(self, phone, password, number, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, number, response, password_version, salt, iterations)

    def do_name_login(self, username, password, number, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                             is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, number, response, password_version, salt, iterations)

    def valid_login(self, user_qs, password, number, response, password_version, salt, iterations):
        if not user_qs.exists():
            return response.json(104)
        # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
        #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath')[0]
        if password_version == 'V1':
            check_flag = check_password(password, users['password'])
        else:
            if not all([iterations, salt]):
                return response.json(444)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), salt, password)
            check_flag = CommonService.check_password(password, users['password'])
        if not check_flag:
            return response.json(111)
        userID = users['userID']
        tko = TokenObject()
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'm_code': '123413243214'})
        if tko.code == 0:
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            if not number or number == '0':
                user_qs.update(last_login=now_time, language=response.lang)
            else:
                user_qs.update(last_login=now_time, language=response.lang, region_country=number)
            user_qs.update(last_login=now_time, language=response.lang)
            res['rid'] = users['role__rid']
            res['roleName'] = users['role__roleName']
            res['permList'] = ModelService.own_permission(userID)
            res['userID'] = userID
            # 昵称，邮箱，电话，刷新，头像
            userIconPath = str(users['userIconPath'])
            if userIconPath and userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
            else:
                res['userIconUrl'] = ''
            res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
            res['username'] = users['username'] if users['username'] is not None else ''
            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
            res['phone'] = users['phone'] if users['phone'] is not None else ''
            return response.json(0, res)
        else:
            return response.json(tko.code)


# 登录
class noPasslogin(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(noPasslogin, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        language = request_dict.get('language', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response)

    def get(self, request, *args, **kwargs):
        print("进来了")
        request.encoding = 'utf-8'
        request_dict = request.GET
        language = request_dict.get('lang', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response)

    def validates(self, request_dict, response):
        username = request_dict.get('userName', None)
        if not username:
            return response.json(111)
        username = username.strip()
        data_valid = DataValid()
        if data_valid.email_validate(username):
            return self.do_email_login(username, response)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, response)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, response)
        else:
            return response.json(107)

    def do_email_login(self, email, response):
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        return self.valid_login(user_qs, response)

    def do_phone_login(self, phone, response):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True, user_isValid=True)
        return self.valid_login(user_qs, response)

    def do_name_login(self, username, response):
        user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                             is_active=True, user_isValid=True)
        return self.valid_login(user_qs, response)

    def valid_login(self, user_qs, response):
        if not user_qs.exists():
            return response.json(104)
        # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
        #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath')[0]
        userID = users['userID']
        tko = TokenObject()
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'm_code': '123413243214'})
        if tko.code == 0:
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            user_qs.update(last_login=now_time, language=response.lang)
            res['rid'] = users['role__rid']
            res['roleName'] = users['role__roleName']
            res['permList'] = ModelService.own_permission(userID)
            res['userID'] = userID
            # 昵称，邮箱，电话，刷新，头像
            userIconPath = str(users['userIconPath'])
            if userIconPath and userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
            else:
                res['userIconUrl'] = ''
            res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
            res['username'] = users['username'] if users['username'] is not None else ''
            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
            res['phone'] = users['phone'] if users['phone'] is not None else ''
            return response.json(0, res)
        else:
            return response.json(tko.code)


# 密码加密新登录
class v3LoginView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v3LoginView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        language = request_dict.get('lang', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response, request)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        language = request_dict.get('lang', 'en')
        response = ResponseObject(language)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validates(request_dict, response, request)

    def validates(self, request_dict, response, request):
        username = request_dict.get('userName', None)
        password = request_dict.get('userPwd', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        subscribe = request_dict.get('subscribe', None)
        number = request_dict.get('number', None)
        if not username or not password:
            return response.json(111)
        username = username.strip()
        password = password.strip()
        print("准备解密")
        # 解密
        try:
            if password_version == 'V1':
                for i in range(1, 4):
                    if i == 1:
                        # 第一次先解密
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        # 截去第一位，最后一位
                        password = password[1:-1]
                    if i == 2:
                        # 第2次先解密
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        # 去前2位，后2位
                        password = password[2:-2]
                    if i == 3:
                        # 第3次先解密
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        # 去前3位，后3位
                        password = password[3:-3]
        except Exception as e:
            print(repr(e))
            return response.json(111)
        else:
            ip = CommonService.get_ip_address(request)
            data_valid = DataValid()
            if data_valid.email_validate(username):
                return self.do_email_login(username, password, response, subscribe, number, request_dict, ip)
            elif data_valid.mobile_validate(username):
                return self.do_phone_login(username, password, response, subscribe, number, request_dict, ip)
            elif data_valid.name_validate(username):
                return self.do_name_login(username, password, response, subscribe, number, request_dict, ip)
            else:
                return response.json(107)

    def do_email_login(self, email, password, response, subscribe, number, request_dict, ip):
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        return self.valid_login(user_qs, password, response, subscribe, number, request_dict, ip)

    def do_phone_login(self, phone, password, response, subscribe, number, request_dict, ip):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response, subscribe, number, request_dict, ip)

    def do_name_login(self, username, password, response, subscribe, number, request_dict, ip):
        user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                             is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response, subscribe, number, request_dict, ip)

    def valid_login(self, user_qs, password, response, subscribe, number, request_dict, ip):
        password_version = request_dict.get('pwdVersion', 'V1')
        salt = request_dict.get('salt', None)
        iterations = request_dict.get('iterations', None)
        if not user_qs.exists():
            return response.json(104)
        if subscribe:
            user_qs.update(subscribe_email=subscribe)

        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath', 'fingerprint_enable', 'fingerprint_key',
                               'subscribe_email', 'region_country')[0]
        if password_version == 'V1':
            check_flag = check_password(password, users['password'])
        else:
            if not all([iterations, salt]):
                return response.json(444)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), salt, password)
            check_flag = CommonService.check_password(password, users['password'])
        if not check_flag:
            return response.json(111)

        userID = users['userID']
        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
        auth_type = 0
        if oauth_qs.exists():
            auth_type = oauth_qs[0].authType

        # 网关推送新增内容
        app_bundle_id = request_dict.get('appBundleId', None)
        app_type = request_dict.get('appType', None)
        push_type = request_dict.get('pushType', None)
        token_val = request_dict.get('tokenVal', None)
        m_code = request_dict.get('mCode', None)
        lang = request_dict.get('lang', 'en')
        tz = request_dict.get('tz', None)
        token_version = request_dict.get('tokenVersion', 'V1')
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        tko = TokenObject()
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'm_code': '123413243214',
                  'appBundleId': new_bundle, 'tokenVal': token_val, 'tokenVersion': token_version})
        if tko.code != 0:
            return response.json(tko.code)
        if all([app_bundle_id, app_type, push_type, token_val, m_code, tz]):
            gateway_push_qs = GatewayPush.objects.filter(user_id=userID, m_code=m_code)
            if gateway_push_qs.exists():
                gateway_push_qs.update(token_val=token_val, push_type=push_type, logout=False)
            else:
                GatewayPush.objects.create(user_id=userID, app_bundle_id=app_bundle_id, app_type=app_type,
                                           push_type=push_type, token_val=token_val, m_code=m_code, lang=lang, tz=tz)
            UidPushModel.objects.filter(userID=userID, m_code=m_code).update(token_val=token_val, push_type=push_type)
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        region_country = users['region_country']
        # 语言不存在返回英文
        language_qs = LanguageModel.objects.filter(lang=lang).values('id')
        if not language_qs.exists():
            language_qs = LanguageModel.objects.filter(lang='en').values('id')

        # 更新最后登录时间
        if not number or number == '0':
            user_qs.update(last_login=now_time, language=response.lang)
        else:
            # 判断所选地区和用户注册地区是否一致
            number = int(number)
            if number != region_country and region_country != 0:  # 不一致
                res['status'] = 1
                user_qs.update(last_login=now_time, language=response.lang)
            else:  # 一致
                res['status'] = 0
                user_qs.update(last_login=now_time, language=response.lang, region_country=number)
        region_qs = CountryLanguageModel.objects.filter(country_id=region_country, language_id=language_qs[0]['id']). \
            values('country_name')

        res['rid'] = users['role__rid']
        res['roleName'] = users['role__roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(users['userIconPath'])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
        res['username'] = users['username'] if users['username'] is not None else ''
        res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
        res['phone'] = users['phone'] if users['phone'] is not None else ''
        res['authType'] = auth_type
        res['subscribe_email'] = users['subscribe_email'] if users['subscribe_email'] is not None else ''
        res['region'] = region_qs[0]['country_name'] if region_qs.exists() else ''

        # 记录操作日志
        username = CommonService.get_username(userID)
        content = json.loads(json.dumps(request_dict))
        log = {
            'ip': ip,
            'user_id': 1,
            'status': 200,
            'time': int(time.time()),
            'content': json.dumps(content),
            'url': 'v3/account/login',
            'operation': '{}用户登录成功'.format(username),
        }
        LogModel.objects.create(**log)

        return response.json(0, res)


# 一键登录接口
class oneClickLoginView(TemplateView):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.validation(request.GET)

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

    def validation(self, request_dict):
        token = request_dict.get('token', None)
        language = request_dict.get('language', 'en')
        app_bundle_id = request_dict.get('appBundleId', None)
        token_version = request_dict.get('tokenVersion', None)
        token_val = request_dict.get('tokenVal', None)
        response = ResponseObject(language)

        if not token:
            return response.json(444)

        try:
            # 友盟一键登录验证
            UVerify = UVerifyObject(token)
            verify = UVerify.verify_request()
            if not verify:
                return response.json(309)
            phone = UVerify.phone

            if not phone:
                return response.json(102)

            user_qs = Device_User.objects.filter(phone=phone).values('userID', 'username', 'NickName', 'phone',
                                                                     'password')
            # 用户已存在的响应
            if user_qs.exists():
                new_bundle = APP_MAPPING.get(app_bundle_id, None)
                tokenObj = TokenObject()
                res = tokenObj.generate(
                    data={
                        'userID': user_qs[0]['userID'],
                        'lang': response.lang,
                        'user': user_qs[0]['username'],
                        'appBundleId': new_bundle,
                        'tokenVersion': token_version,
                        'tokenVal': token_val,
                        'm_code': '123413243214'
                    }
                )
                if tokenObj.code != 0:
                    return response.json(tokenObj.code)

                res['userID'] = user_qs[0]['userID']
                res['username'] = user_qs[0]['username']
                res['NickName'] = user_qs[0]['NickName']
                res['phone'] = user_qs[0]['phone']
                res['userEmail'] = ''
                res['userIconUrl'] = ''
                res['subscribe_email'] = ''
                if user_qs[0]['password']:  # 设置密码,返回已设置标识
                    res['password'] = '1'
                else:
                    res['password'] = ''
                return response.json(0, res)

            # 新用户
            userID = CommonService.getUserID(μs=False, setOTAID=True)
            create_data = {
                "userID": userID,
                "username": phone,
                "NickName": phone,
                "phone": phone,
                "is_active": True,
                "user_isValid": True,
            }
            users = Device_User.objects.create(**create_data)

            new_bundle = APP_MAPPING.get(app_bundle_id, None)
            tokenObj = TokenObject()
            res = tokenObj.generate(
                data={
                    'userID': userID,
                    'lang': response.lang,
                    'user': users.username,
                    'appBundleId': new_bundle,
                    'm_code': '123413243214'
                }
            )
            if tokenObj.code != 0:
                return response.json(tokenObj.code)

            # 组织响应数据
            res['userID'] = userID
            res['username'] = users.username
            res['NickName'] = users.NickName
            res['phone'] = users.phone
            res['password'] = ''
            res['userEmail'] = ''
            res['userIconUrl'] = ''
            res['subscribe_email'] = ''
            return response.json(0, res)
        except Exception as e:
            djangoLogger = logging.getLogger('django')
            djangoLogger.exception(e)
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


# 用户登录后初始化接口
class InitInfoView(View):

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

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

    def validation(self, request_dict, request):
        response = ResponseObject()
        token = request_dict.get('token', None)
        unique = request_dict.get('unique', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            return self.init_info(request_dict, userID, response, request)
        elif unique:
            return self.update_country(request_dict, response, request)
        else:
            return response.json(tko.code)

    # 初始化设备token
    def init_info(self, request_dict, userID, response, request):
        # 未读的系统消息
        token_val = request_dict.get('token_val', None)
        jg_token_val = request_dict.get('jg_token_val', '')
        m_code = request_dict.get('m_code', None)
        push_type = request_dict.get('push_type', None)
        appBundleId = request_dict.get('appBundleId', None)
        tz = request_dict.get('tz', '0')
        lang = request_dict.get('lang', '')  # 语言区域
        now_time = int(time.time())
        if m_code[:4] == 'iOS_':
            m_code = m_code[4:]
        if all([token_val, push_type, appBundleId, userID]):
            push_type = int(push_type)
            self.save_push_config(userID, appBundleId, push_type, token_val, m_code, lang, tz, jg_token_val)
            self.save_or_creat_uid_push(userID, appBundleId, push_type, token_val, m_code, lang, tz, now_time,
                                        jg_token_val)
            if appBundleId:
                user_ex_qs = UserExModel.objects.filter(userID_id=userID)
                user_ex = None
                if user_ex_qs.exists():
                    update_dict = {
                        'updTime': now_time,
                        'appBundleId': appBundleId,
                        'region': lang
                    }
                    user_ex_qs.update(**update_dict)
                    user_ex = user_ex_qs[0]
                else:
                    create_dict = {
                        'addTime': now_time,
                        'updTime': now_time,
                        'appBundleId': appBundleId,
                        'userID_id': userID,
                        'region': lang
                    }
                    device_user = Device_User.objects.filter(userID=userID)
                    if not device_user.exists():
                        return response.json(173)
                    user_ex = UserExModel.objects.create(**create_dict)

                country_ip_qs = CountryIPModel.objects.filter(user_ex_id=user_ex.id)
                if not country_ip_qs.exists():
                    countryIp = CountryIPModel(
                        ip=CommonService.get_ip_address(request),
                        add_time=now_time,
                        user_ex_id=user_ex_qs[0].id
                    )
                    countryIp.save()
        # 刷新最后登录时间
        self.update_user_status(userID)
        # 获取设备是否存在有已被删除
        res = {'usmsg': 0}  # 预留字段， 有版本app该字段去掉会报错
        return response.json(0, res)

    @staticmethod
    def update_user_status(user_id):
        try:
            redisObj = RedisObject()
            key = f'BASIC:LOGIN:STATUS:{user_id}'
            login_data = redisObj.get_data(key)
            if login_data:
                return True
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            Device_User.objects.filter(userID=user_id).update(last_login=now_time)
            redisObj.set_data(key, '1', 86400)
            return True
        except Exception as e:
            LOGGER.info('更新用户最后登录时间异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return False

    @staticmethod
    def save_push_config(user_id, app_bundle_id, push_type, token_val, m_code, lang, tz, jg_token_val):
        """
        异步保存新推送配置
        @param user_id: 用户id
        @param app_bundle_id: app版本包id
        @param push_type: 推送类型 0：Ios，1：Google，2：国内极光
        @param token_val: 推送token
        @param jg_token_val: 极光推送token
        @param m_code: 手机唯一标识
        @param lang: 语言
        @param tz: 时区
        @return: None
        """
        try:
            app_type = 1 if push_type == 0 else 2
            gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, m_code=m_code)
            if gateway_push_qs.exists():
                gateway_push_qs.update(token_val=token_val, push_type=push_type, logout=False,
                                       jg_token_val=jg_token_val)
            else:
                GatewayPush.objects.create(user_id=user_id, app_bundle_id=app_bundle_id, app_type=app_type,
                                           push_type=push_type, token_val=token_val, m_code=m_code, lang=lang, tz=tz,
                                           jg_token_val=jg_token_val)
        except Exception as e:
            print('出错了~异步保存配置信息错误,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def save_or_creat_uid_push(user_id, app_bundle_id, push_type, token_val, m_code, lang, tz, now_time, jg_token_val):
        """
        异步保存推送配置
        @param user_id: 用户id
        @param app_bundle_id: app版本包id
        @param push_type: 推送类型 0：Ios，1：Google，2：国内极光
        @param token_val: 推送token
        @param jg_token_val: 极光推送token
        @param m_code: 手机唯一标识
        @param lang: 语言
        @param tz: 时区
        @param now_time: 时间戳
        @return: None
        """
        try:
            app_type = 1 if push_type == 0 else 2
            device_info = Device_Info.objects.filter(userID=user_id).values('UID')
            if device_info.exists():
                uid_set = UidSetModel.objects.filter(uid__in=device_info).values('id')
                for item in uid_set:
                    uid_push_qs = UidPushModel.objects.filter(userID=user_id, m_code=m_code, uid_set_id=item['id'])
                    if uid_push_qs.exists():
                        uid_push_qs.update(token_val=token_val, push_type=push_type, jg_token_val=jg_token_val)
                    else:
                        UidPushModel.objects.create(userID_id=user_id, appBundleId=app_bundle_id, app_type=app_type,
                                                    push_type=push_type, token_val=token_val, m_code=m_code, lang=lang,
                                                    tz=tz, addTime=now_time, updTime=now_time, uid_set_id=item['id'],
                                                    jg_token_val=jg_token_val)
        except Exception as e:
            LOGGER.info('出错了~保存推送配置信息错误,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def update_country(self, request_dict, response, request):
        username = request_dict.get('unique', None)
        appBundleId = request_dict.get('appBundleId', None)
        lang = request_dict.get('lang', '')  # 语言区域
        if username and appBundleId:
            user_qs = Device_User.objects.filter(username=username)
            if user_qs.exists():
                user = user_qs[0]
                user_ex_qs = UserExModel.objects.filter(userID_id=user.userID)
                now_time = int(time.time())
                if user_ex_qs.exists():
                    update_dict = {
                        'updTime': now_time,
                        'appBundleId': appBundleId,
                        'region': lang
                    }
                    user_ex_qs.update(**update_dict)
                    user_ex = user_ex_qs[0]
                else:
                    create_dict = {
                        'addTime': now_time,
                        'updTime': now_time,
                        'appBundleId': appBundleId,
                        'userID_id': user.userID,
                        'region': lang
                    }
                    user_ex = UserExModel.objects.create(**create_dict)
                country_ip_qs = CountryIPModel.objects.filter(user_ex_id=user_ex.id)
                if not country_ip_qs.exists():
                    countryIp = CountryIPModel(
                        ip=CommonService.get_ip_address(request),
                        add_time=now_time,
                        user_ex_id=user_ex_qs[0].id
                    )
                    countryIp.save()
                return response.json(0)
            else:
                return response.json(104)
        else:
            return response.json(444)


# 获取验证码
class verifyAuthcode(TemplateView):

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        return self.ValidationError(request_dict, response)

    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.GET
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        email = request_dict.get('email', None)
        phone = request_dict.get('phone', None)
        authcode = request_dict.get('authcode', None)
        if email is not None:
            email = email.strip()
            return self.email_validate(email, authcode, response)
        elif phone is not None:
            phone = phone.strip()
            return self.phone_validate(phone, authcode, response)
        else:
            return response.json(444)

    def email_validate(self, email, authcode, response):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        reds = RedisObject()
        resetCode = reds.get_data(key=email + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(120)
        if authcode != resetCode:
            return response.json(121)
        return response.json(0)

    def phone_validate(self, phone, authcode, response):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        reds = RedisObject()
        resetCode = reds.get_data(key=phone + '_forgetPwdResetCode')
        if resetCode is False:
            return response.json(120)
        print(resetCode)
        if authcode != resetCode:
            return response.json(121)
        return response.json(0)


# 微信登录
class wxAuthSignView(TemplateView):

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        return self.ValidationError(request_dict, response)

    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        response = ResponseObject(lang)
        request_dict = request.GET
        # return self.do_register('157113010663213800138000', '157113010663213800138000', response, 'xx')

        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        grant_code = request_dict.get('grant_code', None)  # 微信授权code
        appBundleID = request_dict.get('appBundleID', None)  # 包名
        token_val = request_dict.get('tokenVal', None)  # 推送token
        token_version = request_dict.get('tokenVersion', None)  # token版本
        print('grant_code')
        print(grant_code)
        print('appBundleID')
        print(appBundleID)
        if all([grant_code, appBundleID]):
            app_config = {
                'com.ansjer.loocamccloud': {'appid': 'wx9f6d6ce63f85b367',
                                            'secret': 'fe495884cd24637f1ae516c7f53d1b97', },
                'com.ansjer.zccloud': {'appid': 'wx2a9f5ef9baf2760f', 'secret': '5d38c7079676463149ffea593c58f2ed'},
                'com.ansjer.customizede': {'appid': 'wx2a9f5ef9baf2760f', 'secret': '5d38c7079676463149ffea593c58f2ed'},
                # ios
                'com.ansjer.zccloud_ab': {'appid': 'wx2a9f5ef9baf2760f', 'secret': '5d38c7079676463149ffea593c58f2ed'},
                # android
            }
            if appBundleID in app_config.keys():
                appid = app_config[appBundleID]['appid']
                secret = app_config[appBundleID]['secret']
                # 获取access_token请求
                at_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}' \
                         '&grant_type=authorization_code'.format(appid=appid, secret=secret, code=grant_code)
                res_req = requests.get(url=at_url)
                res_json = res_req.json()
                print(res_json)
                if 'access_token' not in res_json.keys():
                    # 授权过期
                    return response.json(717)
                access_token = res_json['access_token']
                openid = res_json['openid']
                if access_token and openid:
                    info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}'. \
                        format(access_token=access_token, openid=openid)
                    res_req = requests.get(url=info_url)
                    res_req.encoding = res_req.apparent_encoding
                    res_json = res_req.json()
                    print(res_json)
                    unionID = res_json['unionid']
                    user_extend_qs = UserOauth2Model.objects.filter(unionID=unionID, authType=1)
                    if user_extend_qs.exists():
                        # 如果用户绑定过则直接登录
                        userID = user_extend_qs[0].userID_id
                        print(userID)
                        user_qs = Device_User.objects.filter(userID=userID)
                        return self.do_login(user_qs, appBundleID, token_val, token_version, response)
                    else:
                        # 如果用户为绑定过则创建用户并进行登录返回token
                        userID = CommonService.getUserID(getUser=False)
                        nickname = res_json['nickname'] + '_' + CommonService.RandomStr(4)
                        return self.do_register(userID, nickname, response, appBundleID, token_val, token_version,
                                                unionID)
                else:
                    return response.json(414, 'access_token,openid')
            else:
                return response.json(414, 'appBundleID is wrong!')
        else:
            return response.json(414)
        # if wxcode

    # 登录
    def do_login(self, user_qs, app_bundle_id, token_val, token_version, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        userID = user_qs[0].userID
        print('userID' + userID)
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"],
                                 'appBundleId': new_bundle, 'tokenVal': token_val, 'tokenVersion': token_version})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        # 添加用户登录类型
        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
        auth_type = 0
        if oauth_qs.exists():
            auth_type = oauth_qs[0].authType
        res['authType'] = auth_type
        user_qs.update(last_login=now_time, online=True)
        return response.json(0, res)

    def do_register(self, userID, nickname, response, appBundleId, token_val, token_version, unionID):
        data_valid = DataValid()
        if data_valid.name_validate(userID) is not True:
            return response.json(105)
        try:
            users = Device_User.objects.create(
                username=userID,
                NickName=nickname,
                password=make_password('123456'),
                userID=userID,
                is_active=True,
                user_isValid=True,
            )

            nowTime = int(time.time())
            UserOauth2Model.objects.create(
                addTime=nowTime,
                updTime=nowTime,
                userID_id=users.userID,
                authType=1,
                unionID=unionID
            )
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            user_qs = Device_User.objects.filter(Q(userID=userID))
            print('---')
            print(user_qs)
            return self.do_login(user_qs, appBundleId, token_val, token_version, response)


# 获取验证码
class wxPerfectView(TemplateView):

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        return self.ValidationError(request_dict, response)

    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        response = ResponseObject(lang)
        request_dict = request.GET
        # return self.do_register('157113010663213800138000', '157113010663213800138000', response, 'xx')

        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        grant_code = request_dict.get('grant_code', None)  # 微信授权code
        appBundleID = request_dict.get('appBundleID', None)  # 包名
        token = request_dict.get('token', None)  # 包名
        if all([grant_code, appBundleID, token]):
            tko = TokenObject(token)
            if tko.code == 0:
                userID = tko.userID
                app_config = {
                    # ios
                    'com.ansjer.loocamccloud': {'appid': 'wx9f6d6ce63f85b367',
                                                'secret': 'fe495884cd24637f1ae516c7f53d1b97', },
                    'com.ansjer.zccloud': {'appid': 'wx2a9f5ef9baf2760f', 'secret': '5d38c7079676463149ffea593c58f2ed'},
                    'com.ansjer.customizede': {'appid': 'wx2a9f5ef9baf2760f',
                                               'secret': '5d38c7079676463149ffea593c58f2ed'},
                    # android
                    'com.ansjer.zccloud_ab': {'appid': 'wx2a9f5ef9baf2760f',
                                              'secret': '5d38c7079676463149ffea593c58f2ed'},

                }
                if appBundleID in app_config.keys():
                    appid = app_config[appBundleID]['appid']
                    secret = app_config[appBundleID]['secret']
                    # 获取access_token请求
                    at_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&' \
                             'code={code}&grant_type=authorization_code'. \
                        format(appid=appid, secret=secret, code=grant_code)
                    res_req = requests.get(url=at_url)
                    res_json = res_req.json()
                    LOGGER.info(f"绑定微信获取access_token返回数据:{res_json}")
                    if 'access_token' not in res_json.keys():
                        # 授权过期
                        return response.json(717)
                    access_token = res_json['access_token']
                    openid = res_json['openid']

                    if access_token and openid:
                        info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&' \
                                   'openid={openid}'.format(access_token=access_token, openid=openid)
                        res_req = requests.get(url=info_url)
                        res_req.encoding = res_req.apparent_encoding
                        res_json = res_req.json()
                        print(res_json)
                        unionID = res_json['unionid']
                        user_has_bind = UserOauth2Model.objects.filter(unionID=unionID)
                        if not user_has_bind.exists():
                            user_oauth2_qs = UserOauth2Model.objects. \
                                filter(userID_id=userID, authType=1)
                            if user_oauth2_qs.exists():
                                user_oauth2_qs.update(unionID=unionID)
                                return response.json(0)
                            else:
                                try:
                                    nowTime = int(time.time())
                                    UserOauth2Model.objects.create(
                                        addTime=nowTime,
                                        updTime=nowTime,
                                        userID_id=userID,
                                        authType=1,
                                        unionID=unionID)
                                except Exception as e:
                                    return response.json(424, repr(e))
                                else:
                                    return response.json(0)
                        else:
                            return response.json(16)
                    else:
                        return response.json(414, 'access_token,openid')
                else:
                    return response.json(414, 'appBundleID is wrong!')
            else:
                return response.json(tko.code)
        else:
            return response.json(414)


# 获取验证码
class OauthAuthCodeView(TemplateView):

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(OauthAuthCodeView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        phone = request_dict.get('phone', None)
        if phone is not None:
            was_limited = getattr(request, 'limited', False)
            if was_limited is True:
                return response.json(5)
        return self.ValidationError(request_dict, response)

    @limits(calls=2, period=60)
    def get(self, request, *args, **kwargs):
        # Device_User.objects.filter(userEmail='chanjunkai@163.com').delete()
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        request_dict = request.GET
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        email = request_dict.get('email', None)
        phone = request_dict.get('phone', None)
        country_code = request_dict.get('country_code', None)
        sign_name = request_dict.get('sign_name', None)
        token = request_dict.get('token', None)
        print(token)
        if email is not None:
            email = email.strip()
            # 阿里云的发送邮箱的调用方法
            return self.aliyun_emailCode(email, response)

            # return self.emailCode(email, response)
        elif phone is not None:
            phone = phone.strip()
            # 短信签名
            sign_name = CommonService.confirm_msg_sign_name(sign_name, phone)
            if country_code is None:
                return self.phoneCode(phone, response, sign_name)
            else:
                country_code = str(country_code.strip())
                return self.phoneCodeV2(country_code, phone, response, sign_name)
        else:
            return response.json(444)

    def emailCode(self, email, response):

        dataValid = DataValid()
        # 邮箱匹配
        if dataValid.email_validate(email) is False:
            return response.json(107)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=email + '_OauthPerfect')
        # 是否以获取邮箱验证码
        if identifyingCode:
            return response.json(89)
        user_qs = Device_User.objects.filter(username=email)
        email_qs = Device_User.objects.filter(userEmail=email)
        # 邮箱用户是否已存在
        if user_qs.exists():
            return response.json(103)
        elif email_qs.exists():
            return response.json(103)
        # 生成随机6位数
        identifyingCode = RandomStr(6, True)
        # 设置随机数缓存生命周期
        send_data = TemplateService.email_message(type='register_code', language=response.lang)
        ses = SesClassObject()
        # 发送邮件
        send_res = ses.send_email(
            send_address_list=[email],
            subject=send_data['title'],
            body=send_data['body'].replace("{username}", email).replace("{captcha}",
                                                                        str(identifyingCode))
        )
        if send_res is not True:
            return response.json(44)
        if reds.set_data(key=email + '_OauthPerfect', val=identifyingCode, expire=600) is not True:
            return response.json(10, 'error')
        return response.json(0)
        # return response.json(0, {'identifyingCode': identifyingCode})

    # 阿里云获取邮箱验证码
    def aliyun_emailCode(self, email, response):
        print('阿里云开始')
        dataValid = DataValid()
        # 邮箱匹配
        if dataValid.email_validate(email) is False:
            return response.json(107)
        reds = RedisObject()
        identifyingCode = reds.get_data(key=email + '_OauthPerfect')
        # 是否以获取邮箱验证码
        if identifyingCode:
            return response.json(89)
        user_qs = Device_User.objects.filter(username=email)
        email_qs = Device_User.objects.filter(userEmail=email)
        # 邮箱用户是否已存在
        if user_qs.exists():
            return response.json(103)
        elif email_qs.exists():
            return response.json(103)
        # 生成随机6位数
        identifyingCode = RandomStr(6, True)
        # 设置随机数缓存生命周期
        send_data = TemplateService.email_message(type='register_code', language=response.lang)
        ses = SesClassObject()
        # 发送邮件
        send_res = ses.alyEmailCode(
            send_address_list=[email],
            subject=send_data['title'],
            body=send_data['body'].replace("{username}", email).replace("{captcha}", str(identifyingCode))
        )
        if send_res is not True:
            return response.json(44)
        if reds.set_data(key=email + '_OauthPerfect', val=identifyingCode, expire=600) is not True:
            return response.json(10, 'error')
        return response.json(0)

    def phoneCode(self, phone, response, sign_name):
        dataValid = DataValid()
        if dataValid.mobile_validate(phone) is not True:
            return response.json(107)
        reds = RedisObject()
        reds_key = str(phone) + '_OauthPerfect'
        identifyingCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and identifyingCode:
            # if identifyingCode :
            return response.json(90)
        user_qs = Device_User.objects.filter(username=phone)
        phone_qs = Device_User.objects.filter(phone=phone)
        if user_qs.exists() or phone_qs.exists():
            return response.json(101)
        identifyingCode = RandomStr(6, True)
        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name=sign_name, temp_msg='SMS_151600991')
        if res["Code"] == "OK":
            if reds.set_data(key=reds_key, val=identifyingCode, expire=300) is not True:
                return response.json(10, '生成缓存系统错误')
            return response.json(0)
        else:
            return response.json(10, res["Message"])

    def phoneCodeV2(self, country_code, phone, response, sign_name):
        dataValid = DataValid()
        if dataValid.mobile_validate(phone) is not True:
            return response.json(107)
        reds = RedisObject()
        reds_key = str(phone) + '_OauthPerfect'
        identifyingCode = reds.get_data(key=reds_key)
        reds_key_ttl = reds.get_ttl(key=reds_key)
        if reds_key_ttl > 240 and identifyingCode:
            # if identifyingCode :
            return response.json(90)
        user_qs = Device_User.objects.filter(username=phone)
        phone_qs = Device_User.objects.filter(phone=phone)
        if user_qs.exists() or phone_qs.exists():
            return response.json(101)
        identifyingCode = RandomStr(6, True)

        if country_code == '86':
            # 国内短信推送模板
            temp_msg = 'SMS_151600991'
            rec_phone = phone
        else:
            # 国际短信推送模板
            temp_msg = 'SMS_172165867'
            rec_phone = country_code + phone
            sign_name = 'Ansjer'

        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=rec_phone, code=identifyingCode, sign_name=sign_name, temp_msg=temp_msg)
        if res["Code"] == "OK":
            if reds.set_data(key=reds_key, val=identifyingCode, expire=300) is not True:
                return response.json(10, '生成缓存系统错误')
            return response.json(0)
        else:
            return response.json(10, res["Message"])


class OauthPerfectView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(OauthPerfectView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def post(self, request):
        request.encoding = 'utf-8'
        request_dict = request.POST
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        authcode = request_dict.get('authcode', None)
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if password is None or authcode is None:
            return response.json(444, 'password,authcode')
        authcode = CommonService.decode_data(authcode.strip())
        if authcode is None:
            return response.json(444, 'password,authcode')

        password = CommonService.decode_data(password.strip())
        if password is None:
            return response.json(444, 'password,authcode')
        if phone is not None:
            phone = phone.strip()
            return self.do_phone(tko, phone, authcode, password, response, password_version, salt)
        elif email is not None:
            email = email.strip()
            return self.do_email(tko, email, authcode, password, response, password_version, salt)
        else:
            return response.json(444, 'phone')

    def do_email(self, tko, email, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)

        if tko.code == 0:
            user_qs = Device_User.objects.filter(userID=tko.userID)
        else:
            return response.json(tko.code)
        if not user_qs.exists():
            return response.json(104)
        reds = RedisObject()
        resetCode = reds.get_data(key=email + '_OauthPerfect')
        if resetCode is False:
            return response.json(90)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=email + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(userEmail=email, password=password)
        if not reds.del_data(email + '_OauthPerfect'):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    def do_phone(self, tko, phone, authcode, password, response, password_version, salt):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)

        if tko.code == 0:
            user_qs = Device_User.objects.filter(userID=tko.userID)
        else:
            return response.json(tko.code)
        if not user_qs.exists():
            return response.json(102)
        reds = RedisObject()
        resetCode = reds.get_data(key=str(phone) + '_OauthPerfect')
        print(resetCode)
        if resetCode is False:
            return response.json(90)
        if authcode != resetCode:
            return response.json(121)
        # if not reds.set_data(key=phone + '_forgetPwdResetCode', val=resetCode, expire=300):
        #     return response.json(10, '生成缓存错误')
        user_qs.update(phone=phone, password=password)
        if not reds.del_data(str(phone) + '_OauthPerfect'):
            return response.json(10, '删除缓存失败')
        return response.json(0)


class SingleLoginView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(SingleLoginView, self).dispatch(*args, **kwargs)

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

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

    def validation(self, request, request_dict, operation):
        lang = request_dict.get('lang', 'en')
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        if operation == 'get-verification-code':  # 获取验证码
            return self.get_verification_code(request_dict, response)
        elif operation == 'change-password':  # 验证码修改密码
            return self.change_password(request_dict, response)
        else:
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            if tko.code != 0:
                return response.json(tko.code)
            if operation == 'get-login-status':  # 获取登录状态
                return self.get_login_status(response)
            else:
                return response.json(404)

    @staticmethod
    def get_login_status(response):
        return response.json(0)

    def get_verification_code(self, request_dict, response):
        email = request_dict.get('email', None)
        phone = request_dict.get('phone', None)
        sign_name = request_dict.get('sign_name', None)
        country_code = request_dict.get('country_code', None)
        code_type = request_dict.get('code_type', None)
        uid = request_dict.get('uid', None)
        if not any([email, phone]):
            return response.json(444)

        try:
            # 查看设备密码,传uid和检验主用户
            if code_type == '2':
                if uid is None:
                    return response.json(444)
                user_info = email if email is not None else phone
                # 查询主用户信息
                device_info_qs = Device_Info.objects.filter(UID=uid).values('vodPrimaryMaster')
                if not device_info_qs.exists():
                    return response.json(173)
                if user_info != device_info_qs[0]['vodPrimaryMaster']:
                    return response.json(12)
            # 邮箱验证码
            if email is not None:
                email = email.strip()
                return self.get_aliyun_email_code(email, code_type, uid, response)
            # 手机验证码
            else:
                phone = phone.strip()
                country_code = str(country_code.strip())
                # 短信签名
                sign_name = CommonService.confirm_msg_sign_name(sign_name, phone)
                return self.get_phone_code(country_code, phone, sign_name, code_type, uid, response)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_aliyun_email_code(email, code_type, uid, response):
        """
        获取邮箱验证码
        @param email: 邮箱
        @param code_type:  不传: 单点登录, 2: 查看设备密码
        @param uid:
        @param response:
        @return:
        """
        data_valid = DataValid()
        # 邮箱匹配
        if data_valid.email_validate(email) is False:
            return response.json(107)
        # 查询用户是否存在
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        if not user_qs.exists():
            return response.json(99)

        # 确定缓存key
        if code_type is None:
            redis_key = '{}_SingleLogin'.format(email)
            email_type = 'register_code'
        elif code_type == '2':
            redis_key = '{}_{}_GetDevicePassword'.format(email, uid)
            email_type = 'get_device_password'
        else:
            return response.json(444)

        redis_obj = RedisObject()
        # 检查是否已获取邮箱验证码
        identifying_code = redis_obj.get_data(key=redis_key)
        if identifying_code:
            return response.json(89)

        # 生成随机6位数
        identifying_code = RandomStr(6, True)
        # 设置随机数缓存生命周期
        send_data = TemplateService.email_message(type=email_type, language=response.lang)
        ses = SesClassObject()
        # 发送邮件
        send_res = ses.alyEmailCode(
            send_address_list=[email],
            subject=send_data['title'],
            body=send_data['body'].replace('{username}', email).replace('{captcha}', str(identifying_code))
        )
        if send_res is not True:
            return response.json(44)
        if redis_obj.set_data(key=redis_key, val=identifying_code, expire=600) is not True:
            return response.json(10, 'error')
        return response.json(0)

    @staticmethod
    def get_phone_code(country_code, phone, sign_name, code_type, uid, response):
        """
        获取手机验证码
        @param country_code: 国家编码
        @param phone: 手机号码
        @param sign_name: 短信签名
        @param code_type: 验证码类型, None: 单点登录, 1: 修改手机号码, 2: 查看设备密码
        @param uid:
        @param response:
        @return:
        """
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(107)
        # 根据验证码类型确定缓存key和短信模板
        if code_type is None:
            user_qs = Device_User.objects.filter(Q(username=phone) | Q(phone=phone))
            if not user_qs.exists():
                return response.json(102)
            redis_key = '{}_SingleLogin'.format(phone)
            # 短信模板
            temp_msg = 'SMS_151675019' if country_code == '86' else 'SMS_172200051'
        elif code_type == '1':
            redis_key = '{}_ChangePhone'.format(phone)
            temp_msg = 'SMS_151675018' if country_code == '86' else 'SMS_172165867'
        elif code_type == '2':
            redis_key = '{}_{}_GetDevicePassword'.format(phone, uid)
            temp_msg = 'SMS_479855154' if country_code == '86' else 'SMS_479785146'
        else:
            return response.json(444)

        # 根据手机区号处理发送手机号码和签名
        if country_code == '86':
            rec_phone = phone
        else:
            rec_phone = country_code + phone
            sign_name = 'Ansjer'

        redis_obj = RedisObject()
        identifying_code = redis_obj.get_data(key=redis_key)
        reds_key_ttl = redis_obj.get_ttl(key=redis_key)
        if reds_key_ttl > 240 and identifying_code:
            return response.json(90)
        identifying_code = RandomStr(6, True)

        # 发送手机验证码
        alisms = AliSmsObject()
        res = alisms.send_code_sms(phone=rec_phone, code=identifying_code, sign_name=sign_name, temp_msg=temp_msg)
        if res['Code'] == 'OK':
            if redis_obj.set_data(key=redis_key, val=identifying_code, expire=300) is not True:
                return response.json(10, '生成缓存系统错误')
            return response.json(0)
        else:
            return response.json(10, res['Message'])

    def change_password(self, request_dict, response):
        phone = request_dict.get('phone', None)
        email = request_dict.get('email', None)
        password = request_dict.get('password', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        authcode = request_dict.get('authcode', None)
        app_bundle_id = request_dict.get('appBundleId', None)
        token_val = request_dict.get('tokenVal', None)
        if not all([app_bundle_id, token_val]):
            return response.json(444, 'appBundleId,tokenVal')
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        if password is None or authcode is None:
            return response.json(444, 'password,authcode')
        authcode = CommonService.decode_data(authcode.strip())
        if authcode is None:
            return response.json(444, 'password,authcode')

        password = CommonService.decode_data(password.strip())
        if password is None:
            return response.json(444, 'password,authcode')
        if phone is not None:
            phone = phone.strip()
            return self.do_phone(phone, authcode, password, response, password_version, salt, new_bundle, token_val)
        elif email is not None:
            email = email.strip()
            return self.do_email(email, authcode, password, response, password_version, salt, new_bundle, token_val)
        else:
            return response.json(444, 'phone')

    @staticmethod
    def do_email(email, authcode, password, response, password_version, salt, new_bundle, token_val):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        # 邮箱用户是否已存在
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        if not user_qs.exists():
            return response.json(99)
        user_id = user_qs[0].userID
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        key = email + '_SingleLogin'
        reset_code = reds.get_data(key=key)
        if reset_code is False:
            return response.json(92)
        if authcode != reset_code:
            return response.json(121)
        user_qs.update(userEmail=email, password=password)
        if not reds.del_data(key):
            return response.json(10, '删除缓存失败')
        key = 'token_user_{}_{}'.format(user_id, new_bundle)
        LOGGER.info('{}修改密码写入token：{}'.format(user_id, 'temp_value'))
        reds.set_data(key, 'temp_value')
        push_url = '{}transparent-transmission/logout-push'.format(DETECT_PUSH_DOMAINS)
        result = requests.post(push_url, data={'push_token': token_val, 'user_id': user_id,
                                               'app_bundle_id': new_bundle})
        LOGGER.info('{}修改密码推送结果:{}'.format(user_id, result.json()))
        return response.json(0)

    @staticmethod
    def do_phone(phone, authcode, password, response, password_version, salt, new_bundle, token_val):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        user_qs = Device_User.objects.filter(Q(username=phone) | Q(phone=phone))
        if not user_qs.exists():
            return response.json(102)
        user_id = user_qs[0].userID
        if password_version == 'V1':
            re_flag = data_valid.password_validate(password)
            password = make_password(password)
        else:
            if not salt:
                return response.json(111)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
            re_flag = True
        if re_flag is not True:
            return response.json(109)
        reds = RedisObject()
        key = str(phone) + '_SingleLogin'
        reset_code = reds.get_data(key=key)
        if reset_code is False:
            return response.json(92)
        if authcode != reset_code:
            return response.json(121)
        user_qs.update(phone=phone, password=password)
        if not reds.del_data(key):
            return response.json(10, '删除缓存失败')
        key = 'token_user_{}_{}'.format(user_id, new_bundle)
        LOGGER.info('{}修改密码写入token：{}'.format(user_id, 'temp_value'))
        reds.set_data(key, 'temp_value')
        push_url = '{}transparent-transmission/logout-push'.format(DETECT_PUSH_DOMAINS)
        result = requests.post(push_url, data={'push_token': token_val, 'user_id': user_id,
                                               'app_bundle_id': new_bundle})
        LOGGER.info('{}修改密码推送结果:{}'.format(user_id, result.json()))
        return response.json(0)


class UnbundingWXView(TemplateView):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        return self.ValidationError(request_dict, response)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        lang = request_dict.get('lang')
        if not lang:
            lang = request_dict.get('language', None)
        response = ResponseObject(lang)
        return self.ValidationError(request_dict, response)

    def ValidationError(self, request_dict, response):
        token = request_dict.get('token', None)
        auth_type = request_dict.get('auth_type', None)
        if not all([token, auth_type]):
            return response.json(444, 'token,auth_type')
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            user_oauth2_qs = UserOauth2Model.objects.filter(
                ~Q(unionID='') & Q(userID_id=userID) & Q(authType=auth_type))
            if user_oauth2_qs.exists():
                user_qs = Device_User.objects.filter(phone='', userEmail='', userID=userID)
                if user_qs.exists():
                    return response.json(17)
                else:
                    user_oauth2_qs.delete()
                    return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(tko.code)


class alexaAuthView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        # request_dict = json.loads(request.body.decode('utf-8'))
        request_dict = request.POST
        response = ResponseObject()
        return self.validates(request_dict, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        response = ResponseObject()
        return self.validates(request_dict, response)

    def validates(self, request_dict, response):
        username = request_dict.get('userName', None)
        password = request_dict.get('userPwd', None)
        salt = request_dict.get('salt', None)
        iterations = request_dict.get('iterations', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        if not username or not password:
            return response.json(111)
        username = username.strip()
        password = password.strip()
        data_valid = DataValid()
        if data_valid.email_validate(username):
            return self.do_email_login(username, password, response, password_version, salt, iterations)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, password, response, password_version, salt, iterations)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, password, response, password_version, salt, iterations)
        else:
            return response.json(107)

    def do_email_login(self, email, password, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        return self.valid_login(user_qs, password, response, password_version, salt, iterations)

    def do_phone_login(self, phone, password, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response, password_version, salt, iterations)

    def do_name_login(self, username, password, response, password_version, salt, iterations):
        user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                             is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response, password_version, salt, iterations)

    def valid_login(self, user_qs, password, response, password_version, salt, iterations):
        if not user_qs.exists():
            return response.json(104)
        users = user_qs.values('userID', 'password', 'region_country')[0]
        if password_version == 'V1':
            check_flag = check_password(password, users['password'])
        else:
            if not all([iterations, salt]):
                return response.json(444)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), salt, password)
            check_flag = CommonService.check_password(password, users['password'])
        if not check_flag:
            return response.json(111)
        userID = users['userID']
        region_country = users['region_country']

        # 确认用户地区
        region_code = 'US'
        country_qs = CountryModel.objects.filter(id=region_country).values('region_id')
        if country_qs.exists():
            region_id = country_qs[0]['region_id']
            if region_id == 4:
                region_code = 'EU'

        res = {
            'userID': userID,
            'region_code': region_code
        }
        return response.json(0, res)


class alexaUidView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        response = ResponseObject()
        return self.validates(request_dict, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        response = ResponseObject()
        return self.validates(request_dict, response)

    def validates1(self, request_dict, response):
        userID = request_dict.get('alexa_user_id')
        sid = request_dict.get('sid')
        sst = request_dict.get('sst')
        if sid == 'admin' and sst == 'admin':
            uid_qs = Device_Info.objects.filter(userID_id=userID, isExist=1).values('UID', 'NickName', 'View_Password')
            uid_arr = []
            uid_list = []
            for uid_q in uid_qs:
                uid_list.append(uid_q['UID'])
                uid_arr.append({'uid': uid_q['UID'], 'nick': uid_q['NickName'], 'password': uid_q['View_Password'], })
            res = {
                'uid_arr': uid_arr
            }
            return response.json(0, res)
        else:
            return response.json(107)

    def validates(self, request_dict, response):
        sid = request_dict.get('sid')
        sst = request_dict.get('sst')
        userID = request_dict.get('alexa_user_id')

        if sid != 'admin' or sst != 'admin':
            return response.json(107)
        uid_qs = Device_Info.objects.filter(userID_id=userID, isExist=1).values('UID', 'NickName', 'View_Password',
                                                                                'userID__region_country')
        if not uid_qs.exists():
            return response.json(107)
        country_qs = CountryModel.objects.filter(id=uid_qs[0]['userID__region_country']).values(
            'region__continent_code')

        try:
            uid_dict = {}
            uid_list = []
            for uid_q in uid_qs:
                # uid转大写
                UID = uid_q['UID'].upper()
                uid_list.append(UID)
                uid_dict[UID] = {'nick': uid_q['NickName'], 'password': uid_q['View_Password']}

            us_qs = UidSetModel.objects.filter(uid__in=uid_list, is_alexa=1).values('id', 'uid', 'region_alexa',
                                                                                    'channel')
            if not us_qs.exists():
                return response.json(173)
            # uid,password,region的列表
            uid_arr = []
            for us in us_qs:
                uid = us['uid']
                channel = us['channel']
                # 设备alexa区域
                region_alexa = country_qs[0]['region__continent_code'] if country_qs.exists() else 'EN'

                # 多通道设备获取通道名
                if channel > 1:
                    uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us['id']).values('channel',
                                                                                                   'channel_name')
                    if uid_channel_set_qs.exists():
                        # DVR设备名为 UidChannelSetModel 的 channel_name
                        for uid_channel_set in uid_channel_set_qs:
                            uid_arr.append({'uid': uid, 'nick': uid_channel_set['channel_name'], 'region': region_alexa,
                                            'password': uid_dict[uid]['password'], 'multi_channel': 1,
                                            'channel': uid_channel_set['channel']})
                else:
                    uid_arr.append({'uid': uid, 'nick': uid_dict[uid]['nick'], 'region': region_alexa,
                                    'password': uid_dict[uid]['password'], 'multi_channel': 0})
            res = {
                'uid_arr': uid_arr
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


class alexaSwitchView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        # request_dict = json.loads(request.body.decode('utf-8'))
        request_dict = request.POST
        response = ResponseObject()
        return self.validates(request_dict, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        response = ResponseObject()
        return self.validates(request_dict, response)

    def validates(self, request_dict, response):
        sid = request_dict.get('sid')
        sst = request_dict.get('sst')
        userID = request_dict.get('alexa_user_id')

        if sid != 'admin' or sst != 'admin':
            return response.json(107)
        switch_qs = Device_Info.objects.filter(userID_id=userID, Type=201).values('UID', 'NickName')
        if not switch_qs.exists():
            return response.json(107)
        # 设备alexa区域
        region_id = CommonService.confirm_region_id()
        if region_id == 4:
            region_alexa = 'EU'
        elif region_id == 5:
            region_alexa = 'CN'
        else:
            region_alexa = 'US'
        try:
            switch_list = []
            for switch in switch_qs:
                uid = switch['UID']
                nick_name = switch['NickName']
                switch_list.append({'uid': uid, 'nick': nick_name, 'region': region_alexa})
            res = {
                'switch_list': switch_list
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


# 登出
class V2LogoutView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(V2LogoutView, self).dispatch(*args, **kwargs)

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

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

    def Logout(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token')
        tko = TokenObject(token)
        userID = tko.userID
        if tko.code == 0:
            Device_User.objects.filter(userID=tko.userID).update(online=False)

            redisObj = RedisObject(db=3)
            redisObj.del_data(key=tko.userID)
            m_code = request_dict.get('m_code', None)
            if m_code:
                try:
                    UidPushModel.objects.filter(userID_id=userID, m_code=m_code).delete()
                except Exception as e:
                    print(repr(e))
                else:
                    pass
            os_type = request_dict.get('os_type', None)
            appid = request_dict.get('appid', None)
            udid = request_dict.get('udid', None)
            if os_type and appid and udid:
                tutk_push_url = "{tutk_push_domain}?cmd=mapsync&os={os_type}&appid={appid}&udid={udid}". \
                    format(os_type=os_type, appid=appid, udid=udid, tutk_push_domain=TUTK_PUSH_DOMAIN)
                res = requests.get(url=tutk_push_url)
                res_s = res.text
                res_s = res_s.rstrip()

                if res_s == '200 Success.':
                    return response.json(0)
                else:
                    return response.json(10, 'not yes')
            return response.json(0)
        else:
            return response.json(tko.code)


# 图片验证码生成
class generatePictureCodeView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(generatePictureCodeView, self).dispatch(*args, **kwargs)

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

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

    # 生成验证码和验证码图片
    def get_valid_code_img(self, request_dict):
        # ---------生成背景图片-----------
        # img = Image.new('RGB', (260, 34), color=get_random_color())
        img = Image.new('RGB', (260, 34),
                        color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        # -------/生成背景图片-----------

        # --------生成随机验证码，设置字体格式，大小等属性------------
        draw = ImageDraw.Draw(img)
        path = BASE_DIR + '/Ansjer/file/font/simhei.ttf'
        kumo_font = ImageFont.truetype(path, 40, encoding="unic")  # 设置字体
        print("字体可以")
        valid_code_str = ''
        for i in range(6):
            random_num = str(random.randint(0, 9))
            random_low_alpha = chr(random.randint(97, 122))
            random_high_alpha = chr(random.randint(65, 90))
            random_char = random.choice([random_num, random_low_alpha, random_high_alpha])
            draw.text((i * 40 + 20, -3), random_char, 'white', kumo_font)

            # 保存验证码字符串
            valid_code_str += random_char
        print(valid_code_str)
        # --------/生成随机验证码，设置字体格式，大小等属性------------

        # -------增加干扰线，点----------
        # 噪点噪线
        width = 260
        height = 34
        for i in range(10):
            x1 = random.randint(0, width)
            x2 = random.randint(0, width)
            y1 = random.randint(0, height)
            y2 = random.randint(0, height)
            draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

        for i in range(10):
            draw.point([random.randint(0, width), random.randint(0, height)],
                       fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
            x = random.randint(0, width)
            y = random.randint(0, height)
            draw.arc((x, y, x + 4, y + 4), 0, 90,
                     fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        # -------/增加干扰线，点-----------
        # ------存入内存---------
        f = BytesIO()  # 用完之后，BytesIO会自动清掉
        img.save(f, 'png')
        data = f.getvalue()
        return data, valid_code_str

    # 生成验证码方法
    def validates(self, request_dict):
        # 页面传过来的uuid
        imageCodeId = request_dict.get('imageCodeId', '')
        response = ResponseObject()
        if not imageCodeId:
            return response.json(444)
        # 存入redis的key
        image_code_id = "image_code_%s" % imageCodeId
        """
        基于PIL模块动态生成响应状态码图片
        :param request:
        :return:
        """
        # 图片data,验证码
        data, valid_code_str = self.get_valid_code_img(request_dict)
        if imageCodeId:
            redisObj = RedisObject(db=6)
            # 单条维护
            redisObj.set_data(key=image_code_id, val=valid_code_str, expire=120)
            image_code_val = redisObj.get_data(key=image_code_id)
            print("________获取验证码的值" + image_code_val)
            return HttpResponse(data, 'image/png')


class Image_Code_RegisterView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(Image_Code_RegisterView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict):
        """
        图片验证码注册
        @param request_dict: 请求数据
        @request_dict userEmail: 邮箱
        @request_dict userPwd: 密码
        @request_dict imageCodeId: 图片验证码id
        @request_dict valid_code: 验证码
        @request_dict unique: 手机唯一标识
        @request_dict number: 国家id号
        @request_dict region_status: 地区选择状态
        @request_dict lang: 语言
        @return: response
        """
        userEmail = request_dict.get('userEmail', None)
        password = request_dict.get('userPwd', None)
        salt = request_dict.get('salt', None)
        password_version = request_dict.get('pwdVersion', 'V1')
        imageCodeId = request_dict.get('imageCodeId', None)
        valid_code = request_dict.get('id_v_code', None)
        unique = request_dict.get('unique', None)
        number = request_dict.get('number', None)
        region_status = request_dict.get('region_status', None)
        lang = request_dict.get('lang', None)
        response = ResponseObject(lang)
        email_scription = request_dict.get('email_scription', None)
        push_scription = request_dict.get('push_scription', None)
        app_bundle_id = request_dict.get('appBundleId', None)
        token_val = request_dict.get('tokenVal', None)
        token_version = request_dict.get('tokenVersion', None)

        if not all([userEmail, password, lang, imageCodeId, valid_code]):
            return response.json(444)

        if unique:
            delete_local_account(unique)
        region_status = int(region_status) if region_status else 0

        try:
            if password_version == 'V1':
                for i in range(1, 4):
                    if i == 1:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[1:-1]
                    if i == 2:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[2:-2]
                    if i == 3:
                        password = base64.b64decode(password)
                        password = password.decode('utf-8')
                        password = password[3:-3]
                password = make_password(password)
            else:
                if not salt:
                    return response.json(111)
                password = "%s$%d$%s$%s" % ("pbkdf2_sha256", 260000, salt, password)
        except Exception as e:
            print(repr(e))
            return response.json(111)
        try:
            for i in range(1, 4):
                if i == 1:
                    valid_code = base64.b64decode(valid_code)
                    valid_code = valid_code.decode('utf-8')
                    valid_code = valid_code[1:-1]
                if i == 2:
                    valid_code = base64.b64decode(valid_code)
                    valid_code = valid_code.decode('utf-8')
                    valid_code = valid_code[2:-2]
                if i == 3:
                    valid_code = base64.b64decode(valid_code)
                    valid_code = valid_code.decode('utf-8')
                    valid_code = valid_code[3:-3]
        except Exception as e:
            print(repr(e))
            return response.json(121)
        if not userEmail:
            return response.json(105)
        if not password:
            return response.json(109)

        userEmail = userEmail.strip()
        password = password.strip()
        # 注释
        if userEmail:
            emailValid = Device_User.objects.filter(userEmail=userEmail)
            if emailValid:
                return response.json(103)

        # 判断验证码是否过期
        image_code_key = 'image_code_%s' % imageCodeId
        redisObj = RedisObject(db=6)
        redis_image_code = redisObj.get_data(key=image_code_key)
        # 验证用户输入的验证码和redis中的验证码
        if redis_image_code is False or valid_code.lower() != redis_image_code.lower():
            return response.json(121)
        # 删除redis中的图片验证码，防止用户使用同一个图片验证码验证多次
        redisObj.del_data(key=image_code_key)
        username = userEmail
        email_qs = Device_User.objects.filter(Q(userEmail=userEmail) | Q(username=userEmail))
        if email_qs:
            return response.json(103)

        # 创建用户
        userID = CommonService.getUserID(μs=False, setOTAID=True)
        create_data = {
            "username": username,
            "NickName": username,
            "userEmail": userEmail,
            "password": password,
            "userID": userID,
            "is_active": True,
            "user_isValid": True,
            "region_status": region_status
        }
        if number:
            create_data["region_country"] = number
        Device_User.objects.create(**create_data)
        if push_scription:
            UserEmailSubscriptions.objects.create(email=userEmail, user_id=userID, push_sub_status=1)
        else:
            UserEmailSubscriptions.objects.create(email=userEmail, user_id=userID, push_sub_status=0)
        if email_scription:
            subscribers = {
                "userEmail": userEmail,
                "region_country": number
            }
            subscription_thread = threading.Thread(target=UserSubscriptionControllerView.subscription,
                                                   args=(subscribers,))
            subscription_thread.start()
        return self.do_login(email_qs, app_bundle_id, token_val, token_version, response)

    @staticmethod
    def do_login(user_qs, app_bundle_id, token_val, token_version, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        user_qs.update(last_login=now_time, online=True)
        userID = user_qs[0].userID
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"],
                                 'appBundleId': new_bundle, 'tokenVal': token_val, 'tokenVersion': token_version})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        return response.json(0, res)


class UserAppFrequencyView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(UserAppFrequencyView, self).dispatch(*args, **kwargs)

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

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

    def validates(self, request_dict, operation):
        token = request_dict.get('token', None)
        response = ResponseObject()

        token = TokenObject(token)
        if token.code != 0:
            return response.json(token.code)

        if operation == 'refresh':
            return self.do_refresh(request_dict, token.userID, response)
        else:
            return response.json(404)

    def do_refresh(self, request_dict, userID, response):
        type = request_dict.get('type', None)
        month = request_dict.get('month', None)
        if not type or not month:
            return response.json(444, 'type')
        else:
            type = int(type)
            now_time = int(time.time())
            month = int(month)
            uaf_qs = UserAppFrequencyModel.objects.filter(user__userID=userID)

            if not uaf_qs.exists():
                user = Device_User.objects.filter(userID=userID)[0]
                data = {
                    'user': user,
                    'type': type,
                    'data_time': month,
                    'add_time': now_time,
                    'update_time': now_time,
                }
                UserAppFrequencyModel.objects.create(**data)
                return response.json(0)
            else:
                updateMonth = time.strftime('%m', time.localtime(month))
                uaf = uaf_qs.values('id', 'type', 'data_time')[0]
                dbMonth = time.strftime('%m', time.localtime(int(uaf['data_time'])))
                print('update month is ' + updateMonth)
                print('db month is ' + dbMonth)
                if updateMonth == dbMonth:
                    UserAppFrequencyModel.objects.filter(id=uaf['id']).update(type=type)
                    return response.json(0)
                elif updateMonth > dbMonth:
                    user = Device_User.objects.filter(userID=userID)[0]
                    data = {
                        'user': user,
                        'type': type,
                        'data_time': month,
                        'add_time': now_time,
                        'update_time': now_time,
                    }
                    UserAppFrequencyModel.objects.create(**data)
                    return response.json(0)
                else:
                    return response.json(444, 'month')


class loginCodeView(View):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(loginCodeView, self).dispatch(*args, **kwargs)

    @limits(calls=2, period=60)
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        phone = request_dict.get('phone', None)
        if phone is not None:
            was_limited = getattr(request, 'limited', False)
            if was_limited is True:
                return response.json(5)
        return self.validate(request_dict, response)

    @limits(calls=2, period=60)
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        request_dict = request.GET
        return self.validate(request_dict, response)

    def validate(self, request_dict, response):
        phone = request_dict.get('phone', None)
        request_dict.get('country_code', None)
        sign_name = request_dict.get('sign_name', None)

        if phone and sign_name:
            du_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone))
            if not du_qs.exists():
                return response.json(104)
            else:
                redisObject = RedisObject()
                login_code_key = '{phone}_login_code'.format(phone=phone)
                login_code = redisObject.get_data(key=login_code_key)
                login_code_ttl = redisObject.get_ttl(key=login_code_key)
                if login_code_ttl > 240 and login_code:
                    return response.json(90)
                login_code = RandomStr(6, True)
                aliSms = AliSmsObject()
                # 短信签名
                sign_name = CommonService.confirm_msg_sign_name(sign_name, phone)

                res = aliSms.send_code_sms(phone=phone, code=login_code, sign_name=sign_name, temp_msg='SMS_151675022')

                if res['Code'] == 'OK':
                    if redisObject.set_data(key=login_code_key, val=login_code, expire=300) is not True:
                        return response.json(48)
                    return response.json(0)
                else:
                    return response.json(10, res['Message'])
        else:
            return response.json(444)


class v3LoginByCodeView(View):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(v3LoginByCodeView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST
        phone = request_dict.get('phone', None)
        if phone is not None:
            was_limited = getattr(request, 'limited', False)
            if was_limited is True:
                return response.json(5)
        return self.validate(request_dict, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        request_dict = request.GET
        return self.validate(request_dict, response)

    def validate(self, request_dict, response):
        phone = request_dict.get('phone', None)
        app_bundle_id = request_dict.get('appBundleId', None)
        token_val = request_dict.get('tokenVal', None)
        token_version = request_dict.get('tokenVersion', None)
        code = request_dict.get('code', None)

        if phone and code:
            redisObject = RedisObject()
            login_code_key = '{phone}_login_code'.format(phone=phone)
            login_code = redisObject.get_data(key=login_code_key)

            if login_code is not False:
                print(code)
                code = CommonService.decode_data(code)
                print(code)
                if login_code == code:
                    if response.lang is None:
                        response.lang = 'en'
                    return self.do_phone_login(phone, app_bundle_id, token_val, token_version, response)
                else:
                    return response.json(121)
            else:
                return response.json(120)

    def do_phone_login(self, phone, app_bundle_id, token_val, token_version, response):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True,
                                             user_isValid=True)
        return self.valid_login(user_qs, app_bundle_id, token_val, token_version, response)

    def valid_login(self, user_qs, app_bundle_id, token_val, token_version, response):
        if not user_qs.exists():
            return response.json(104)
        # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
        #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath')[0]

        userID = users['userID']
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        tko = TokenObject()
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'tokenVersion': token_version,
                  'm_code': '123413243214', 'appBundleId': new_bundle, 'tokenVal': token_val})
        # 添加用户登录类型
        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
        auth_type = 0
        if oauth_qs.exists():
            auth_type = oauth_qs[0].authType

        if tko.code == 0:
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            user_qs.update(last_login=now_time, language=response.lang)
            res['rid'] = users['role__rid']
            res['roleName'] = users['role__roleName']
            res['permList'] = ModelService.own_permission(userID)
            res['userID'] = userID
            # 昵称，邮箱，电话，刷新，头像
            userIconPath = str(users['userIconPath'])
            if userIconPath and userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
            else:
                res['userIconUrl'] = ''
            res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
            res['username'] = users['username'] if users['username'] is not None else ''
            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
            res['phone'] = users['phone'] if users['phone'] is not None else ''
            res['authType'] = auth_type
            return response.json(0, res)
        else:
            return response.json(tko.code)


class v3LoginByFingerprintView(View):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(v3LoginByFingerprintView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.POST.get('lang', None)
        if not lang:
            lang = request.POST.get('language', None)
        response = ResponseObject(lang)
        request_dict = request.POST

        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        return self.validate(request_dict, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        lang = request.GET.get('lang', None)
        if not lang:
            lang = request.GET.get('language', None)
        response = ResponseObject(lang)
        was_limited = getattr(request, 'limited', False)
        if was_limited is True:
            return response.json(5)
        request_dict = request.GET
        return self.validate(request_dict, response)

    def validate(self, request_dict, response):
        password = request_dict.get("password", None)

        if password:
            password = CommonService.decode_data(password)
            if password is None:
                return response.json(444)
            else:
                user_qs = Device_User.objects.filter(username=password, is_active=True, user_isValid=True)
                if not user_qs.exists():
                    return response.json(104)
                else:
                    users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                                           'phone', 'password', 'userIconPath', 'fingerprint_enable',
                                           'fingerprint_key')[0]
                    if users['fingerprint_enable'] == 0:
                        return response.json(112)
                    else:
                        userID = users['userID']
                        tko = TokenObject()
                        res = tko.generate(
                            data={'userID': userID, 'lang': response.lang, 'user': users['username'],
                                  'm_code': '123413243214'})
                        if tko.code == 0:
                            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
                            user_qs.update(last_login=now_time, language=response.lang)
                            res['rid'] = users['role__rid']
                            res['roleName'] = users['role__roleName']
                            res['permList'] = ModelService.own_permission(userID)
                            res['userID'] = userID
                            # 昵称，邮箱，电话，刷新，头像
                            userIconPath = str(users['userIconPath'])
                            if userIconPath and userIconPath.find('static/') != -1:
                                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                                res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
                            else:
                                res['userIconUrl'] = ''
                            res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
                            res['username'] = users['username'] if users['username'] is not None else ''
                            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
                            res['phone'] = users['phone'] if users['phone'] is not None else ''
                            res['fingerprint_enable'] = users['fingerprint_enable']
                            res['fingerprint_key'] = CommonService.encode_data(content=users['fingerprint_key'],
                                                                               start=2)
                            return response.json(0, res)
                        else:
                            return response.json(tko.code)
        else:
            return response.json(444)


class v3SetFingerprintView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(v3SetFingerprintView, self).dispatch(*args, **kwargs)

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

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

    def validate(self, request_dict):
        lang = request_dict.get('lang', None)
        token = request_dict.get('token', None)
        fingerprint_enable = request_dict.get('fingerprint_enable', None)
        fingerprint_key = request_dict.get('fingerprint_key', None)

        response = ResponseObject()

        token = TokenObject(token)
        if token.code != 0:
            return response.json(token.code)

        if not lang:
            return response.json(444, 'lang')

        response.lang = lang

        data = {}

        if fingerprint_enable:
            data['fingerprint_enable'] = int(fingerprint_enable)

        if fingerprint_key:
            data['fingerprint_key'] = CommonService.decode_data(fingerprint_key, end=3)

        if len(data) > 0:
            Device_User.objects.filter(userID=token.userID).update(**data)
        return response.json(0)


class AppleAuthLogin(View):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        lang = request_dict.get('lang', None)
        identity_token = request_dict.get('identity_token', None)
        app_bundle_id = request_dict.get('app_bundle_id', None)  # 包名
        token_val = request_dict.get('tokenVal', None)  # 包名
        token_version = request_dict.get('tokenVersion', None)  # 包名

        response = ResponseObject(lang)
        identity_token = CommonService.decode_data(identity_token)
        # print(identity_token)
        if identity_token:
            key_url = 'https://appleid.apple.com/auth/keys'
            key_response = requests.get(key_url).json()
            # print(key_response)
            head = jwt.get_unverified_header(identity_token)
            # print(head)
            token_key = head['kid']
            key_object = None
            alg = None
            for pub_key in key_response['keys']:
                if pub_key['kid'] == token_key:
                    key_object = simplejson.dumps(pub_key)
                    key_object = RSAAlgorithm.from_jwk(key_object)
                    alg = pub_key['alg']
                    break

            if key_object:
                try:
                    claims = jwt.decode(identity_token, key=key_object, verify=True, algorithms=[alg],
                                        audience=app_bundle_id)
                    unionID = claims['sub']
                    print(claims)
                    user_extend_qs = UserOauth2Model.objects.filter(unionID=unionID, authType=2)
                    if user_extend_qs.exists():
                        # 如果用户绑定过则直接登录
                        userID = user_extend_qs[0].userID_id
                        print(userID)
                        user_qs = Device_User.objects.filter(userID=userID)
                        return self.do_login(user_qs, app_bundle_id, response)
                    else:
                        # 如果用户为绑定过则创建用户并进行登录返回token
                        userID = CommonService.getUserID(getUser=False)
                        if claims.__contains__('email'):
                            nickname = claims['email']
                        else:
                            nickname = 'apple_{num}'.format(num=CommonService.RandomStr(6, False))
                        return self.do_register(userID, nickname, response, app_bundle_id, token_val, token_version,
                                                unionID)

                except Exception as e:
                    print(e)
                    return response.json(717)
            else:
                return response.json(444)
        else:
            return response.json(444)

    # 登录
    def do_login(self, user_qs, app_bundle_id, token_val, token_version, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        new_bundle = APP_MAPPING.get(app_bundle_id, None)
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"],
                                 'appBundleId': new_bundle, 'tokenVal': token_val, 'tokenVersion': token_version})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        # 添加用户登录类型
        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
        auth_type = 0
        if oauth_qs.exists():
            auth_type = oauth_qs[0].authType
        res['authType'] = auth_type

        user_qs.update(last_login=now_time, online=True)
        return response.json(0, res)

    def do_register(self, userID, nickname, response, appBundleId, token_val, token_version, unionID):
        data_valid = DataValid()
        if data_valid.name_validate(userID) is not True:
            return response.json(105)
        try:
            users = Device_User.objects.create(
                username=userID,
                NickName=nickname,
                password=make_password('123456'),
                userID=userID,
                is_active=True,
                user_isValid=True,
            )

            nowTime = int(time.time())
            UserOauth2Model.objects.create(
                addTime=nowTime,
                updTime=nowTime,
                userID_id=users.userID,
                authType=2,
                unionID=unionID
            )
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            user_qs = Device_User.objects.filter(Q(userID=userID))
            print('---')
            print(user_qs)
            return self.do_login(user_qs, appBundleId, token_val, token_version, response)


class LocalUserView(View):

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        operation = kwargs.get('operation', None)
        print('start_time=' + str((time.time())))
        CommonService.get_ip_address(request)
        print('end_time=' + str((time.time())))
        return self.validate(request_dict, operation)

    def validate(self, request_dict, operation):
        language = request_dict.get('lang', None)
        response = ResponseObject(lang=language)
        if operation == 'login':
            return self.do_local_login(request_dict, response)
        else:
            return response.json(404)

    def do_local_login(self, request_dict, response):
        username = request_dict.get('username', None)
        app_bundle_id = request_dict.get('app_bundle_id', None)

        if username is None:
            return response.json(444)

        user_qs = Device_User.objects.filter(username=username)
        if user_qs.exists():
            return self.do_login(user_qs, response)
        else:
            # 如果用户为绑定过则创建用户并进行登录返回token
            userID = CommonService.getUserID(μs=False, setOTAID=True)
            nickname = 'local_{num}'.format(num=CommonService.RandomStr(6, False))
            return self.do_register(userID, username, nickname, response, app_bundle_id)

    # 登录
    def do_login(self, user_qs, response):
        now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
        userID = user_qs[0].userID
        print('userID' + userID)
        tko = TokenObject()
        user_list = user_qs.values("NickName", "userIconUrl", "userIconPath", "username", "userEmail", "phone")
        res = tko.generate(data={'userID': userID, 'lang': response.lang, 'user': user_list[0]["username"]})
        # 增加角色
        user_qs[0].role.add(Role.objects.get(rid=1))
        role_dict = ModelService.own_role(userID=userID)
        res['rid'] = role_dict['rid']
        res['roleName'] = role_dict['roleName']
        res['permList'] = ModelService.own_permission(userID)
        res['userID'] = userID
        # 昵称，邮箱，电话，刷新，头像
        userIconPath = str(user_list[0]["userIconPath"])
        if userIconPath and userIconPath.find('static/') != -1:
            userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
            res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        else:
            res['userIconUrl'] = ''
        res['NickName'] = user_list[0]["NickName"] if user_list[0]["NickName"] is not None else ''
        res['username'] = user_list[0]["username"] if user_list[0]["username"] is not None else ''
        res['userEmail'] = user_list[0]["userEmail"] if user_list[0]["userEmail"] is not None else ''
        res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
        print(res)
        # 添加用户登录类型
        oauth_qs = UserOauth2Model.objects.filter(userID__userID=userID)
        auth_type = 0
        if oauth_qs.exists():
            auth_type = oauth_qs[0].authType
        res['authType'] = auth_type
        user_qs.update(last_login=now_time, online=True)
        return response.json(0, res)

    def do_register(self, userID, username, nickname, response, appBundleId):
        data_valid = DataValid()
        if data_valid.name_validate(userID) is not True:
            return response.json(105)
        try:
            Device_User.objects.create(
                username=username,
                NickName=nickname,
                password=make_password('123456'),
                userID=userID,
                is_active=True,
                user_isValid=True,
                is_local=True
            )

        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, repr(e))
        else:
            user_qs = Device_User.objects.filter(Q(userID=userID))
            print('---')
            print(user_qs)
            return self.do_login(user_qs, response)


class SubscribeEmailView(View):

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

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

    def validate(self, request_dict):
        token = request_dict.get('token', None)
        lang = request_dict.get('lang', None)
        token = TokenObject(token)

        response = ResponseObject(lang=lang)
        if token.code != 0:
            return response.json(token.code)

        status = request_dict.get('subscribe', None)
        if status is None:
            return response.json(444)

        status = int(status)
        user_qs = Device_User.objects.filter(userID=token.userID)
        if user_qs.exists():
            user_qs.update(subscribe_email=status)
            return response.json(0)
        else:
            return response.json(104)


def delete_local_account(username):
    user_qs = Device_User.objects.filter(username=username)
    print(user_qs)
    if user_qs.exists():
        user = user_qs[0]
        if user.is_local:
            user.delete()
            Device_Info.objects.filter(userID__userID=user.userID).delete()


def updateUserCountry(request):
    country_ip_qs = CountryIPModel.objects.filter(status=0)[0: 100]
    if country_ip_qs.exists():
        country_ip_qs = country_ip_qs.values()
        redisObject = RedisObject(db=6)
        for country_ip in country_ip_qs:
            key = 'ip_country_{ip}'.format(ip=country_ip['ip'])
            data = redisObject.get_data(key=key)
            if data:
                country = data
            else:
                country = CommonService.getIpIpInfo(country_ip['ip'], lang='CN')
                country = country['country_name']
                redisObject.set_data(key=key, val=country, expire=3600)

            country_ip['country'] = country
            CountryIPModel.objects.filter(id=country_ip['id']).update(country=country, status=1)
            # ids.append(country_ip['id'])
        # CountryIPModel.objects.filter(id__in=tuple(ids)).update(status=1)
    response = ResponseObject()
    return response.json(0)


def confirmRegion(request):
    response = ResponseObject()
    request.encoding = 'utf-8'
    # test
    number = request.POST.get('number', None)
    if number is None:
        return response.json(309)
    number = request.POST.get('number', None)
    selectRegion = CountryModel.objects.filter(number=number).values('region__api')
    if not selectRegion.exists():
        return response.json(0, {"request_url": "https://www.dvema.com"})
    else:
        return response.json(0, {"request_url": selectRegion[0]['region__api']})


def deleteAccount(request):
    # test
    lang = request.POST.get('lang', None)
    token = request.POST.get('token', None)
    password = request.POST.get('userPwd', None)
    salt = request.POST.get('salt', None)
    iterations = request.POST.get('iterations', None)
    password_version = request.POST.get('pwdVersion', 'V1')
    response = ResponseObject(lang=lang) if lang else ResponseObject()
    request.encoding = 'utf-8'

    try:
        if password_version == 'V1':
            for i in range(1, 4):
                if i == 1:
                    # 第一次先解密
                    password = base64.b64decode(password)
                    password = password.decode('utf-8')
                    # 截去第一位，最后一位
                    password = password[1:-1]
                if i == 2:
                    # 第2次先解密
                    password = base64.b64decode(password)
                    password = password.decode('utf-8')
                    # 去前2位，后2位
                    password = password[2:-2]
                if i == 3:
                    # 第3次先解密
                    password = base64.b64decode(password)
                    password = password.decode('utf-8')
                    # 去前3位，后3位
                    password = password[3:-3]
    except Exception as e:
        print(repr(e))
        return response.json(111)
    else:
        if token is None:
            return response.json(309)
        tko = TokenObject(token)
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if not userID:
            return response.json(309)

        delUser = Device_User.objects.filter(userID=userID)
        if not delUser.exists():
            return response.json(104)

        userPWD = delUser.values('password')[0]
        if password_version == 'V1':
            check_flag = check_password(password, userPWD['password'])
        else:
            if not all([iterations, salt]):
                return response.json(444)
            password = "%s$%d$%s$%s" % ("pbkdf2_sha256", int(iterations), salt, password)
            check_flag = CommonService.check_password(password, userPWD['password'])
        if not check_flag:
            return response.json(111)

        hasDevices = Device_Info.objects.filter(userID=userID)
        if hasDevices.exists():
            return response.json(10047)

        orderUserIds = Order_Model.objects.filter(userID=userID, status=1).values_list('UID').distinct().order_by("UID")
        hadUseSevice = UID_Bucket.objects.filter(uid__in=orderUserIds, use_status=1)
        if hadUseSevice.exists():
            return response.json(10046)

        hadUnUseSevice = Unused_Uid_Meal.objects.filter(uid__in=orderUserIds)
        if hadUnUseSevice.exists():
            return response.json(10046)

        try:
            user_vo = Device_User.objects.filter(userEmail='asjorder@ansjer.com').values('userID')
            Order_Model.objects.filter(userID=userID) \
                .update(userID_id=user_vo[0]['userID'],
                        desc=f'原:{userID},{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
        except Exception as e:
            print(repr(e))

        delUser.delete()
        # 删除云盘记录
        icloud_record = IcloudStorageRecord.objects.filter(user_id=userID).values('bucket_id')
        if icloud_record.exists():
            bucket_id = icloud_record[0]['bucket_id']
            bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold')
            bucket_name = bucket_qs[0]['bucket']
            bucket_region = bucket_qs[0]['region']
            mold = bucket_qs[0]['mold']
            s3_obj = AmazonS3Util(
                AWS_ACCESS_KEY_ID[mold],
                AWS_SECRET_ACCESS_KEY[mold],
                bucket_region
            )
            object_list = s3_obj.get_object_list(bucket_name, userID)
            for obj in object_list:
                s3_obj.delete_obj(bucket_name, obj['Key'])
            icloud_record.delete()
        IcloudUseDetails.objects.filter(user_id=userID).update(use_size=0)
        return response.json(0)


class InitUserInformationView(View):

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

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

    def validate(self, request_dict, operation):
        token = TokenObject(request_dict.get('token', None))

        response = ResponseObject()

        if token.code != 0:
            return response.json(token.code)

        if operation == 'init':
            return self.do_init(token.userID, request_dict, response)
        else:
            return response.json(444)

    def do_init(self, userID, request_dict, response):
        appBundleId = request_dict.get('appBundleId', None)

        if appBundleId:
            user_ex_qs = UserExModel.objects.filter(userID_id=userID)
            now_time = int(time.time())
            if user_ex_qs.exists():
                update = {
                    'appBundleId': appBundleId,
                    'updTime': now_time
                }
                user_ex_qs.update(**update)
            else:

                user_ex = UserExModel(userID_id=userID, appBundleId=appBundleId, addTime=now_time, updTime=now_time)
                user_ex.save()
            return response.json(0)
        else:
            return response.json(444)


class DeleteUser(View):

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

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

    def validate(self, request, request_dict):
        response = ResponseObject('cn')
        try:
            user_id = request_dict.get('userID', None)
            if not user_id:
                return response.json(444)
            Device_User.objects.filter(userID=user_id).delete()
            Device_Info.objects.filter(userID=user_id).delete()
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


def getPasswordSalt(request):
    if request.method == 'GET':
        request_dict = request.GET
    else:
        request_dict = request.POST
    lang = request_dict.get('lang', 'en')
    username = request_dict.get('userName', None)
    token = request_dict.get('token', None)
    response = ResponseObject(lang=lang)
    request.encoding = 'utf-8'
    if token:
        token_obj = TokenObject(token)
        if token_obj.code != 0:
            return response.json(token_obj.code)
        username = token_obj.user
    if not username:
        return response.json(444, 'userName')
    username = username.strip()
    data_valid = DataValid()
    try:
        if data_valid.email_validate(username):
            user_qs = Device_User.objects.filter(Q(username=username) | Q(userEmail=username)).values('password')
        elif data_valid.mobile_validate(username):
            user_qs = Device_User.objects.filter(Q(phone=username) | Q(username=username), is_active=True,
                                                 user_isValid=True).values('password')
        elif data_valid.name_validate(username):
            user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                                 is_active=True, user_isValid=True).values('password')
        else:
            return response.json(104)
        if not user_qs.exists():
            return response.json(104)
        iterations = user_qs[0]['password'].split('$')[1]
        salt = user_qs[0]['password'].split('$')[2]
        return response.json(0, {'iterations': iterations, 'salt': salt})
    except Exception as e:
        return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


class ChangeAccountInfoView(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):
        language = request_dict.get('lang', 'en')
        response = ResponseObject(language)
        if operation == 'verifyCode':
            return self.verify_code(request_dict, response)
        elif operation == 'changePhone':
            return self.change_phone(request_dict, response)
        else:
            return response.json(444)

    @staticmethod
    def verify_code(request_dict, response):
        phone = request_dict.get('phone', None)
        authcode = request_dict.get('authcode', None)
        if phone is None or authcode is None:
            return response.json(444, 'phone, authcode')
        authcode = CommonService.decode_data(authcode.strip())
        if authcode is None:
            return response.json(444, 'authcode')
        reds = RedisObject()
        key = str(phone) + '_ChangePhone'
        reset_code = reds.get_data(key=key)
        if reset_code is False:
            return response.json(90)
        if authcode != reset_code:
            return response.json(121)
        if not reds.del_data(key):
            return response.json(10, '删除缓存失败')
        return response.json(0)

    @staticmethod
    def change_phone(request_dict, response):
        ord_phone = request_dict.get('ord_phone', None)
        new_phone = request_dict.get('new_phone', None)
        authcode = request_dict.get('authcode', None)
        new_user_qs = Device_User.objects.filter(Q(username=new_phone) | Q(phone=new_phone))
        if new_user_qs.exists():
            return response.json(101)

        authcode = CommonService.decode_data(authcode.strip())
        if authcode is None:
            return response.json(444, 'authcode')
        LOGGER.info(f"change_phone, authcode: {authcode}")
        reds = RedisObject()
        key = str(new_phone) + '_ChangePhone'
        reset_code = reds.get_data(key=key)
        if reset_code is False:
            return response.json(90)
        if authcode != reset_code:
            return response.json(121)
        if not reds.del_data(key):
            return response.json(10, '删除缓存失败')

        ord_user_qs = Device_User.objects.filter(Q(username=ord_phone) | Q(phone=ord_phone))
        if not ord_user_qs.exists():
            return response.json(102)
        if ord_user_qs[0].username == ord_phone:
            ord_user_qs.update(phone=new_phone, username=new_phone)
        else:
            ord_user_qs.update(phone=new_phone)
        return response.json(0)
