import { UserOrderModel, UserOrderModelType } from '../db/UserOrder';
import { ACTIVITY_TYPE, ORDER_STATE, STATUS, TASK_TYPE, TA_EVENT, TA_USERSET_TYPE } from '../consts';
import { dicRMB } from '../pubUtils/dictionary/DicRMB';
import { makeYuanbaoShopReward } from './activity/yuanbaoService';
import { RoleModel } from '../db/Role';
import { makeMonthlyTicketReward } from './activity/monthlyTicketService';
import { makeSignInVIP } from './activity/signInService';
import { makeDailyRMBGiftsReward } from './activity/dailyRMBGiftsService';
import { makePopUpShopReward } from './activity/popUpShopService';
import { ActivityModel, ActivityModelType } from '../db/Activity';
import { ActivityFirstGiftModel } from '../db/ActivityFirstGift';
import { ServerlistModel } from '../db/Serverlist';
import { makeGrowthFund } from './activity/growthFundService';
import { makeLimitPackageReward } from './activity/limitPackageService';
import { makeShop } from './activity/treasureHuntService';
import { makeSelfServerShop } from './activity/selfServiceShopActivityService';
import { makeRefreshShopReward } from './activity/refreshShopService';
import { ActivityMonopolyModel, ActivityMonopolyModelType } from '../db/ActivityMonopoly';
import { ActivityMonopolyLandModel, ActivityMonopolyLandModelType } from '../db/ActivityMonopolyLand';
import { pinus } from 'pinus';
import { resResult } from '../pubUtils/util';
import { checkOrderWX } from './pay/weixinPay';
import { addRechargeMoney } from './activity/rechargeMoneyService';
import { addVipRechargeMoney } from './activity/vipRechargeMoneyService';
import { checkActivityTask } from './taskService';
import { checkOrderALI } from './pay/aliPay';
import { getRoleOnlineInfo } from './redisService';
import { PayCallback37Data } from '../domain/sdk';
import { reportTAEvent, reportTAUserSet } from './sdkService';
import { savePayLog } from '../pubUtils/logUtil';


/**
 * 结算账单 
 * @param localOrderID 本地订单号
 */
