import logging
import time
from urllib.parse import quote, parse_qs, unquote

import paypalrestsdk
from django.db import transaction
from django.db.models import Q, F, Sum
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic.base import View

from Ansjer.config import PAYPAL_CRD, SERVER_DOMAIN_SSL, DETECT_PUSH_DOMAINS, LOGGER
from Model.models import Device_Info, Order_Model, ExperienceAiModel, Pay_Type, CDKcontextModel, UidPushModel, \
    AiStoreMeal, AiService, UidSetModel
from Object.AliPayObject import AliPayObject
from Object.ETkObject import ETkObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.WechatPayObject import WechatPayObject
from Service.CommonService import CommonService


class AiView(View):
    """
    AI业务功能
    AI套餐,开关,消息列表
    """

    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):
        response = ResponseObject()
        if operation is None:
            return response.json(414)
        # 支付回调接口
        elif operation == 'doPayPalCallBack':  # paypal支付回调
            return self.do_paypal_callback(request_dict, response)
        elif operation == 'doAlipayCallBack':  # 支付宝支付回调
            return self.do_alipay_callback(request_dict, response)
        elif operation == 'doWechatCallBack':  # 微信支付回调
            return self.do_wechat_callback(request, response)
        else:
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            user_id = tko.userID

            # 套餐相关接口
            if operation == 'commoditylist':  # 查询套餐列表
                return self.commodity_list(request_dict, response)
            # elif operation == 'experienceOrder':  # 体验套餐
            #     return self.experience_order(request_dict, user_id, response)
            # elif operation == 'createpayorder':  # 创建支付订单
            #     return self.create_pay_order(request_dict, request, user_id, response)
            elif operation == 'queryorderlist':  # 查询订单列表
                return self.query_order_list(request_dict, user_id, response)
            elif operation == 'getUsingPackage':  # 获取当前使用套餐
                return self.get_using_package(request_dict, response)
            # 开关相关接口
            elif operation == 'getAiStatus':  # 获取开关状态
                return self.get_ai_status(request_dict, response)
            elif operation == 'changeaistatus':  # 修改开关状态
                return self.change_ai_status(request_dict, user_id, response)
            else:
                return response.json(414)

    @staticmethod
    def commodity_list(request_dict, response):
        """
        查询套餐列表
        @param request_dict: 请求数据
        @request_dict uid: uid
        @request_dict lang: 语言
        @param response: 响应
        @return: response
        """
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')

        try:
            # DVR/NVR设备暂不返回套餐列表
            device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
            if device_info_qs.exists():
                return response.json(0)

            # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
            exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
            if exc_ai_qs.exists():
                ai_meal_qs = AiStoreMeal.objects.filter(~Q(pay_type=10))
            else:
                ai_meal_qs = AiStoreMeal.objects.filter(pay_type=10)

            # 查询套餐数据
            ai_meal_qs = ai_meal_qs.filter(is_show=1, lang__lang=lang). \
                annotate(ai_meal_id=F('id'), title=F('lang__title'), content=F('lang__content')). \
                values('ai_meal_id', 'title', 'content', 'price', 'effective_day', 'currency', 'virtual_price',
                       'symbol', 'is_beta')
            if not ai_meal_qs.exists():
                return response.json(0)

            # 查询每种套餐的所有支付方式
            ai_meal_list = list(ai_meal_qs)
            for ai_meal in ai_meal_list:
                pay_type_qs = Pay_Type.objects.filter(aistoremeal=ai_meal['ai_meal_id']).values('id', 'payment')
                ai_meal['pay_type'] = list(pay_type_qs)
            result = {
                'meals': ai_meal_list,
            }
            return response.json(0, result)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def experience_order(request_dict, user_id, response):
        """
        体验套餐
        @param request_dict: 请求数据
        @request_dict uid: uid
        @request_dict channel: 通道
        @request_dict pay_type: 支付类型
        @request_dict rank: 套餐id
        @request_dict cdk: 兑换码
        @request_dict lang: 语言
        @param user_id: 用户id
        @param response: 响应
        @return: response
        """
        logger = logging.getLogger('info')
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        pay_type = int(request_dict.get('pay_type', 10))
        rank = request_dict.get('rank', None)
        cdk = request_dict.get('cdk', None)
        lang = request_dict.get('lang', 'en')

        # 使用redis设置唯一key加锁
        redisObj = RedisObject()
        redis_key = uid + 'do_experience_ai_order'
        isLock = redisObj.CONN.setnx(redis_key, 1)
        if not isLock:
            return response.json(5)
        redisObj.CONN.expire(redis_key, 60)
        try:
            if pay_type == 10:  # 判断是否已体验过套餐
                exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
                if exc_ai_qs.exists():
                    return response.json(5)

            if cdk is not None and pay_type == 11:  # 兑换码体验
                cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id',
                                                                        'rank__commodity_code')
                if not cdk_qs.exists():
                    return response.json(10040)
                if cdk_qs[0]['is_activate'] == 1:
                    return response.json(10039)
                rank = cdk_qs[0]['rank__id']

            if not all([uid, channel, rank]):
                redisObj.del_data(key=redis_key)
                return response.json(444)

            # 判断是否为主用户操作
            device_info_qs = Device_Info.objects.filter(Q(UID=uid) & ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
            if device_info_qs.exists():
                if device_info_qs[0]['vodPrimaryUserID'] != user_id:
                    if pay_type == 10:
                        return response.json(10035)
                    if pay_type == 11:
                        return response.json(10036)

            dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
            if not dv_qs.exists():
                return response.json(12)

            orderID = CommonService.createOrderID()
            nowTime = int(time.time())
            ai_store_meal_qs = AiStoreMeal.objects.filter(id=rank, lang__lang=lang, is_show=1). \
                values('lang__content', 'price', 'currency', 'effective_day')
            if not ai_store_meal_qs.exists():
                return response.json(173)

            effective_day = ai_store_meal_qs[0]['effective_day']
            endTime = int(time.time()) + effective_day * 24 * 60 * 60  # 套餐结束时间

            # 查询中文套餐名
            ai_cn_store_meal_qs = AiStoreMeal.objects.filter(id=rank, lang__lang='cn', is_show=1). \
                values('lang__content', 'lang__title')
            if ai_cn_store_meal_qs.exists():
                store_meal_name = ai_cn_store_meal_qs[0]['lang__title'] + '-' + ai_cn_store_meal_qs[0]['lang__content']
            else:
                store_meal_name = '未知套餐'

            with transaction.atomic():
                # 订单表创建数据
                Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=user_id,
                                           desc=ai_store_meal_qs[0]['lang__content'], payType=pay_type, payTime=nowTime,
                                           price=ai_store_meal_qs[0]['price'], currency=ai_store_meal_qs[0]['currency'],
                                           addTime=nowTime, updTime=nowTime, pay_url='AI体验',
                                           store_meal_name=store_meal_name, order_type=1,
                                           rank_id=1, ai_rank_id=rank, status=1)
                # ai服务表创建数据
                AiService.objects.create(uid=uid, channel=channel, detect_status=1, endTime=endTime,
                                         addTime=nowTime, updTime=nowTime, use_status=1)
                logger.info('{}成功开通AI体验,结束时间{}'.format(uid, endTime))
                if pay_type == 10:
                    ExperienceAiModel.objects.create(
                        experience_type=0,
                        uid=uid,
                        do_time=nowTime
                    )
                elif pay_type == 11:
                    CDKcontextModel.objects.filter(cdk=cdk).update(is_activate=1, order=orderID)

                redisObj.del_data(key=redis_key)
                pay_ok_url = "{}cloudstorage/payOK?paytype={}&lang={}".format(SERVER_DOMAIN_SSL, pay_type, lang)
                return response.json(0, pay_ok_url)
        except Exception as e:
            redisObj.del_data(key=redis_key)
            logger.info('开通AI异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(474)

    @classmethod
    def create_pay_order(cls, request_dict, request, user_id, response):
        """
        创建支付订单
        @param request_dict: 请求数据
        @param request: 请求体
        @request_dict uid: uid
        @request_dict channel: 通道
        @request_dict pay_type: 支付类型
        @request_dict rank: 套餐id
        @request_dict lang: 语言
        @param user_id: 用户id
        @param response: 响应
        @return: response
        """
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        pay_type = int(request_dict.get('pay_type', 1))
        rank = request_dict.get('rank', None)
        lang = request_dict.get('lang', 'en')
        if not all([uid, channel, rank]):
            return response.json(444)

        try:
            # 获取ai套餐数据
            ai_sm_qs = AiStoreMeal.objects.filter(id=rank, pay_type=pay_type, is_show=1, lang__lang=lang). \
                values('lang__title', 'lang__content', 'currency', 'price')
            if not ai_sm_qs.exists():
                return response.json(173)
            title = ai_sm_qs[0]['lang__title']
            content = ai_sm_qs[0]['lang__content']
            currency = ai_sm_qs[0]['currency']
            price = ai_sm_qs[0]['price']

            # 查询中文套餐名
            ai_store_meal_qs = AiStoreMeal.objects.filter(id=rank, is_show=1, lang__lang='cn'). \
                values('lang__title', 'lang__content')
            if ai_store_meal_qs.exists():
                store_meal_name = ai_store_meal_qs[0]['lang__title'] + '-' + ai_store_meal_qs[0]['lang__content']
            else:
                store_meal_name = '未知套餐'

            now_time = int(time.time())
            price = round(float(price), 2)
            order_id = CommonService.createOrderID()

            order_dict = {
                'orderID': order_id,
                'UID': uid,
                'channel': channel,
                'userID_id': user_id,
                'desc': content,
                'payType': pay_type,
                'payTime': now_time,
                'price': price,
                'currency': currency,
                'addTime': now_time,
                'updTime': now_time,
                'ai_rank_id': rank,
                'rank_id': 1,
                'order_type': 1,
                'store_meal_name': store_meal_name
            }

            # 创建订单数据和返回支付回调链接
            if pay_type == 1:  # PayPal支付
                res_dict = cls.create_paypal_payment(lang, order_id, price, currency, content)
                if not res_dict:
                    return response.json(10, 'create ai order failed')
                order_dict['paymentID'], order_dict['pay_url'] = res_dict['payment_id'], res_dict['pay_url']
                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url']}

            elif pay_type == 2:  # 支付宝支付
                res_dict = cls.create_alipay_payment(lang, order_id, price, title, content)
                if not res_dict:
                    return response.json(10, 'create ai order failed')
                order_dict['pay_url'] = res_dict['pay_url']
                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url']}

            elif pay_type == 3:  # 微信支付
                ip = CommonService.get_ip_address(request)
                res_dict = cls.create_wechat_payment(lang, order_id, price, ip, content)
                if not res_dict:
                    return response.json(10, 'create ai order failed')
                order_dict['pay_url'], sign_params = res_dict['pay_url'], res_dict['sign_params']
                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url'], 'result': sign_params}

            else:
                return response.json(444, {'param': 'pay_type'})

            Order_Model.objects.create(**order_dict)
            return response.json(0, res_data)

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

    @staticmethod
    def query_order_list(request_dict, user_id, response):
        """
        查询订单列表
        @param request_dict: 请求数据
        @param user_id: 用户id
        @request_dict page: 页数
        @request_dict line: 条数
        @request_dict uid: uid
        @request_dict lang: 语言
        @param response: 响应
        @return: response
        """
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')

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

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

        try:
            order_qs = Order_Model.objects.filter(userID_id=user_id, status=1, order_type=1, ai_rank__lang__lang=lang)

            if uid:  # 查询指定设备订单
                order_qs.filter(UID=uid)
            if not order_qs.exists():
                return response.json(173)

            count = order_qs.count()
            order_qs = order_qs.annotate(rank__title=F('ai_rank__lang__title'),
                                         rank__content=F('ai_rank__lang__content'),
                                         rank__day=F('ai_rank__effective_day'), rank__price=F('ai_rank__price'),
                                         rank__expire=F('ai_rank__effective_day'), rank__id=F('ai_rank_id'),
                                         rank__currency=F('ai_rank__currency'))
            order_qs = order_qs[(page - 1) * line:page * line].values('orderID', 'UID', 'channel', 'desc', 'price',
                                                                      'currency', 'addTime', 'updTime', 'paypal',
                                                                      'rank__day', 'payType', 'rank__price', 'status',
                                                                      'rank__content', 'rank__title', 'rank__currency',
                                                                      'rank__expire', 'ai_rank_id')
            order_list = list(order_qs)
            data = []
            now_time = int(time.time())
            uid_list = [order['UID'] for order in order_list]
            device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID__in=uid_list).values('id', 'UID', 'Type')
            for order in order_list:
                if order['status'] == 0:
                    if order['addTime'] + 3600 < now_time:
                        order['status'] = 3
                for did in device_info_qs:
                    if order['UID'] == did['UID']:
                        order['did'] = did['id']
                        order['Type'] = did['Type']
                        data.append(order)
            return response.json(0, {'data': data, 'count': count})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_using_package(request_dict, response):
        """
        获取当前使用套餐
        @param request_dict: 请求数据
        @request_dict uid: uid
        @request_dict lang: 语言
        @param response: 响应
        @return: response
        """
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')

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

        try:
            ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, orders__ai_rank__lang__lang=lang)
            if not ai_service_qs.exists():
                return response.json(0, [])

            # 计算套餐过期时间
            sum_end_time = AiService.objects.filter(Q(uid=uid), ~Q(use_status=2)).aggregate(Sum('endTime'))[
                'endTime__sum']
            ai_service_qs = ai_service_qs.order_by('addTime').annotate(
                bucket__content=F('orders__ai_rank__lang__title')). \
                values('uid', 'use_status', 'bucket__content')

            ai_service_data = ai_service_qs[0]
            ai_service_data['endTime'] = sum_end_time

            # 如果存在序列号返回完整序列号
            device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
            serial_number = device_info_qs[0]['serial_number']
            device_type = device_info_qs[0]['Type']
            if serial_number:
                ai_service_data['serial_number'] = CommonService.get_full_serial_number(uid, serial_number, device_type)

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

    @staticmethod
    def get_ai_status(request_dict, response):
        """
        获取AI开关状态
        @param request_dict: 请求数据
        @request_dict uid: uid
        @param response: 响应
        @return: response
        """
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(444)
        try:
            ai_server_qs = AiService.objects.filter(uid=uid, use_status=1).values('detect_status', 'detect_group')
            if not ai_server_qs.exists():
                return response.json(173)
            res = {
                'detect_status': ai_server_qs[0]['detect_status'],
                'detect_group': ai_server_qs[0]['detect_group'],
            }
            return response.json(0, {'data': res})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def change_ai_status(request_dict, user_id, response):
        """
        修改AI开关状态
        @param request_dict: 请求数据
        @request_dict token_val: 设备验证令牌
        @request_dict appBundleId: app包id
        @request_dict app_type: app类型
        @request_dict push_type: 推送类型
        @request_dict status: 开关状态, 0: 关, 1: 开
        @request_dict m_code: 手机唯一标识
        @request_dict uid: uid
        @request_dict lang: 语言
        @request_dict tz: 时区
        @request_dict detect_group: 检测类型
        @request_dict interval: 推送间隔
        @request_dict domain_name: 域名
        @param user_id: 用户id
        @param response: 响应
        @return: response
        """
        token_val = request_dict.get('token_val', None)
        appBundleId = request_dict.get('appBundleId', None)
        app_type = request_dict.get('app_type', None)
        push_type = request_dict.get('push_type', None)
        status = request_dict.get('status', None)
        m_code = request_dict.get('m_code', None)
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')
        tz = request_dict.get('tz', '0')
        detect_group = request_dict.get('detect_group', None)
        interval = request_dict.get('interval', None)
        domain_name = request_dict.get('domain_name', None)

        if not all([appBundleId, app_type, token_val, uid, m_code, status]):
            return response.json(444, 'appBundleId, app_type, token_val, uid,m_code, status')

        # 如果传空上来，就默认为0
        tz = '0' if tz == '' else tz.replace('GMT', '')

        try:
            ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
            if not ai_service_qs.exists():
                return response.json(10053)
            nowTime = int(time.time())
            endTime = ai_service_qs.values('endTime')[0]['endTime']
            if nowTime > endTime:
                return response.json(10054)

            # 查询设备是否属于该用户
            device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid)
            if not device_info_qs.exists():
                return response.json(14)
            status = int(status)
            nowTime = int(time.time())

            uid_set_qs = UidSetModel.objects.filter(uid=uid)
            if uid_set_qs.exists():
                uid_set_id = uid_set_qs[0].id
                interval = uid_set_qs[0].new_detect_interval if not interval else interval
                qs_data = {
                    'updTime': nowTime,
                }
                if interval:
                    qs_data['detect_interval'] = int(interval)
                    qs_data['detect_group'] = detect_group if detect_group else ''
                uid_set_qs.update(**qs_data)
            else:
                qs_data = {
                    'uid': uid,
                    'addTime': nowTime,
                    'updTime': nowTime,
                    'device_type': device_info_qs[0].Type
                }
                if interval:
                    qs_data['detect_interval'] = int(interval)
                qs_data['detect_group'] = detect_group if detect_group else ''
                # 添加设备配置
                uid_set_qs = UidSetModel.objects.create(**qs_data)
                uid_set_id = uid_set_qs.id

            qs_data['detect_status'] = status  # ai开关状态
            thing_name = CommonService.query_serial_with_uid(uid)  # 存在序列号则为使用序列号作为物品名
            topic_name = 'ansjer/generic/{}'.format(thing_name)

            if status == 0:  # 关闭
                # mqtt通知设备关闭AI识别功能
                msg = {'commandType': 'AIDisable'}
                req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
                if not req_success:
                    return response.json(10044)
                ai_service_qs.update(**qs_data)
                return response.json(0)
            elif status == 1:  # 开启
                # 更新或创建uid_push数据
                uid_push_qs = UidPushModel.objects.filter(userID_id=user_id, m_code=m_code, uid_set__uid=uid)
                uid_push_data = {
                    'appBundleId': appBundleId,
                    'app_type': app_type,
                    'push_type': push_type,
                    'token_val': token_val,
                    'updTime': nowTime,
                    'lang': lang,
                    'tz': tz
                }

                if uid_push_qs.exists():
                    uid_push_qs.update(**uid_push_data)
                else:
                    uid_push_data['uid_set_id'] = uid_set_id
                    uid_push_data['userID_id'] = user_id
                    uid_push_data['m_code'] = m_code
                    uid_push_data['addTime'] = nowTime
                    UidPushModel.objects.create(**uid_push_data)
                if appBundleId == 0 or appBundleId == '0':
                    LOGGER.info('AiService/changeaistatus接口推送数据：{}'.format(request_dict))
                etkObj = ETkObject(etk='')
                etk = etkObj.encrypt(uid)

                # mqtt通知设备开启AI识别功能
                push_url = DETECT_PUSH_DOMAINS
                # 欧洲域名固定返回欧洲域名
                if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
                    push_url = 'https://push.zositeche.com/'
                aiIdentificationUrl = '{}AiService/identification'.format(push_url)
                msg = {
                    'commandType': 'AIEnable',
                    'payload': {
                        'etk': etk,
                        'endTime': endTime,
                        'aiIdentificationUrl': aiIdentificationUrl,
                    }
                }
                req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
                if not req_success:
                    return response.json(10044)
                ai_service_qs.update(**qs_data)
                return response.json(0, {'aiIdentificationUrl': aiIdentificationUrl, 'endTime': endTime, 'etk': etk})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def create_paypal_payment(lang, order_id, price, currency, content):
        """
        创建PayPal支付
        @param lang: 语言
        @param order_id: 订单id
        @param price: 价格
        @param currency: 货币
        @param content: 内容
        @return: pay_dict
        """
        cancel_url = CommonService.get_payment_status_url(lang, 'fail')
        call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id, lang)

        try:
            paypalrestsdk.configure(PAYPAL_CRD)
            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {"payment_method": "paypal"},
                "redirect_urls": {"return_url": call_sub_url, "cancel_url": cancel_url},
                "transactions": [{
                    "item_list": {"items": [
                        {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
                    "amount": {"total": price, "currency": currency},
                    "description": content}]})

            pay_dict = {}
            if not payment.create():  # 创建失败
                return pay_dict
            payment_id = payment['id']  # 获取payment id
            for link in payment.links:
                if link.rel == "approval_url":
                    pay_url = str(link.href)
                    pay_dict['payment_id'] = payment_id
                    pay_dict['pay_url'] = pay_url
                    return pay_dict
            return pay_dict
        except Exception as e:
            print(e)
            return {}

    @staticmethod
    def create_alipay_payment(lang, order_id, price, title, content):
        """
        创建支付宝支付
        @param lang: 语言
        @param order_id: 订单id
        @param price: 价格
        @param title: 标题
        @param content: 内容
        @return: pay_dict
        """
        try:
            aliPayObj = AliPayObject()
            alipay = aliPayObj.conf()
            subject = title + content
            order_string = alipay.api_alipay_trade_wap_pay(
                out_trade_no=order_id,
                total_amount=price,
                subject=subject,
                return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
                notify_url="{}AiService/doAlipayCallBack".format(SERVER_DOMAIN_SSL),
                quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
                passback_params=quote("lang=" + lang)
            )
            if not order_string:
                return {}
            return {'pay_url': aliPayObj.alipay_prefix + order_string}
        except Exception as e:
            print(e)
            return {}

    @staticmethod
    def create_wechat_payment(lang, order_id, price, ip, content):
        """
        创建微信支付
        @param lang: 语言
        @param order_id: 订单id
        @param price: 价格
        @param ip: ip
        @param content: 内容
        @return: pay_dict
        """
        pay_url = "{}AiService/doWechatCallBack".format(SERVER_DOMAIN_SSL)
        try:
            pay = WechatPayObject()
            content = CommonService.Package_Type(1, content)  # AI套餐
            pay.get_parameter(order_id, content, float(price) * 100, ip, pay_url, quote("lang=" + lang))
            sign_params = pay.re_finall(orderid=order_id)
            if not sign_params:
                return {}
            return {'pay_url': pay_url, 'sign_params': sign_params}
        except Exception as e:
            print(e)
            return {}

    @classmethod
    def do_paypal_callback(cls, request_dict, response):
        """
        paypal支付回调
        @param request_dict: 请求数据
        @request_dict paymentId: 支付id
        @request_dict PayerID: 支付账号id
        @request_dict orderID: 订单id
        @request_dict lang: 语言
        @param response: 响应
        @return: response
        """
        logger = logging.getLogger('info')
        logger.info('AI订单---paypal支付回调')
        payment_id = request_dict.get('paymentId', None)
        payer_id = request_dict.get('PayerID', None)
        order_id = request_dict.get('orderID', None)
        lang = request_dict.get('lang', 'en')

        if not order_id:
            pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
            return HttpResponseRedirect(pay_failed_url)

        # redis加锁，防止订单重复
        redis_obj = RedisObject()
        isLock = redis_obj.CONN.setnx(order_id + 'creating_ai_order', 1)
        redis_obj.CONN.expire(order_id + 'creating_ai_order', 60)
        if not isLock:
            return response.json(5)

        order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
        if not order_qs.exists():
            return response.json(173)

        try:
            paypalrestsdk.configure(PAYPAL_CRD)
            payment = paypalrestsdk.Payment.find(payment_id)
            payer = payment.execute({'payer_id': payer_id})
            if not payer:
                pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
                redis_obj.del_data(key=order_id + 'creating_ai_order')
                return HttpResponseRedirect(pay_failed_url)
            return cls.payment_success(order_id, lang, order_qs, redis_obj)
        except Exception as e:
            logger.info('AI订单paypal支付回调异常:{}'.format(repr(e)))
            order_qs.update(status=10)
            pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
            redis_obj.del_data(key=order_id + 'creating_ai_order')
            return HttpResponseRedirect(pay_failed_url)

    @classmethod
    def do_alipay_callback(cls, request_dict, response):
        """
        支付宝支付回调
        @param request_dict: 请求数据
        @param response: 响应
        @return: response
        """
        logger = logging.getLogger('info')
        logger.info('AI订单---支付宝支付回调')

        data = request_dict.dict()
        passback_params = data['passback_params']
        params = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
        lang = params['lang']
        signature = data['sign']
        data.pop('sign')
        order_id = data['out_trade_no']

        # redis加锁，防止订单重复
        redis_obj = RedisObject()
        isLock = redis_obj.CONN.setnx(order_id + 'creating_ai_order', 1)
        redis_obj.CONN.expire(order_id + 'creating_ai_order', 60)
        if not isLock:
            return response.json(5)

        order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
        if not order_qs.exists():
            return response.json(173)

        try:
            alipay_obj = AliPayObject()
            alipay = alipay_obj.conf()
            success = alipay.verify(data, signature)
            if not success or data['trade_status'] not in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
                return response.json(0, signature)
            return cls.payment_success(order_id, lang, order_qs, redis_obj)
        except Exception as e:
            logger.info('AI订单支付宝支付回调异常:{}'.format(repr(e)))
            order_qs.update(status=10)
            redis_obj.del_data(key=order_id + 'creating_ai_order')
            pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
            redis_obj.del_data(key=order_id + 'creating_ai_order')
            return HttpResponseRedirect(pay_failed_url)

    @classmethod
    def do_wechat_callback(cls, request, response):
        """
        微信支付回调
        @param request: 请求体
        @param response: 响应
        @return: response
        """
        logger = logging.getLogger('info')
        logger.info('AI订单---微信支付回调')

        pay = WechatPayObject()
        data = pay.weixinpay_call_back(request.body)
        attach = data["attach"]
        params = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
        lang = params['lang']
        trade_status = data['result_code']  # 业务结果  SUCCESS/FAIL
        order_id = data['out_trade_no']  # 商户订单号

        # redis加锁，防止订单重复
        redis_obj = RedisObject()
        isLock = redis_obj.CONN.setnx(order_id + 'creating_ai_order', 1)
        redis_obj.CONN.expire(order_id + 'creating_ai_order', 60)
        if not isLock:
            return response.json(5)

        order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
        if not order_qs.exists():
            return response.json(173)
        try:
            if trade_status != 'SUCCESS':
                order_qs.update(status=10)
                return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL'}))
            check_sign = pay.get_notifypay(data)
            if not check_sign:
                return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))

            return cls.payment_success(order_id, lang, order_qs, redis_obj, True)
        except Exception as e:
            order_qs.update(status=10)
            redis_obj.del_data(key=order_id + 'creating_ai_order')
            return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))

    @staticmethod
    def payment_success(order_id, lang, order_qs, redis_obj, is_wechat_pay=False):
        """
        支付成功
        @param order_id: 订单id
        @param lang: 语言
        @param order_qs: 订单QuerySet对象
        @param redis_obj: redis对象
        @param is_wechat_pay: 是否为微信支付
        @return: HttpResponse or HttpResponseRedirect
        """
        now_time = int(time.time())
        order_list = order_qs.values('UID', 'channel', 'commodity_code', 'ai_rank__effective_day', 'isSelectDiscounts',
                                     'userID__userID', 'userID__username', 'coupon_id')
        userid = order_list[0]['userID__userID']
        username = order_list[0]['userID__username']
        UID = order_list[0]['UID']
        channel = order_list[0]['channel']
        effective_day = order_list[0]['ai_rank__effective_day']

        ai_service_qs = AiService.objects.filter(Q(uid=UID), Q(channel=channel), Q(use_status=1))
        ai_service_dict = {'uid': UID,
                           'channel': channel,
                           'detect_status': 1,
                           'addTime': now_time,
                           'updTime': now_time,
                           }
        if ai_service_qs.exists():  # 有正在使用的套餐,套餐结束时间保存为套餐有效期
            ai_service_dict['endTime'] = effective_day * 24 * 60 * 60
        else:
            ai_service_dict['use_status'] = 1
            ai_service_dict['endTime'] = now_time + effective_day * 24 * 60 * 60
        with transaction.atomic():
            # 更新设备主用户
            Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster=''). \
                update(vodPrimaryUserID=userid, vodPrimaryMaster=username)
            # 更新订单数据,返回支付成功url
            order_qs.update(status=1, updTime=now_time)
            # 创建AiService数据
            AiService.objects.create(**ai_service_dict)

        pay_success_url = CommonService.get_payment_status_url(lang, 'success')
        redis_obj.del_data(key=order_id + 'creating_ai_order')
        if is_wechat_pay:
            return HttpResponse("<xml>\
              <return_code><![CDATA[SUCCESS]]></return_code>\
              <return_msg><![CDATA[OK]]></return_msg>\
            </xml>")
        else:
            return HttpResponseRedirect(pay_success_url)
