
'use strict';

const Service = require('egg').Service;

class HomeService extends Service {


    /**
     * 我的信用首页
     */
    async home() {
        const { ctx } = this;
        let ret = {
            is_login: false,
            have_history: false,
            have_be_pay: false,
            be_pay: {
                send: 'tab',
                order_id: null,
                msg: '',
            },
            preferential: {
                blacklist: false,
                callrisk: false,
            }
        }
        if (!ctx.userId) {
            return ret;
        }
        ret.is_login = true;

        let taskList = [
            ctx.service.credit.order.getHistoryOrders('blacklist'),
            ctx.service.credit.order.getHistoryOrders('callrisk')
        ];

        let retList = await Promise.all(taskList).then(result => {
            return result;
        }).catch(error => {
            ctx.failed(error);
        });
        ctx.logger.info('home-retList:' + JSON.stringify(retList));

        let historyAmount = 0;
        for (let i in retList) {
            if (retList[i] === null) {
                continue;
            }
            historyAmount += retList[i].worth_h.length + retList[i].worth_l.length;
        }
        ret.have_history = historyAmount > 0 ? true : false;

        let bePayOrder = [];
        if (historyAmount > 0) {
            let blacklist = retList[0].worth_h;
            let callrisk = retList[1].worth_h;
            for (let i in blacklist) {
                if (['待支付', '支付中'].includes(blacklist[i].state)) {
                    bePayOrder.push(blacklist[i]);
                }
            }
            for (let i in callrisk) {
                if (['待支付', '支付中'].includes(callrisk[i].state)) {
                    bePayOrder.push(callrisk[i]);
                }
            }
            ret.be_pay.msg = '您有' + bePayOrder.length + '份报告待支付';
        }

        if (bePayOrder.length > 0) {
            ret.have_be_pay = true;
            if (bePayOrder.length === 1) {
                ret.be_pay.send = bePayOrder[0].type;
                ret.be_pay.order_id = bePayOrder[0].order_id;
            } else {
                ret.be_pay.send = 'tab';
            }
        }

        //判断是否有优惠信息
        let havePreferential = await ctx.service.credit.preferential.havePreferential();
        ret.preferential = havePreferential;
        return ret;
    }







}

module.exports = HomeService;