export async function makeOrder(orderInfo: UserOrderModelType, sid: string) {

    //商品价格信息
    let productInfo = dicRMB.get(orderInfo.productID)


    let productType = productInfo.type;//类型
    let price = orderInfo.price;//下单时的价格
    let payType = orderInfo.payType;//支付类型
    let roleId = orderInfo.roleId;//角色

    const roleInfo = await RoleModel.increaseTotalPay(roleId, price);

    let rewardResult: any = { code: 0, data: null };

    //首冲礼包
    {
        let { activityGroupId } = await ServerlistModel.findByServerId(orderInfo.serverId);
        let activityArray: ActivityModelType[] = await ActivityModel.findOpenActivityByType(activityGroupId, ACTIVITY_TYPE.FIRST_GIFT, new Date())
        for (let obj of activityArray) {
            await ActivityFirstGiftModel.begin(obj.activityId, roleId);
        }
    }


    switch (productType) {
        case ACTIVITY_TYPE.SIGN_IN_VIP:
            {
                rewardResult = await makeSignInVIP(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.NEW_PLAYER_LIMIT_PACKAGE:
            {
                rewardResult = await makeLimitPackageReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.LIMIT_PACKAGE_SHOP_DAILY:
        case ACTIVITY_TYPE.LIMIT_PACKAGE_SHOP_WEEKLY:
            {
                rewardResult = await makeLimitPackageReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.YUAN_BAO_SHOP:
            {
                rewardResult = await makeYuanbaoShopReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }

        case ACTIVITY_TYPE.MONTHLY_TICKET_1:
        case ACTIVITY_TYPE.MONTHLY_TICKET_2:
            {
                rewardResult = await makeMonthlyTicketReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.DAILY_RMB_GIFTS:
            {
                rewardResult = await makeDailyRMBGiftsReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.POP_UP_SHOP://弹出礼包
            {
                rewardResult = await makePopUpShopReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID, orderInfo.paramStr)
                break;
            }
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN_VIP: //主线成长基金（高阶）
            {
                rewardResult = await makeGrowthFund(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.GROWTH_FUND_TOWER_VIP://镇念塔成长基金（高阶）
            {
                rewardResult = await makeGrowthFund(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.GROWTH_FUND_MAIN_ELITE_VIP://精英成长基金（高阶）
            {
                rewardResult = await makeGrowthFund(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.TREASURE_HUNT://寻宝奇兵活动-每日物资商店
            {
                rewardResult = await makeShop(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.SELF_SERVICE_SHOP://自选商店-购买礼包
            {
                rewardResult = await makeSelfServerShop(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID)
                break;
            }
        case ACTIVITY_TYPE.REFRESH_SHOP://通用的刷新商店（分页，可刷新，限制购买次数，支持rmb与资源兑换）
            {
                if (orderInfo.paramStr) {//大富翁商店结算
                    let paramObj = JSON.parse(orderInfo.paramStr);
                    let activityId = paramObj.activityId;//大富翁活动id；   orderInfo.activityId是大富翁中的商店活动id
                    if (activityId) {
                        let playerMonopolyData: ActivityMonopolyModelType = await ActivityMonopolyModel.findData(orderInfo.serverId, activityId, roleId);
                        let playerLandData: ActivityMonopolyLandModelType = await ActivityMonopolyLandModel.findDataByPosition(orderInfo.serverId, activityId, roleId, playerMonopolyData.curPosition);
                        let roundIndex = playerLandData.stopCount;
                        rewardResult = await makeRefreshShopReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID, roundIndex)
                        break;
                    }
                }
                //正常商店结算
                rewardResult = await makeRefreshShopReward(roleId, roleInfo.roleName, sid, orderInfo.serverId, orderInfo.activityId, orderInfo.productID, 0)
                break;
            }
        default:
            rewardResult = STATUS.ERROR_TYPE;
            break;
    }
    pinus.app.get('channelService').pushMessageByUids('onPlayerDataChange', resResult(STATUS.SUCCESS, {
        totalPay: roleInfo.totalPay
    }), [{ uid: roleId, sid }]);
    
    return rewardResult
}

export async function settleOrder(order: UserOrderModelType, serverId: number, sid?: string) {
    if(!sid) {
        let onlineUser = await getRoleOnlineInfo(order.roleId);
        sid = onlineUser.sid;
    }
    //结算奖励
    let result = await makeOrder(order, sid);
    if (result.code !== 0) {//结算失败
        console.log(`支付失败..... ${JSON.stringify(result)}`)
        reportTAEvent(order.roleId, TA_EVENT.RECHARGE_FAIL, { pay_id: order.localOrderID, charge_id: order.productID, pay_name: order.message, pay_amount: order.price, pay_channel: order.payType })
        savePayLog(order);
        return resResult(result);
    }
    //推送
    console.log('***** settleOrder', order.roleId, sid)
    if(!!sid) {
        pinus.app.channelService.pushMessageByUids('onOrder', resResult(STATUS.SUCCESS, {
            ...result.data,
            price: order.price,
            state: order.state,
            localOrderID: order.localOrderID
        }), [{ uid: order.roleId, sid }]);
    }
    //活动统计
    await addRechargeMoney(order.roleId, serverId, order.price);
    await addVipRechargeMoney(order.roleId, serverId, order.price);
    //成长任务
    await checkActivityTask(serverId, sid, order.roleId, TASK_TYPE.ACTIVITY_RMB, order.price, { activityId: order.activityId })
    reportTAEvent(order.roleId, TA_EVENT.RECHARGE_SUCCESS, { pay_id: order.localOrderID, charge_id: order.productID, pay_name: order.message, pay_amount: order.price, pay_channel: order.payType })
    reportTAUserSet(TA_USERSET_TYPE.SET_ONCE, order.roleId, { first_pay_time: new Date() });
    reportTAUserSet(TA_USERSET_TYPE.SET, order.roleId, { last_pay_time: new Date() });
    reportTAUserSet(TA_USERSET_TYPE.ADD, order.roleId, { total_revenue: order.price });
    savePayLog(order);
    return result.data;
}

export async function settleOrderWx(order: UserOrderModelType, serverId: number, sid: string) {

    if (order.state == ORDER_STATE.RESULT_SUCCESS) {
        return STATUS.DUPLICATE_ORDER;
    }
    order = await UserOrderModel.check(order.roleId, order.localOrderID);
    if (!order) {
        return STATUS.DUPLICATE_ORDER;
    }

    let weixinResult = await checkOrderWX(order.localOrderID);
    if (weixinResult.code == 0) {
        console.log('微信订单查询失败')
        return STATUS.ORDER_ERROR;
    }
    if (parseInt(weixinResult.data.total_fee) / 100 != order.price) {
        console.log('订单价格错误')
        return STATUS.PRICE_ERROR;
    }
    if (weixinResult.data.trade_state != "SUCCESS" ||
        weixinResult.data.result_code != "SUCCESS" ||
        weixinResult.data.return_code != "SUCCESS") {
        return STATUS.NO_PAY;
    }    

    let result = await  settleOrder(order, serverId, sid);
    order = await UserOrderModel.success(order.roleId, order.localOrderID, result);

    return STATUS.SUCCESS
}

export async function settleOrderAli(order: UserOrderModelType, serverId: number, sid: string) {
    if (order.state == ORDER_STATE.RESULT_SUCCESS) {
        return STATUS.DUPLICATE_ORDER;
    }
    let aliResult = await checkOrderALI(order.localOrderID);
    if (aliResult.code == 0) {
        console.log('支付宝订单查询失败')
        return STATUS.ORDER_ERROR;
    }
    if (parseInt(aliResult.data.total_amount) != order.price) {
        console.log('订单价格错误')
        return STATUS.PRICE_ERROR;
    }
    if (aliResult.data.trade_status != "TRADE_SUCCESS") {
        return STATUS.NO_PAY;
    }
    let aliOrderID = aliResult.data.trade_no;
    let result = await settleOrder(order, serverId, sid);
    await UserOrderModel.saveOrderID(order.roleId, order.localOrderID, aliOrderID, result);

    return STATUS.SUCCESS
}

export async function settleOrderFromRedisPub(message: string) {
    console.log('**********settleOrderFromRedisPub*******')
    console.log('message: ', message);

    let params: PayCallback37Data;
    try {
        params = JSON.parse(message);
    } catch(e) {
        return false;
    }

    let order = await UserOrderModel.findOrder(params.order_no);
    if(!order || order.state != ORDER_STATE.CHECK_ORDER) {
        console.log('订单状态错误');
        return false;
    }
    if(order.roleId != params.actor_id) {
        console.log('订单玩家错误');
        return false;
    }
    if(order.price != parseFloat(params.money)) {
        console.log('订单金额错误');
        return false;
    }

    let aliOrderID = params.order_id;

    let result = await settleOrder(order, params.sid);
    await UserOrderModel.saveOrderID(order.roleId, order.localOrderID, aliOrderID, JSON.stringify(result));

    return true
}