import { Application, BackendSession, pinus } from 'pinus';
import { genCode, getRandSingleEelm, resResult } from '../../../pubUtils/util';
import { STATUS } from '../../../consts/statusCode';
import { ORDER_STATE, PAY_TYPE } from '../../../consts';
import _ = require('underscore');
import { dicRMB } from '../../../pubUtils/dictionary/DicRMB';
import { getActivityById } from '../../../services/activity/activityService';
import { UserOrderModel } from '../../../db/UserOrder';
import { settleOrder, settleOrderAli, settleOrderFromHandler, settleOrderWx } from '../../../services/orderService';
import { getActivityProducts, getParamStr } from '../../../services/gmService';
import { ActivityGroupModel } from '../../../db/ActivityGroup';
import { Receiver } from '../../../db/GMMail';
import { getRoleOnlineInfo } from '../../../services/redisService';
import { RoleModel } from '../../../db/Role';

export interface Cascader {
    value: number|string;
    label: number|string;
    children?: Cascader[];
}

export default function (app: Application) {
    return new GmOrderHandler(app);
}

export class GmOrderHandler {
    constructor(private app: Application) {
    }

    async getActivitiesCanBuy(msg: { serverId: number }, session: BackendSession) {
        const { serverId } = msg;

        let groups = await ActivityGroupModel.findByServerId(serverId);
        let result: Cascader[] = [];
        for (let groupData of groups) {
            let activities: Cascader[] = [];
            for (let activityId of groupData.activities) {
                let activityData = await getActivityById(activityId);
                if(!activityData) continue;
                let products = getActivityProducts(activityData);
                if(products) {
                    let children = products.filter(cur => !!cur);
                    if(children.length > 0) {
                        activities.push({
                            value: activityData.activityId,
                            label: activityData.name,
                            children
                        });
                    }
                }
            }
            if(activities.length > 0) {
                result.push({
                    value: groupData.groupId,
                    label: groupData.groupName,
                    children: activities
                });
            }
        }
        
        return resResult(STATUS.SUCCESS, result);
    }

    /**
   * @description 虚拟充值
   * @param {BackendSession} session
   * @memberof orderHandler
   */
     async applyOrder(msg: { serverId: number, activityId: (number|string)[], receiver: Receiver[] }, session: BackendSession) {
        const { activityId: activityIds, receiver } = msg;
        let activityId = <number>activityIds[1];
        let productID = <string>activityIds[2];

        let payType = PAY_TYPE.TEST
        //如果有特殊情况，activityId可为0
        if (!productID || !_.isString(productID)) {
            return resResult(STATUS.WRONG_PARMS);
        }

        //商品价格信息
        let productInfo = dicRMB.get(productID)
        if (!productInfo) {
            console.log('productID', productID)
            return resResult(STATUS.NO_PRODUCT_ID);
        }

        let price = productInfo.price;//价格
        let productType = productInfo.type;//类型
        let message = productInfo.message;//商品信息
        let localOrderID = genCode(32);//本地订单号
        let orderID = '';//平台订单号
        let sdkOrderInfo = null;//客户端需要的平台订单信息

        let activityData = await getActivityById(activityId);
        if (!activityData) return resResult(STATUS.ACTIVITY_MISSING);

        let results = [];
        for(let { roleId, serverId } of receiver) {
            let role = await RoleModel.findByRoleId(roleId);
            if(!role && role.serverId != serverId) {
                results.push(resResult(STATUS.ROLE_NOT_FOUND));
                continue;
            }
            let paramStr = await getParamStr(activityData, productID, role);
            let orderInfo = await UserOrderModel.applyOrder(serverId, roleId, productID, localOrderID, orderID, price, payType, activityId, paramStr, message, false);

            //订单成功
            if(!orderInfo) {
                results.push(resResult(STATUS.NO_ORDER));
                continue;
            }
            let onlineUser = await getRoleOnlineInfo(roleId);
            let result = await settleOrder(orderInfo, serverId, onlineUser?.sid);
            orderInfo = await UserOrderModel.success(roleId, localOrderID, JSON.stringify(result));
            console.log(`测试支付完成!!!!!!!!!!!!!  serverId:${serverId}, productID:${productID}, productType:${productType}, roleId:${roleId}, localOrderID:${localOrderID}, payType:${payType}`)
            results.push(resResult(STATUS.SUCCESS));
        }

        let findResultErrCode = results.find(cur => cur.code != 0);
        if(!findResultErrCode) {
            return resResult(STATUS.SUCCESS);
        } else {
            return findResultErrCode;
        }
    }


    /**
   * @description 补单
   * @param {BackendSession} session
   * @memberof orderHandler
   */
    async reCallOrder(msg: { localOrderID: string }, session: BackendSession) {

        let sid = session.get('sid');
        const { localOrderID } = msg;
        
        if (!localOrderID || !_.isString(localOrderID)) {
            return resResult(STATUS.WRONG_PARMS);
        }
        let orderInfo = await UserOrderModel.findOrder(localOrderID);
        if (!orderInfo) {
            return resResult(STATUS.NO_ORDER);
        }

        if(orderInfo.state == ORDER_STATE.RESULT_SUCCESS) {
            return resResult(STATUS.DUPLICATE_ORDER);
        }
        //商品价格信息
        let productInfo = dicRMB.get(orderInfo.productID)
        if (!productInfo) {
            console.log(orderInfo.productID)
            return resResult(STATUS.NO_PRODUCT_ID);
        }

        let order = await UserOrderModel.findOrder(localOrderID);

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

        orderInfo = await UserOrderModel.findOrder(localOrderID);

        //订单成功
        console.log('结算完成', localOrderID)
        let res: any = {};
        try {
            res = orderInfo.rewardResult? JSON.parse(orderInfo.rewardResult): {};
        } catch(e) {
            console.log('order rewardResult', e);
        }
        if(res.code && res.code != 0) {
            return resResult(STATUS.APPLY_ORDER_ERROR);
        }
        
        return resResult(STATUS.SUCCESS, {
            ...res, 
            price: orderInfo.price,
            state: orderInfo.state,
            localOrderID: orderInfo.localOrderID
        });
    }
}