import datetime
import time
from concurrent.futures import ThreadPoolExecutor

import oss2
import requests
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
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 AgentModel.models import AgentCustomerInfo, AgentCustomerCard, AgentCloudServicePackage, AgentCustomerPackage
from Ansjer.config import SERVER_DOMAIN, OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, \
    AWS_SECRET_ACCESS_KEY, AWS_SES_ACCESS_REGION, DETECT_PUSH_DOMAINS
from Controller.CheckUserData import DataValid, RandomStr
from Model.models import Device_User, Role, UserExModel, CountryModel, MenuModel, FeedBackModel, StatResModel, \
    SysMassModel, App_Info, SysMsgModel, DeviceSuperPassword, CustomizedPush, DeviceTypeModel, CustomCustomerOrderInfo
from Object.AWS.AmazonS3Util import AmazonS3Util
from Object.ApschedulerObject import ApschedulerObject
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 django.views.generic import View


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

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

        return self.validates(request_dict, response)

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

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

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

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

    def valid_login(self, user_qs, password, response, password_version):
        if not user_qs.exists():
            return response.json(104)
        # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
        #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath')[0]
        if password_version == 'V1':
            check_flag = check_password(password, users['password'])
        else:
            check_flag = CommonService.check_password(password, users['password'])
        if not check_flag:
            return response.json(111)
        userID = users['userID']
        tko = TokenObject(returntpye='pc')
        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 GetPermissions(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(GetPermissions, self).dispatch(*args, **kwargs)

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

    def validates(self, request_dict, token, response):
        tko = TokenObject(token, returntpye='pc')
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID

        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        # 待补充逻辑
        username = user_qs[0].username
        userIconPath = user_qs[0].userIconPath.url
        if userIconPath:
            if userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath

        role_qs = Role.objects.filter(device_user=userID)
        menu_qs = MenuModel.objects.filter(role__in=role_qs, menutype=2);
        perms = []
        for menu in menu_qs:
            perms.append(menu.menu_code)
        res = {
            "code": 200,
            "msg": "success",
            "data": {
                "roles": ["admin"],  # 一个用户可包含多个角色如["admin","editor","XXXX"]，必须返回，如小项目用不到角色权限请返回 ["admin"]
                "ability": ["READ", "WRITE", "DELETE"],  # 如果用不到rabc精细化权限可以不返回，建议返回
                "username": username,  # 用户名，必须返回
                "avatar": userIconUrl,  # 头像，必须返回
                "perms": perms
            }
        }
        return response.json(0, res)


# 获取菜单
class GetList(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(GetList, self).dispatch(*args, **kwargs)

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

    def validates(self, request_dict, token, response):
        tko = TokenObject(token, returntpye='pc')
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID

        role_qs = Role.objects.filter(device_user=userID)
        menu_qs = MenuModel.objects.filter(parentId=0, role__in=role_qs, menutype=1);
        list = []

        for menu in menu_qs:
            list.append(
                {
                    'id': menu.id,
                    'parentId': menu.parentId,
                    'path': menu.path,
                    'name': menu.name,
                    'component': menu.component,
                    'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg': menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable': menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot': menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
            )
        menu_qs = MenuModel.objects.filter(role__in=role_qs, menutype=1)
        menulist = []
        for objlist in list:
            menulist.append(self.menulist(menu_qs, objlist))
        return response.json(0, {'list': menulist})

    def menulist(self, menu_qs, objlist):
        if objlist is None:
            return
        for menu in menu_qs:
            if objlist['id'] == menu.parentId:
                if 'children' not in objlist:
                    objlist['children'] = []

                obj = {
                    'id': menu.id,
                    'parentId': menu.parentId,
                    'path': menu.path,
                    'name': menu.name,
                    'component': menu.component,
                    'menutype': menu.menutype,
                    'menu_code': menu.menu_code,
                    'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg': menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable': menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot': menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
                objlist['children'].append(
                    obj
                )
                self.menulist(menu_qs, obj)

        return objlist


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

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

    def validation(self, request_dict, request, operation):
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        if operation == 'sendSysMessage':
            return self.sendSysMessage(request_dict, response)
        elif operation == 'getAppDataList':
            return self.getAppDataList(request_dict, response)
        elif operation == 'replyFeedBack':
            return self.replyFeedBack(request_dict, response)
        elif operation == 'sendSysMsgToUser':
            return self.sendSysMsgToUser(request_dict, response)
        elif operation == 'getCountryList':  # 查询国家列表
            return self.getCountryList(response)
        elif operation == 'getDeviceTypeList':  # 查询设备型号列表
            return self.getDeviceTypeList(response)
        else:
            tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'), returntpye='pc')
            # if tko.code != 0:
            #     return response.json(tko.code)
            response.lang = tko.lang
            userID = tko.userID
            if operation == 'getUserInfo':
                return self.getUserInfo(userID, request_dict, response)
            elif operation == 'AddOrEditAccount':
                return self.AddOrEditAccount(userID, request_dict, response)
            elif operation == 'doDelete':
                return self.doDelete(request_dict, response)
            elif operation == 'resetPassword':
                return self.resetPassword(request_dict, response)
            elif operation == 'getFeedbackList':
                return self.getFeedbackList(request_dict, response)
            elif operation == 'deleteFeedBack':
                return self.deleteFeedBack(request_dict, response)
            elif operation == 'getSysMessageList':
                return self.getSysMessageList(request_dict, response)
            elif operation == 'collectFeedBack':
                return self.collectFeedBack(request_dict, response)
            elif operation == 'exportFeedBack':
                return self.exportFeedBack(request_dict, response)
            elif operation == 'customerServiceManagement':  # 审核用户请求/生成超级密码
                return self.customerServiceManagement(request_dict, response)
            elif operation == 'getDeviceSuperPassword':  # 查询超级密码请求表
                return self.getDeviceSuperPassword(request_dict, response)
            elif operation == 'deleteInformation':  # 删除超级密码请求表
                return self.deleteInformation(request_dict, response)
            # 定制推送
            elif operation == 'getCustomizedPushList':  # 查询定制推送列表
                return self.getCustomizedPushList(request_dict, response)
            elif operation == 'addOrEditCustomizedPush':  # 新增/编辑推送内容
                return self.addOrEditCustomizedPush(request, request_dict, response)
            elif operation == 'delCustomizedPush':  # 删除定制推送
                return self.delCustomizedPush(request_dict, response)
            if operation == 'getCustomCustomerList':  # 查詢定制客户信息
                return self.get_custom_customer_list(request_dict, response)
            elif operation == 'addCustomCustomer':  # 添加定制客户信息接口
                return self.add_custom_customer(request_dict, response)
            elif operation == 'delCustomCustomer':  # 查询定制客户设备列表
                return self.del_custom_customer(request_dict, response)
            else:
                return response.json(414)

    def getUserInfo(self, userID, request_dict, response):
        """
        @param userID:用户ID
        @param request_dict:请求参数
        @param response:响应对象
        @param username:用户名
        @param NickName:用户昵称
        @param phone:电话号
        @param userEmail:用户邮箱
        @return:
        """
        print('request_dict: ', request_dict)
        user_id = request_dict.get('userId', '').strip()
        username = request_dict.get('username', '').strip()  # 移除字符串头尾的空格
        NickName = request_dict.get('NickName', '').strip()
        phone = request_dict.get('phone', '').strip()
        userEmail = request_dict.get('userEmail', '').strip()
        countryName = request_dict.get('countryName', '').strip()
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)

        try:
            device_user_qs = Device_User.objects.all()
            # 条件查询
            if user_id:
                device_user_qs = device_user_qs.filter(userID=user_id)
            if username:
                device_user_qs = device_user_qs.filter(username__icontains=username)
            if NickName:
                device_user_qs = device_user_qs.filter(NickName__icontains=NickName)
            if phone:
                device_user_qs = device_user_qs.filter(phone__icontains=phone)
            if userEmail:
                device_user_qs = device_user_qs.filter(userEmail__icontains=userEmail)
            if countryName:
                country_qs = CountryModel.objects.filter(country_name=countryName).values('id')
                if not country_qs:
                    return response.json(10, '国家不存在')
                device_user_qs = device_user_qs.filter(region_country=country_qs[0]['id'])
            if not device_user_qs.exists():
                return response.json(0)
            total = device_user_qs.count()
            device_users = device_user_qs[(page - 1) * line:page * line]

            user_list = []
            for device_user in device_users:
                role = device_user.role.first()
                rid = role.rid if role else 1  # 不存在角色默认分配为'Users'
                user_ex_qs = UserExModel.objects.filter(userID_id=device_user.userID).values('appBundleId')
                app_bundle_id = user_ex_qs[0]['appBundleId'] if user_ex_qs.exists() else ''
                country_qs = CountryModel.objects.filter(id=device_user.region_country).values('country_name')
                countryName = country_qs[0]['country_name'] if country_qs.exists() else '未知国家'
                user_list.append({
                    'userID': device_user.userID,
                    'username': device_user.username,
                    'NickName': device_user.NickName,
                    'role': Role.objects.get(rid=rid).roleName,
                    'phone': device_user.phone,
                    'userEmail': device_user.userEmail,
                    'data_joined': device_user.data_joined.strftime("%Y-%m-%d %H:%M:%S"),
                    'last_login': device_user.last_login.strftime("%Y-%m-%d %H:%M:%S"),
                    'appBundleId': app_bundle_id,
                    'countryName': countryName
                })
            print('user_list: ', user_list)
            return response.json(0, {'list': user_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def AddOrEditAccount(self, userID, request_dict, response):
        """
        添加/编辑用户
        @param userID:用户ID
        @param request_dict:请求参数
        @param response:响应对象
        @param roleName:用户角色
        @param isEdit:添加用户需要输入密码
        @return:
        """
        print('request_dict: ', request_dict)
        username = request_dict.get('username', '').strip()  # 移除字符串头尾的空格
        userEmail = request_dict.get('userEmail', '').strip()
        roleName = request_dict.get('role', None)
        password = request_dict.get('password', None)
        isEdit = request_dict.get('isEdit', None)
        password_version = request_dict.get('pwdVersion', 'V1')

        # 添加代理商字段
        isAgent = request_dict.get('isAgent', None)  
        agent_company_name = request_dict.get('agent_company_name', None)
        card_name = request_dict.get('card_name', None)
        card_no = request_dict.get('card_no', "")
        card_address = request_dict.get('card_address', "")
        phone = request_dict.get('phone', "")

        # 校验用户名,邮箱,密码是否符合规则
        dataValid = DataValid()
        if not username or not dataValid.name_validate(username):
            return response.json(444, {'Parameter error': 'username'})
        if userEmail and not dataValid.email_validate(userEmail):
            return response.json(444, {'Parameter error': 'userEmail'})
        if not isEdit:  # 添加用户需要输入密码
            if not password or not dataValid.password_validate(password):
                return response.json(444, {'Parameter error': 'password'})
        if password_version == 'V1':
            password = make_password(password)
        try:
            if isEdit:  # 编辑用户信息
                userID = request_dict.get('userID')
                user_data = {
                    "username": username,
                    "NickName": username,
                    "userEmail": userEmail,
                }
                device_user_qs = Device_User.objects.filter(userID=userID)
                device_user_qs.update(**user_data)

                # 如果角色改变,修改用户角色
                device_user_role = device_user_qs[0].role
                user_role = device_user_role.first()
                if not user_role or roleName != user_role.roleName:
                    device_user_role.clear()
                    role_qs = Role.objects.filter(roleName=roleName)  # 账号角色
                    device_user_qs[0].role.set(role_qs)
            else:  # 添加用户
                if isAgent and not all([agent_company_name, card_name, phone]):
                    return response.json(444)
                # 查询邮箱是否已注册
                if Device_User.objects.filter(userEmail=userEmail).exists():
                    return response.json(103)
                role_qs = Role.objects.filter(roleName=roleName)  # 账号角色
                # 创建用户
                new_userID = CommonService.getUserID(μs=False, setOTAID=True)
                user_data = {
                    "username": username,
                    "NickName": username,
                    "userEmail": userEmail,
                    "password": password,
                    "userID": new_userID,
                    "phone": phone,
                    "is_active": True,
                    "user_isValid": True,
                }
                Device_User.objects.create(**user_data).role.set(role_qs)
                if isAgent:
                    agent_customer_info = AgentCustomerInfo.objects.create(user_id=new_userID, company_name=agent_company_name, status=1, created_time=int(time.time()),
                                                     updated_time=int(time.time()), created_by=userID, updated_by=userID)
                    AgentCustomerCard.objects.create(ac_id=agent_customer_info.id, name=card_name, card_no=card_no, card_address=card_address, status=1,
                                                     created_time=int(time.time()), updated_time=int(time.time()), created_by=userID, updated_by=userID)
                    # 绑定所有代理套餐
                    all_service_packages = AgentCloudServicePackage.objects.filter(status=1)
                    for package in all_service_packages:
                        AgentCustomerPackage.objects.create(
                            ac_id=agent_customer_info.id,
                            cs_id=package.id,
                            created_time=int(time.time()),
                            updated_time=int(time.time()),
                            created_by=userID,  # 假设 userID 是创建这个记录的用户ID
                            updated_by=userID
                        )
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

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

    def resetPassword(self, request_dict, response):
        userID = request_dict.get('userID', None)
        if not userID:
            return response.json(444)
        try:
            password = '123456'
            is_update = Device_User.objects.filter(userID=userID).update(password=make_password(password))
            if is_update:
                return response.json(0)
            else:
                return response.json(177)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def getFeedbackList(self, request_dict, response):
        """
        用户反馈查询
        @param request_dict:请求参数
        @param response:响应对象
        @param status:回复状态
        @param collectStatus:收藏状态1
        @return:
        """
        status = request_dict.get('status', 0)
        username = request_dict.get('username', None)
        collectStatus = request_dict.get('collectStatus', None)
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        page = int(pageNo)
        line = int(pageSize)
        try:
            filter_data = {}
            if status or username or collectStatus:
                if status:
                    filter_data['status'] = int(status)
                if username:
                    filter_data['userID_id'] = ModelService.get_userID_byname(username)
                if collectStatus:
                    filter_data['collect_status'] = int(collectStatus)
            feed_back_qs = FeedBackModel.objects.filter()
            if filter_data:
                feed_back_qs = feed_back_qs.filter(**filter_data).values()
            total = feed_back_qs.count()
            feed_backs = feed_back_qs.values(
                'id',
                'userID__username',
                'userID__phone',
                'userID__userEmail',
                'content',
                'addTime',
                'status',
                'type',
                'app',
                'app_version',
                'phone_model',
                'os_version',
                'uid',
                'appBundleId',
                'score',
                'collect_status'
            )
            feed_backs = feed_backs[(page - 1) * line: page * line]
            feed_back_id_list = [feed_back['id'] for feed_back in feed_backs]
            stat_res_qs = StatResModel.objects.filter(
                feedbackmodel__id__in=feed_back_id_list).values(
                'name', 'feedbackmodel__id')
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(
                auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
            feed_back_list = []
            for feed_back in feed_backs:
                feed_back['img_url'] = []
                for stat_res in stat_res_qs:
                    if stat_res['feedbackmodel__id'] == feed_back['id']:
                        obj = 'feedback/' + stat_res['name']
                        img_url = bucket.sign_url('GET', obj, 3600)
                        feed_back['img_url'].append(img_url)
                        if not feed_back['userID__username']:
                            feed_back['userID__username'] = feed_back['userID__userEmail'] if feed_back[
                                'userID__userEmail'] else feed_back['userID__phone']
                feed_back_list.append(feed_back)
            return response.json(0, {'list': feed_back_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def replyFeedBack(self, request_dict, response):
        feedBackID = request_dict.get('feedBackID', None)
        msg = request_dict.get('msg', None)
        uid = request_dict.get('uid', None)

        if not all([feedBackID, msg]):
            return response.json(444)

        try:
            nowTime = int(time.time())
            feed_back_qs = FeedBackModel.objects.filter(id=feedBackID)
            if not feed_back_qs.exists():
                return response.json(173)
            with transaction.atomic():
                SysMsgModel.objects.create(userID_id=feed_back_qs.first().userID_id, msg=msg, uid=uid,
                                           addTime=nowTime, updTime=nowTime)  # 创建系统消息
                feed_back_qs.update(status=1)  # 更新状态为已回复
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def sendSysMsgToUser(self, request_dict, response):
        """
        发送系统消息至用户
        @param request_dict:请求参数
        @param response:响应对象
        @param userID:用户ID
        @param msg:发送内容
        @return:
        """
        userID = request_dict.get('userID', None)
        msg = request_dict.get('msg', None)

        if not all([userID, msg]):
            return response.json(444)

        try:
            nowTime = int(time.time())
            SysMsgModel.objects.create(userID_id=userID, msg=msg, addTime=nowTime, updTime=nowTime)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def deleteFeedBack(self, request_dict, response):
        feedBackID = request_dict.get('feedBackID', None)
        if not feedBackID:
            return response.json(444)
        try:
            feed_back = FeedBackModel.objects.get(id=feedBackID)
            sr_id_list = feed_back.FS.values_list('id', flat=True)
            StatResModel.objects.filter(id__in=sr_id_list).delete()
            feed_back.delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def getSysMessageList(self, request_dict, response):
        # 功能群发查询
        print('request_dict: ', request_dict)
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)

        try:
            sys_mass_qs = SysMassModel.objects.filter()
            total = sys_mass_qs.count()
            sys_mass_qs = sys_mass_qs.values('id', 'sender__username', 'addTime', 'updTime', 'lang', 'recever', 'msg',
                                             'platform')
            sys_mass_qs = sys_mass_qs[(page - 1) * line:page * line]
            return response.json(0, {'list': list(sys_mass_qs), 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def getAppDataList(self, request_dict, response):
        print('request_dict: ', request_dict)
        platform = request_dict.get('platform', None)

        if platform == 'ios':
            app_type = [1]
        elif platform == 'android':
            app_type = [2]
        else:
            app_type = [1, 2]

        try:
            app_info_qs = App_Info.objects.filter(app_type__in=app_type).values('appBundleId', 'appName').distinct()
            appBundleId_list = []
            for app_info in app_info_qs:
                appBundleId_list.append(app_info['appBundleId'])
            return response.json(0, {'appBundleId_list': appBundleId_list})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def sendSysMessage(self, request_dict, response):
        print('request_dict: ', request_dict)
        lang = request_dict.get('lang', None)
        platform = request_dict.get('platform', None)
        recever = request_dict.get('app_list', None)
        msg = request_dict.get('msg', None)

        if not all([lang, platform, recever, msg]):
            return response.json(444)

        try:
            # SysMassModel表创建群发消息记录数据
            now_time = int(time.time())
            sender_id = Device_User.objects.filter(username='13800138001').values('userID').first()['userID']
            SysMassModel.objects.create(
                sender_id=sender_id,
                lang=lang,
                platform=platform,
                recever=recever,
                msg=msg,
                addTime=now_time,
                updTime=now_time,
            )
            # 查询并处理数据
            self.process_sys_messages(lang, recever, msg, now_time)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def collectFeedBack(self, request_dict, response):
        """收藏或取消收藏用户反馈信息"""
        feedBackID = request_dict.get('feedBackID', None)
        collect_status = request_dict.get('collectStatus', None)
        if not all([feedBackID, collect_status]):
            return response.json(444)
        feedBackID = int(feedBackID)
        collect_status = int(collect_status)
        feed_back_qs = FeedBackModel.objects.filter(id=feedBackID, collect_status=collect_status)
        if feed_back_qs.exists():  # 判断是否已收藏
            feed_qs = feed_back_qs.first()
            feed_qs.collect_status = 0
            feed_qs.save()
        else:
            FeedBackModel.objects.filter(id=feedBackID).update(collect_status=collect_status)
        return response.json(0)

    def exportFeedBack(self, request_dict, response):
        status = request_dict.get('status', None)
        collectStatus = request_dict.get('collectStatus', None)
        try:
            with transaction.atomic():
                filter_data = {}
                if status or collectStatus:
                    if status:
                        filter_data['status'] = int(status)
                    if collectStatus:
                        filter_data['collect_status'] = int(collectStatus)
                feed_back_qs = FeedBackModel.objects.filter()
                if filter_data:
                    feed_back_qs = feed_back_qs.filter(**filter_data)
                feed_backs = feed_back_qs.values(
                    'id',
                    'userID__username',
                    'userID__phone',
                    'userID__userEmail',
                    'content',
                    'addTime',
                    'status',
                    'type',
                    'app',
                    'app_version',
                    'phone_model',
                    'os_version',
                    'uid',
                    'appBundleId',
                    'score',
                    'collect_status'
                )
                feed_back_id_list = [feed_back['id'] for feed_back in feed_backs]
                stat_res_qs = StatResModel.objects.filter(
                    feedbackmodel__id__in=feed_back_id_list).values(
                    'name', 'feedbackmodel__id')
                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                bucket = oss2.Bucket(
                    auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
                feed_back_list = []
                for feed_back in feed_backs:
                    feed_back['img_url'] = []
                    for stat_res in stat_res_qs:
                        if stat_res['feedbackmodel__id'] == feed_back['id']:
                            obj = 'feedback/' + stat_res['name']
                            img_url = bucket.sign_url('GET', obj, 3600)
                            feed_back['img_url'].append(img_url)
                            if not feed_back['userID__username']:
                                feed_back['userID__username'] = feed_back['userID__userEmail'] if feed_back[
                                    'userID__userEmail'] else feed_back['userID__phone']
                    feed_back_list.append(feed_back)
            return response.json(0, {'list': feed_back_list})
        except Exception as e:
            print(e)

    def customerServiceManagement(self, request_dict, response):
        """
        审核用户请求/生成超级密码
        @param request_dict:请求参数
        @param response:响应对象
        @request_dict status: 0:未通过,1:通过
        @request_dict hint: 温馨提示
        @return:
        """
        ID = request_dict.get('ID', None)
        userID = request_dict.get('userID', None)
        uid = request_dict.get('uid', None)
        status = request_dict.get('status', None)
        hint = request_dict.get('hint', None)
        lang = request_dict.get('lang', 'en')
        if not all({ID, uid, userID}):
            return response.json(444, 'ID, uid, userID')
        now = int(time.time())
        try:
            with transaction.atomic():
                device_super_password_qs = DeviceSuperPassword.objects.filter(id=ID, uid=uid, userID=userID)
                if not device_super_password_qs.exists():
                    return response.json(173)
                status = int(status)
                if status == 1:
                    # 验证码生成
                    super_code = RandomStr(6, True)
                    super_password_id = "super_password_%s" % userID
                    redisObj = RedisObject()
                    redis = redisObj.set_data(key=super_password_id, val=super_code, expire=86400)
                    if redis is False:
                        return response.json(121)
                    device_super_password_qs.update(status=status)
                    if lang == 'en':
                        msg = "Your authorization code is " + super_code + ",valid within 24 hours"
                    else:
                        msg = "您的授权代码：" + super_code + "，24小时内有效"
                    # eventType: 0系统消息，1 ipcamera消息，2 超级密码
                    SysMsgModel.objects.create(userID_id=userID, msg=msg, addTime=now, updTime=now, uid=uid,
                                               eventType=2)
                    return response.json(0)
                if status == 0 and len(hint) > 1:
                    device_super_password_qs.update(status=status, hint=hint)
                    SysMsgModel.objects.create(userID_id=userID, msg=hint, addTime=now, updTime=now, uid=uid,
                                               eventType=2)
                    return response.json(0)
                return response.json(177)
        except Exception as e:
            print('修改状态异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def getDeviceSuperPassword(self, request_dict, response):
        """
        查询用户请求表
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        status = request_dict.get('status', None)
        userID = request_dict.get('userID', None)
        uid = request_dict.get('uid', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        page = int(pageNo)
        line = int(pageSize)
        try:
            device_super_password_qs = DeviceSuperPassword.objects.all()
            if status:
                device_super_password_qs = device_super_password_qs.filter(status=status)
            if userID:
                device_super_password_qs = device_super_password_qs.filter(userID=userID)
            if uid:
                device_super_password_qs = device_super_password_qs.filter(uid=uid)
            if not device_super_password_qs.exists():
                return response.json(0, [])
            count = device_super_password_qs.count()
            device_super_password_qs = device_super_password_qs.values('id',
                                                                       'uid',
                                                                       'userID',
                                                                       'orderID',
                                                                       'describe',
                                                                       'purchase_channel',
                                                                       'addTime',
                                                                       'status',
                                                                       'buyTime',
                                                                       'hint',
                                                                       'lang',
                                                                       'userID__username')
            device_super_password_qs = device_super_password_qs.order_by('-addTime')[
                                       (page - 1) * line:page * line]
            return response.json(0, {'list': list(device_super_password_qs), 'count': count})
        except Exception as e:
            print('查询异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def deleteInformation(self, request_dict, response):
        """
        删除信息
        @param request_dict:请求参数
        @param response:响应对象
        """
        ID = request_dict.get('id', None)
        if not ID:
            return response.json(444)
        device_super_password_qs = DeviceSuperPassword.objects.filter(id=ID)
        if not device_super_password_qs.exists():
            return response.json(173)
        device_super_password_qs.delete()
        return response.json(0)

    @staticmethod
    def getCustomizedPushList(request_dict, response):
        title = request_dict.get('title', None)
        country = request_dict.get('country', None)
        device_type = request_dict.get('device_type', None)
        push_satus = request_dict.get('push_satus', None)
        page = request_dict.get('pageNo', None)
        line = request_dict.get('pageSize', None)

        if not all([page, line]):
            return response.json(444)

        page = int(page)
        line = int(line)

        try:
            customized_push_qs = CustomizedPush.objects.all().order_by('-push_timestamp')
            if title:
                customized_push_qs = customized_push_qs.filter(title=title)
            if country:
                customized_push_qs = customized_push_qs.filter(country=country)
            if device_type:
                customized_push_qs = customized_push_qs.filter(device_type__contains=device_type)
            if push_satus:
                customized_push_qs = customized_push_qs.filter(push_satus=push_satus)
            if not customized_push_qs.exists():
                return response.json(0, [])
            total = customized_push_qs.count()
            customized_push_qs = customized_push_qs.\
                values('id', 'title', 'msg', 'link', 'icon_link', 'country', 'device_type', 'register_period',
                       'time_zone', 'push_time', 'push_app', 'push_satus')
            customized_push_qs = customized_push_qs[(page - 1) * line:page * line]
            customized_push_list = []
            for customized_push in customized_push_qs:
                # 格式化数据
                register_period = customized_push['register_period'] + '年'
                time_zone = 'UTC ' + customized_push['time_zone']

                customized_push_list.append({
                    'customized_push_id': customized_push['id'],
                    'title': customized_push['title'],
                    'msg': customized_push['msg'],
                    'link': customized_push['link'],
                    'icon_link': customized_push['icon_link'],
                    'country': customized_push['country'],
                    'device_type': customized_push['device_type'],
                    'register_period': register_period,
                    'time_zone': time_zone,
                    'push_time': customized_push['push_time'],
                    'push_app': customized_push['push_app'],
                    'push_satus': customized_push['push_satus']
                })
            return response.json(0, {'list': customized_push_list, 'total': total})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def addOrEditCustomizedPush(cls, request, request_dict, response):
        title = request_dict.get('title', None)
        msg = request_dict.get('msg', None)
        link = request_dict.get('link', None)
        icon = request.FILES.get('icon', None)
        country = request_dict.get('country', None)
        device_type = request_dict.get('deviceType', None)
        register_period = request_dict.get('registerPeriod', None)
        time_zone = request_dict.get('timeZone', None)
        push_time = request_dict.get('pushTime', None)
        push_app = request_dict.get('pushApp', None)
        is_edit = request_dict.get('isEdit', None)

        if not all([title, msg, link, country, device_type, register_period, time_zone, push_time, push_app]):
            return response.json(444)

        # 截掉UTC和空格
        time_zone = time_zone[4:]
        try:
            push_timestamp = CommonService.convert_to_timestamp(float(time_zone), push_time)
            if push_timestamp <= int(time.time()):
                return response.json(806)
            customized_push_data = {
                'title': title,
                'msg': msg,
                'link': link,
                'country': country,
                'device_type': device_type,
                'register_period': register_period,
                'time_zone': time_zone,
                'push_time': push_time,
                'push_timestamp': push_timestamp,
                'push_app': push_app
            }
            icon_link = ''
            if icon is not None:
                icon_name = icon.name
                icon_link = 'https://ansjerfilemanager.s3.amazonaws.com/customized-push/' + icon_name
                customized_push_data['icon_link'] = icon_link

                if icon_link:
                    # 上传没有上传过的图片到S3
                    customized_push_qs = CustomizedPush.objects.filter(icon_link=icon_link)
                    if not customized_push_qs.exists():
                        bucket = 'ansjerfilemanager'
                        file_key = 'customized-push/' + icon_name
                        s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
                        s3.upload_file_obj(
                            bucket,
                            file_key,
                            icon,
                            {'ContentType': icon.content_type, 'ACL': 'public-read'})

            apscheduler_obj = ApschedulerObject()
            if is_edit:     # 编辑
                customized_push_id = request_dict.get('customizedPushId', None)
                if not customized_push_id:
                    return response.json(444)
                customized_push_data['push_satus'] = False
                CustomizedPush.objects.filter(id=customized_push_id).update(**customized_push_data)
                apscheduler_obj.del_job('customized_push_id_{}'.format(customized_push_id))  # 删除旧定时任务
            else:           # 新增
                customized_push = CustomizedPush.objects.create(**customized_push_data)
                customized_push_id = customized_push.id

            # 创建定时任务
            task_id = 'customized_push_id_{}'.format(customized_push_id)
            apscheduler_obj.create_date_job(func=cls.req_customized_push, task_id=task_id, time_stamp=push_timestamp,
                                            args=(customized_push_id,))
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def req_customized_push(customized_push_id):
        """
        请求定制化推送
        @param customized_push_id:
        @return:
        """
        data = {'customized_push_id': customized_push_id}
        url = DETECT_PUSH_DOMAINS + 'customized_push/start'
        req = requests.post(url=url, data=data, timeout=8)

    @staticmethod
    def delCustomizedPush(request_dict, response):
        customized_push_id = request_dict.get('customizedPushId', None)
        if not customized_push_id:
            return response.json(444)
        try:
            CustomizedPush.objects.filter(id=customized_push_id).delete()
            # 删除定时任务
            apscheduler_obj = ApschedulerObject()
            apscheduler_obj.del_job('customized_push_id_{}'.format(customized_push_id))
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def getCountryList(response):
        try:
            country_qs = CountryModel.objects.filter().values('country_name')
            if not country_qs.exists():
                return response.json(173)

            country_list = []
            for country in country_qs:
                country_list.append(country['country_name'])
            return response.json(0, {'list': country_list})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def getDeviceTypeList(response):
        try:
            device_type_qs = DeviceTypeModel.objects.filter().values('name')
            if not device_type_qs.exists():
                return response.json(173)

            device_type_list = []
            for device_type in device_type_qs:
                device_type_list.append(device_type['name'])
            return response.json(0, {'list': device_type_list})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_custom_customer_list(request_dict, response):
        """
        查询定制客户信息
        :param request_dict:
        :param response:
        :return:
        """
        order_number = request_dict.get('orderNumber', None)
        name = request_dict.get('name', None)
        email = request_dict.get('email', None)
        page = request_dict.get('pageNo', 1)
        page_size = request_dict.get('pageSize', 10)
        try:
            # 初始化查询集
            custom_customer_qs = CustomCustomerOrderInfo.objects.all()

            if order_number:
                custom_customer_qs = custom_customer_qs.filter(order_number__icontains=order_number)
            if name:
                custom_customer_qs = custom_customer_qs.filter(name__icontains=name)
            if email:
                custom_customer_qs = custom_customer_qs.filter(email__icontains=email)

            paginator = Paginator(custom_customer_qs.order_by('id'), page_size)
            customers = paginator.page(page)

            # 批量查询所有相关的国家信息
            country_ids = custom_customer_qs.values_list('country_id', flat=True).distinct()
            country_qs = CountryModel.objects.filter(id__in=country_ids)
            country_map = {country.id: country.country_name for country in country_qs}

            customer_list = []
            for customer in customers.object_list:
                country_name = country_map.get(customer.country_id, '')
                customer_list.append({
                    'cId': customer.id,
                    'orderNumber': customer.order_number,
                    'name': customer.name,
                    'email': customer.email,
                    'countryName': country_name,
                    'quantity': customer.quantity,
                    'createdTime': customer.created_time,
                })

            # 返回分页结果
            data = {
                'total': paginator.count,
                'list': list(customer_list),  # 当前页的记录列表
            }

            return response.json(0, data)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def add_custom_customer(request_dict, response):
        """
        添加定制客户生产编号信息
        :param request_dict: 请求字典
        :param response: 响应对象
        :return: 响应对象
        """
        order_number = request_dict.get('orderNumber', None)
        name = request_dict.get('name', None)
        quantity = int(request_dict.get('quantity', 0))
        email = request_dict.get('email', None)
        country_code = request_dict.get('countryCode', "en")

        if not all([order_number, name, email, quantity]):
            return response.json(444)

        custom_customer_qs = CustomCustomerOrderInfo.objects.filter(order_number=order_number)
        if custom_customer_qs.exists():
            return response.json(174)

        try:
            country_code = country_code.upper()
            country_qs = CountryModel.objects.filter(country_code=country_code)
            country_id = 0
            if country_qs.exists():
                country_id = country_qs.first().id
            CustomCustomerOrderInfo.objects.create(
                order_number=order_number,
                name=name,
                email=email,
                country_id=country_id,
                quantity=quantity,
                created_time=int(time.time()),
                updated_time=int(time.time())
            )
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def del_custom_customer(request_dict, response):
        pass

    def process_sys_messages(self, lang, recever, msg, now_time):
        """分页查询数据并分批保存系统消息"""
        region_list = lang.split(',')
        appBundleId_list = recever.split(',')

        # 查询符合条件的用户ID
        user_queryset = UserExModel.objects.filter(appBundleId__in=appBundleId_list,
                                                   region__in=region_list).values_list('userID_id', flat=True)
        paginator = Paginator(user_queryset, 10000)  # 每次查询10000条

        # 创建线程池用于并发保存
        with ThreadPoolExecutor(max_workers=5) as executor:
            for page_num in paginator.page_range:
                user_ids = paginator.page(page_num).object_list
                # 提交保存任务到线程池
                executor.submit(self.save_sys_messages_in_batches, user_ids, msg, now_time)

    def save_sys_messages_in_batches(self, user_ids, msg, now_time):
        """分批保存系统消息，每次最多5000条"""
        sys_msg_list = []
        for user_id in user_ids:
            sys_msg_list.append(SysMsgModel(userID_id=user_id, msg=msg, addTime=now_time, updTime=now_time))

            if len(sys_msg_list) >= 5000:
                SysMsgModel.objects.bulk_create(sys_msg_list)
                sys_msg_list = []

        # 保存剩余的消息
        if sys_msg_list:
            SysMsgModel.objects.bulk_create(sys_msg_list)
