
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const _ = require('lodash');
const TypeConfig = {
    blacklist: 1,
    callrisk: 2
}
const TypeConfigFlip = {
    1: 'blacklist',
    2: 'callrisk',
}

class PreferentialService extends Service {

    /**
     * 获取用户可以享受的优惠信息
     * @param {*} type 用户当前操作的订单类型黑名单blacklist通话callrisk
     */
    async getPreferential(type) {
        const { ctx } = this;
        //找到用户三日内已支付最新的另一个类型的订单,判断上次使用的优惠类型,互斥即可
        if (!TypeConfig.hasOwnProperty(type)) {
            ctx.failed('undefined type in getPreferential');
        }
        let anotherType = type === 'blacklist' ? 'callrisk' : 'blacklist';
        let historyFilter = {
            where: {
                user_id: ctx.userId,
                type: TypeConfig[anotherType],
                valid: 1,
                state: '已支付',
                state_time: { $gte: moment().subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss') }
            },
            order: [['state_time', 'desc']]
        }
        let userLastOrder = await ctx.prometheusModel.CreditOrder.findOne(historyFilter);

        let preFilter = {
            where: {
                alias: '',
                type: TypeConfig[type],
                valid: 1,
            },
            order: [['id', 'desc']]
        }
        if (userLastOrder === null) {
            preFilter.where.alias = 'limit';
        } else {
            let lastPre = await ctx.prometheusModel.CreditOrderPreferential.findOne({ where: { id: userLastOrder.preferential_id } });
            preFilter.where.alias = lastPre === null ? 'limit' : (lastPre.alias === 'combina' ? 'limit' : 'combina');
        }

        let preferential = await ctx.prometheusModel.CreditOrderPreferential.findOne(preFilter);
        return preferential;

    }

    /**
     * 当前各种类型的报告是否有优惠
     */
    async havePreferential() {
        const { ctx } = this;
        let ret = {
            blacklist: false,
            callrisk: false
        }
        let filter = {
            attributes: ['type'],
            where: {
                valid: 1
            }
        }
        let preferentialList = await ctx.prometheusModel.CreditOrderPreferential.findAll(filter);
        if (preferentialList !== undefined) {
            for (let i in preferentialList) {
                if (TypeConfigFlip.hasOwnProperty(preferentialList[i].type)) {
                    ret[TypeConfigFlip[preferentialList[i].type]] = true;
                }
            }
        }
        return ret;
    }







}

module.exports = PreferentialService;
