import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { ORDER_STATE } from '../consts';
import { SearchOrderParam } from '../domain/backEndField/search';

/**
  * 玩家充值订单 
*/
@index({ localOrderID: 1 })

export default class UserOrder extends BaseModel {

    @prop({ required: true })
    serverId: number;		    // 区号
    @prop({ required: true })
    roleId: string;				// 用户id
    @prop({ required: true })
    productID: string;			// 商品
    @prop({ required: true })
    orderID: string;			// 平台订单号
    @prop({ required: true })
    rewardResult: string;			// 奖励结果
    @prop({ required: true })
    localOrderID: string;	    // 本地订单号
    @prop({ required: true })
    payType: number;	        // 支付类型    PAY_TYPE
    @prop({ required: true })
    price: number;				// 价格
    @prop({ required: true })
    state: number;				// 订单状态 ORDER_STATE 3.支付成功并结算
    @prop({ required: true })
    message: string;	        // 信息
    @prop({ required: true })
    activityId: number;		    // 活动ID
    @prop({ required: true })
    paramStr: string;	        // 订单参数
    @prop({ required: true })
    useVoucher: boolean;         // 使用代金券
    @prop({ required: true })
    callbackMsg: string;	        // 信息


    //保存平台订单号
    public static async saveOrderID(roleId: string, localOrderID: string, orderID: string, rewardResult: string) {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID },
            { $set: { orderID, rewardResult, state: ORDER_STATE.RESULT_SUCCESS } },
            { new: true }).lean(true);
        return result;
    }

    //校验订单
    public static async check(roleId: string, localOrderID: string, callbackMsg: string = '') {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID, state: { $ne: ORDER_STATE.RESULT_SUCCESS } },
            { $set: { state: ORDER_STATE.CHECK_ORDER, callbackMsg } },
            { new: true }).lean(true);
        return result;
    }

    //订单支付失败
    public static async fail(roleId: string, localOrderID: string, callbackMsg: string = '') {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID, state: { $ne: ORDER_STATE.RESULT_SUCCESS } },
            { $set: { state: ORDER_STATE.RESULT_FAIL, callbackMsg } },
            { new: true }).lean(true);
        return result;
    }

    //订单支付成功
    public static async success(roleId: string, localOrderID: string, rewardResult: string, callbackMsg: string = '') {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID, state: { $ne: ORDER_STATE.RESULT_SUCCESS } },
            { $set: { state: ORDER_STATE.RESULT_SUCCESS, rewardResult, callbackMsg } },
            { new: true }).lean(true);
        return result;
    }

    // 准备退款
    public static async startRefund(roleId: string, localOrderID: string, callbackMsg: string = '') {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID },
            { $set: { state: ORDER_STATE.CHECK_TO_REFUND, callbackMsg } },
            { new: true }).lean(true);
        return result;
    }

    // 退款
    public static async refund(roleId: string, localOrderID: string, callbackMsg: string = '') {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ roleId, localOrderID },
            { $set: { state: ORDER_STATE.REFUND, callbackMsg } },
            { new: true }).lean(true);
        return result;
    }

    //查询成功订单详情
    public static async findSuccessOrderByProductID(productID: string, roleId: string, activityId: number) {
        let result: UserOrderModelType[] = await UserOrderModel.find({ productID, roleId, activityId, state: ORDER_STATE.RESULT_SUCCESS }).lean(true);
        return result;
    }

    //查询订单详情
    public static async findOrderByProductID(productID: string, roleId: string, activityId: number) {
        let result: UserOrderModelType[] = await UserOrderModel.find({ productID, roleId, activityId }).lean(true);
        return result;
    }

    //查询订单详情
    public static async findPlayerOrder(productID: string, roleId: string, activityId: number, limit: number) {
        let result: UserOrderModelType[] = await UserOrderModel.find({ productID, roleId, activityId }, {}).limit(limit).sort({ createdAt: -1 }).lean(true);
        return result;
    }

    //查询订单详情
    public static async findOrderByActivityID(activityId: number, roleId: string,) {
        let result: UserOrderModelType[] = await UserOrderModel.find({ activityId, roleId, state: ORDER_STATE.RESULT_SUCCESS }).lean(true);
        return result;
    }

    //查询订单详情
    public static async findOrder(localOrderID: string) {
        let result: UserOrderModelType = await UserOrderModel.findOne({ localOrderID }).lean(true);
        return result;
    }

    //查询订单详情
    public static async findOrderList(serverId: number, roleId: string, begin: number, count: number) {
        let result: UserOrderModelType[] = await UserOrderModel.find({ serverId, roleId, state: ORDER_STATE.RESULT_SUCCESS }, { price: 1, createdAt: 1, productID: 1 }).skip(begin).limit(count).sort({ createdAt: -1 }).lean(true);
        return result;
    }


    //新增订单
    public static async applyOrder(serverId: number, roleId: string, productID: string, localOrderID: string, orderID: string, price: number, payType: number, activityId: number, paramStr: string, message: string, useVoucher: boolean) {
        let result: UserOrderModelType = await UserOrderModel.findOneAndUpdate({ serverId, roleId, productID, localOrderID, orderID, payType, activityId },
            { $set: { price, state: ORDER_STATE.APPLY, message, paramStr: paramStr ? paramStr : '', useVoucher } },
            { upsert: true, new: true }).lean(true);
        return result;
    }

  private static getSearchObj(form: SearchOrderParam) {
    let searchObj = {};
    if(form.roleId != undefined) searchObj['roleId'] = form.roleId;
    if(form.localOrderID != undefined) searchObj['localOrderID'] = form.localOrderID;
    if(form.orderID != undefined) searchObj['orderID'] = form.orderID;
    if(form.productID != undefined) searchObj['productID'] = form.productID;
    if(form.payType != undefined) searchObj['payType'] = form.payType;
    if(form.state != undefined) searchObj['state'] = form.state;
    if (form.createTimeStart && form.createTimeEnd) {
        searchObj['createdAt'] = { $lte: new Date(form.createTimeEnd * 1000), $gte: new Date(form.createTimeStart * 1000) };
    }
    return searchObj
  }

  public static async findByCondition(page: number, pageSize: number, sortField: string = 'updatedAt', sortOrder: string = 'descend', form: SearchOrderParam = {}) {

    let searchObj = this.getSearchObj(form);
    let sort = {};
    if(sortField && sortOrder) {
        if(sortOrder == 'ascend') {
            sort[sortField] = 1;
        } else if (sortOrder == 'descend') {
            sort[sortField] = -1;
        }
    }
    const result: UserOrderModelType[] = await UserOrderModel.find(searchObj).limit(pageSize).skip((page - 1) * pageSize).sort(sort).select('+sort +showStartTime +showEndTime +isEnable').lean({ getters: true, virtuals: true });
    return result;

  }

  public static async countByCondition(form: SearchOrderParam = {}) {

      let searchObj = this.getSearchObj(form);
      const result = await UserOrderModel.count(searchObj);
      return result;
  }
}

export const UserOrderModel = getModelForClass(UserOrder);

export interface UserOrderModelType extends Pick<DocumentType<UserOrder>, keyof UserOrder> { }
export type UserOrderModelTypeParam = Partial<UserOrderModelType>; // 将所有字段变成可选项