#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2018/9/11 15:08
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: UserController.py
@Contact: chanjunkai@163.com
"""
import datetime
import traceback
import time
import logging
import jwt
import simplejson
import simplejson as json
import requests
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from django.db.models import Q
from django.http import HttpResponseRedirect
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 jwt.algorithms import RSAAlgorithm
from ratelimit.decorators import ratelimit

from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN
from Controller.CheckUserData import DataValid, date_handler, RandomStr
from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
    UserAppFrequencyModel, CountryIPModel, CountryModel
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 Service.CommonService import CommonService
from Service.ModelService import ModelService
from Service.TemplateService import TemplateService
from django.views.generic import View
import base64
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.shortcuts import HttpResponse
from Ansjer.config import BASE_DIR

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

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

    @ratelimit(key='ip', rate='2/m')
    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)

    # @ratelimit(key='ip', rate='2/m')
    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)
        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)
        else:
            return response.json(800)

    def register(self, username, userEmail, password, authCode, response):
        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 dataValid.password_validate(password):
            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": make_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": make_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:
            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:
                userID = tko.userID
                try:
                    UidPushModel.objects.filter(userID_id=userID, m_code=m_code).delete()
                except Exception as e:
                    pass
                else:
                    pass
            return response.json(0)
        else:
            return response.json(tko.code)


# 修改密码
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)
        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)

    def updatePwd(self, userID, oldPwd, newPwd, response):
        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        c_p = check_password(oldPwd, user_qs[0].password)
        # 密码是否正确
        if not c_p:
            return response.json(111)
        update = user_qs.update(password=make_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)
        response = ResponseObject()
        # 解密
        try:
            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]
        except Exception as e:
            return response.json(111)
        else:
            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)

    def updatePwd(self, userID, oldPwd, newPwd, response):
        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        c_p = check_password(oldPwd, user_qs[0].password)
        # 密码是否正确
        if not c_p:
            return response.json(111)
        update = user_qs.update(password=make_password(newPwd))
        if update:
            return response.json(0)
        else:
            return response.json(177)


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

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

    @ratelimit(key='ip', rate='1/m')
    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)

    @ratelimit(key='ip', rate='1/m')
    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):
        # return response.json(475)
        if userName != 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.dvema.com/web/html/paw_update_success.html?code=" + reset_pwd)
                    else:
                        return response.json(10)
                else:
                    return response.json(104)
            else:
                return HttpResponseRedirect('http://www.dvema.com/web/html/paw_update_unsuccessful.html?lang=en')
        else:
            return HttpResponseRedirect('http://www.dvema.com/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:
                    pass
                # # #
                return response.json(0, res)
            else:
                return response.json(tko.code)
        else:
            return response.json(444, 'token')


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

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

    @ratelimit(key='ip', rate='2/m')
    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)

    @ratelimit(key='ip', rate='2/m')
    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()
            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=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 + '_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.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 + '_identifyingCode', 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) + '_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()
        if sign_name == 'zosi':
            sign_ms = '周视'
        else:
            sign_ms = 'Ansjer'
        res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name=sign_ms,
                                   temp_msg='SMS_151600991')
        print(res)
        if res["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:
            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) + '_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)
        # 短信签名
        # sign_name_dict = {
        #     'ansjer':'Ansjer',
        #     'zosi':'周视'
        # }
        sign_ms = ''
        if country_code == '86':
            # 国内短信推送模板
            temp_msg = 'SMS_151600991'
            rec_phone = phone
            if sign_name == 'zosi':
                sign_ms = '周视'
            else:
                sign_ms = 'Ansjer'
        else:
            # 国际短信推送模板
            temp_msg = 'SMS_172165867'
            rec_phone = country_code + phone
            sign_ms = 'Ansjer'

        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=rec_phone, code=identifyingCode, sign_name=sign_ms,
                                   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)
        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)
        elif email is not None:
            return self.do_email_register(email, password, authcode, number, response)
        else:
            return response.json(444, 'phone or email')

    def do_phone_register(self, phone, password, authcode, number, response):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if data_valid.password_validate(password) 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": make_password(password),
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number

            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 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):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if data_valid.password_validate(password) 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": make_password(password),
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number
            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 not reds.del_data(key=email + '_identifyingCode'):
                return response.json(10, '删除缓存验证码错误')
            return self.do_login(email_qs, response)


# 验证码注册v3
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):
        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)

        if unique:
            delete_local_account(unique)
        response = ResponseObject(lang)
        # 解密
        try:
            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:
            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]
            print(authcode)
        except Exception as e:
            return response.json(121)
        else:
            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)
            elif email is not None:
                return self.do_email_register(email, password, authcode, number, response)
            else:
                return response.json(444, 'phone or email')

    def do_phone_register(self, phone, password, authcode, number, response):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if data_valid.password_validate(password) 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": make_password(password),
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number

            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 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, response):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if data_valid.password_validate(password) 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": make_password(password),
                "userID": CommonService.getUserID(μs=False, setOTAID=True),
                "is_active": True,
                "user_isValid": True,
            }
            if number:
                create_data["region_country"] = number
            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 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)

    @ratelimit(key='ip', rate='1/m')
    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)

    @ratelimit(key='ip', rate='1/m')
    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)
        if phone is not None:
            phone = phone.strip()
            if country_code is None:
                return self.do_send_phone_code(phone, response, sign_name)
            else:
                return self.do_v2_send_phone_code(country_code, phone, response, sign_name)
        elif email is not None:
            return self.do_send_email_code(email, response)
        else:
            return response.json(444, 'phone')

    def do_send_phone_code(self, phone, response, sign_name):
        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)
        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)
        if sign_name == 'zosi':
            sign_ms = '周视'
        else:
            sign_ms = 'Ansjer'
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=phone, code=resetCode, sign_name=sign_ms,
                                   temp_msg='SMS_151675019')
        if res["Code"] == "OK":
            if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                return response.json(10, '生成缓存错误')
            return response.json(0)
        else:
            return response.json(10, res["Message"])

    def do_v2_send_phone_code(self, country_code, phone, response, sign_name):
        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)
        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'
            if sign_name == 'zosi':
                sign_ms = '周视'
            else:
                sign_ms = 'Ansjer'
        else:
            temp_msg = 'SMS_172200051'
            rec_phone = str(country_code) + str(phone)
            sign_ms = 'Ansjer'

        res = aliSms.send_code_sms(phone=rec_phone, code=resetCode, sign_name=sign_ms,
                                   temp_msg=temp_msg)
        if res["Code"] == "OK":
            if not reds.set_data(key=reds_key, val=resetCode, expire=300):
                return response.json(10, '生成缓存错误')
            return response.json(0)
        else:
            return response.json(10, res["Message"])

    def do_send_email_code(self, email, response):
        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)
        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()

        # send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
        # 阿里云发送邮箱
        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')
            return response.json(44)
        return response.json(0)


# 忘记密码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)
        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)
        elif email is not None:
            email = email.strip()
            return self.do_email_pwd_reset(email, authcode, password, response)
        else:
            return response.json(444, 'phone')

    def do_email_pwd_reset(self, email, authcode, password, response):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if data_valid.password_validate(password) 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=make_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):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if data_valid.password_validate(password) 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=make_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)
        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:
            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:
            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]
            print(authcode)
        except Exception as e:
            return response.json(121)
        if phone is not None:
            phone = phone.strip()
            return self.do_phone_pwd_reset(phone, authcode, password, response)
        elif email is not None:
            email = email.strip()
            return self.do_email_pwd_reset(email, authcode, password, response)
        else:
            return response.json(444, 'phone')

    def do_email_pwd_reset(self, email, authcode, password, response):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if data_valid.password_validate(password) 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=make_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):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if data_valid.password_validate(password) 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=make_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)

    @ratelimit(key='ip', rate='5/m')
    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)

    # @ratelimit(key='ip', rate='5/m')
    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)
        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)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, password, response)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, password, response)
        else:
            return response.json(107)

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

    def do_phone_login(self, phone, password, 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, password, response)

    def do_name_login(self, username, password, 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, password, response)

    def valid_login(self, user_qs, password, 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]
        if not check_password(password, users['password']):
            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)
            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)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        # chong
        return super(v3LoginView, self).dispatch(*args, **kwargs)

    @ratelimit(key='ip', rate='5/m')
    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)

    # @ratelimit(key='ip', rate='5/m')
    def get(self, request, *args, **kwargs):
        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)
        subscribe = request_dict.get('subscribe', None)
        if not username or not password:
            return response.json(111)
        username = username.strip()
        password = password.strip()
        print("准备解密")
        # 解密
        try:
            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:
            return response.json(111)
        else:
            data_valid = DataValid()
            if data_valid.email_validate(username):
                return self.do_email_login(username, password, response, subscribe)
            elif data_valid.mobile_validate(username):
                return self.do_phone_login(username, password, response, subscribe)
            elif data_valid.name_validate(username):
                return self.do_name_login(username, password, response, subscribe)
            else:
                return response.json(107)

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

    def do_phone_login(self, phone, password, response, subscribe):
        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)

    def do_name_login(self, username, password, response, subscribe):
        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)

    def valid_login(self, user_qs, password, response, subscribe):
        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]
        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')[0]
        if not check_password(password, users['password']):
            return response.json(111)
        userID = users['userID']
        tko = TokenObject()
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'm_code': '123413243214'})
        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['fingerprint_enable'] = users['fingerprint_enable']
            # res['fingerprint_key'] = CommonService.encode_data(content=users['fingerprint_key'], start=2)
            res['authType'] = auth_type
            res['subscribe_email'] = users['subscribe_email'] if users['subscribe_email'] is not None else ''
            return response.json(0, res)
        else:
            return response.json(tko.code)


# 用户登录后初始化接口
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)
        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 all([token_val, push_type, appBundleId, userID]):
            push_type = int(push_type)
            if push_type == 0:
                if appBundleId not in APNS_CONFIG.keys():
                    return response.json(904)
            elif push_type == 1:
                if appBundleId not in FCM_CONFIG.keys():
                    return response.json(904)
            elif push_type == 2:
                if appBundleId not in JPUSH_CONFIG.keys():
                    return response.json(904)
            else:
                return response.json(444, 'push_type')
            if m_code:
                # 获取设备推送状态
                update_dict = {
                    'token_val': token_val,
                    'push_type': push_type,
                    'tz': tz,
                }
                # 更新当前用户推送设备状态
                UidPushModel.objects.filter(userID_id=userID, m_code=m_code). \
                    update(**update_dict)
            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
                    }
                    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()
        # 获取设备是否存在有已被删除
        res = {'usmsg': 0}  # 预留字段， 有版本app该字段去掉会报错
        return response.json(0, res)

    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)  # 包名
        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, response)
                    else:
                        # 如果用户为绑定过则创建用户并进行登录返回token
                        userID = CommonService.getUserID(getUser=False)
                        nickname = res_json['nickname'] + '_' + CommonService.RandomStr(4)
                        return self.do_register(userID, nickname, response, appBundleID, 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, 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, nickname, response, appBundleId, 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, 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()
                    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_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)

    @ratelimit(key='ip', rate='2/m')
    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)

    @ratelimit(key='ip', rate='2/m')
    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()
            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()
        if sign_name == 'zosi':
            sign_ms = '周视'
        else:
            sign_ms = 'Ansjer'
        res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name=sign_ms,
                                   temp_msg='SMS_151600991')
        print(res)
        if res["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:
            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)
        # 短信签名
        # sign_name_dict = {
        #     'ansjer':'Ansjer',
        #     'zosi':'周视'
        # }
        sign_ms = ''
        if country_code == '86':
            # 国内短信推送模板
            temp_msg = 'SMS_151600991'
            rec_phone = phone
            if sign_name == 'zosi':
                sign_ms = '周视'
            else:
                sign_ms = 'Ansjer'
        else:
            # 国际短信推送模板
            temp_msg = 'SMS_172165867'
            rec_phone = country_code + phone
            sign_ms = 'Ansjer'

        # 发送手机验证码
        aliSms = AliSmsObject()
        res = aliSms.send_code_sms(phone=rec_phone, code=identifyingCode, sign_name=sign_ms,
                                   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 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)
        authcode = request_dict.get('authcode', None)
        token = request_dict.get('token', None)
        token = request_dict.get('token')
        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)
        elif email is not None:
            email = email.strip()
            return self.do_email(tko, email, authcode, password, response)
        else:
            return response.json(444, 'phone')

    def do_email(self, tko, email, authcode, password, response):
        data_valid = DataValid()
        if data_valid.email_validate(email) is not True:
            return response.json(105)
        if data_valid.password_validate(password) 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=make_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):
        data_valid = DataValid()
        if data_valid.mobile_validate(phone) is not True:
            return response.json(100)
        if data_valid.password_validate(password) 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=make_password(password))
        if not reds.del_data(str(phone) + '_OauthPerfect'):
            return response.json(10, '删除缓存失败')
        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)
        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)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, password, response)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, password, response)
        else:
            return response.json(107)

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

    def do_phone_login(self, phone, password, 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, password, response)

    def do_name_login(self, username, password, 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, password, response)

    def valid_login(self, user_qs, password, response):
        if not user_qs.exists():
            return response.json(104)
        users = user_qs.values('userID', 'password')[0]
        if not check_password(password, users['password']):
            return response.json(111)
        userID = users['userID']
        # uid_qs = Device_Info.objects.filter(userID_id=userID, isExist=1).values('UID', 'NickName', 'View_Password')
        # uid_arr = []
        # for uid_q in uid_qs:
        #     uid_arr.append({'uid': uid_q['UID'], 'nick': uid_q['NickName'], 'password': uid_q['View_Password']})
        res = {
            'userID': userID,
            #     'uid_arr': uid_arr
        }
        return response.json(0, res)
        # return response.json(0, res)


class alexaUidView(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 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')
        if not uid_qs.exists():
            return response.json(107)

        uid_dict = {}
        uid_list = []
        for uid_q in uid_qs:
            # 追加
            uid_list.append(uid_q['UID'])
            # 给uid_q['UID']赋值
            uid_dict[uid_q['UID']] = {'nick': uid_q['NickName'], 'password': uid_q['View_Password']}

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


# 登出
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:
                    pass
                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)


# 图片验证码校验注册
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):
        print("__________request_dict:%s" % request_dict)
        userEmail = request_dict.get('userEmail', None)
        password = request_dict.get('userPwd', None)
        lang = request_dict.get('lang', None)
        # 前端传进来的uuid
        imageCodeId = request_dict.get('imageCodeId', None)
        # 页面输入的验证码
        response = ResponseObject(lang)
        valid_code = request_dict.get('id_v_code', None)
        unique = request_dict.get('unique', None)
        number = request_dict.get('number', None)
        if unique:
            delete_local_account(unique)
        if not all([userEmail, password, lang, imageCodeId, valid_code]):
            return response.json(444)
        try:
            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%s" % password)
        except Exception as 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]
            print("valid_code:%s" % valid_code)
        except Exception as 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)
        # 根据uuid拼接的key
        image_code_key = "image_code_%s" % imageCodeId
        # 判断验证码是否过期
        if image_code_key is None:
            return response.json(120)
        redisObj = RedisObject(db=6)
        # redis里面的验证码
        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)
        # #存用户名和密码
        create_data = {
            "username": username,
            "NickName": username,
            "userEmail": userEmail,
            "password": make_password(password),
            "userID": CommonService.getUserID(μs=False, setOTAID=True),
            "is_active": True,
            "user_isValid": True,
        }
        if number:
            create_data["region_country"] = number
        users = Device_User.objects.create(**create_data)
        return self.do_login(email_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)


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)

    @ratelimit(key='ip', rate='2/m')
    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)

    @ratelimit(key='ip', rate='2/m')
    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)
        country_code = 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()
                if sign_name == 'zosi':
                    sign_sms = '周视'
                else:
                    sign_sms = 'Ansjer'

                res = aliSms.send_code_sms(phone=phone, code=login_code, sign_name=sign_sms, 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)
        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, response)
                else:
                    return response.json(121)
            else:
                return response.json(120)

    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 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'})
        # 添加用户登录类型
        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)  # 包名

        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, 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, 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, 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, nickname, response, appBundleId, 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, 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())))
        ip = 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('language', 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)


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)