
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const _ = require('lodash');
const RiskConfig = {
    low: {
        standard: '低',
        msg: '您的风险指数较低，有利于机构对您的申贷评估，请继续保持良好的信用行为。',
    },
    medium: {
        standard: '中',
        msg: '您的风险指数中等，请合理申贷，保持良好还款习惯，避免申贷过多影响个人信用。',
    },
    high: {
        standard: '高',
        msg: '您的风险指数较高， 再次申贷容易被拒，建议3个月内不再申请贷款，并养成良好的还款习惯。',
    },
}
const DtldConfig = {
    empty: '您最近6个月没有贷款记录，说明您是在自己的偿还范围内理性借贷，请继续保持。',
    less: '您最近很少进行贷款申请，说明您比较合理地利用和分配资金，有利于提高您的个人信用。',
    more: '您最近6个月网贷申请次数与平台较多，存在多头共债风险，被拒概率极高。建议您在6个月内申请贷款控制在7次以内。',
}

const IdCardConfig = {
    empty: '您的身份证和手机号暂无关联风险，请继续保持良好的信用行为，保护好您的身份信息，不要轻易将身份证借用给他人。',
    have: '您的XX关联了多个NN，请联系平台更改，并同时保护好您的身份信息，不要轻易将身份证借用给他人。'
}

const DeviceConfig = {
    high: '您的设备关联的XXAPP数量较多，建议合理使用APP，并删除不常使用的APP，以免影响申贷通过率。',
    low: '您的设备有关联XXAPP，建议删除此类APP，以免影响申贷通过率。',
    empty: '您的设备关联APP表现很健康，请继续保持。',
}

class BlacklistService extends Service {

    /**
     * 获取黑名单报告
     * @param {*} id 报告编号 
     */
    async getReport(id) {
        const { ctx } = this;
        if (!ctx.userId) {
            ctx.failed('登录异常');
        }
        let reportData = await ctx.prometheusModel.CreditBlacklistReport.findOne({ where: { id: id } });
        if (reportData === null) {
            ctx.failed('该报告不存在');
        }
        let ret = {
            basic: {
                risk_index: '',
                risk_standard: '',
                msg: '',
                name: reportData.name,
                report_no: reportData.report_no,
                phone: reportData.phone.substring(0, 3) + '****' + reportData.phone.substring(7, 11),//手机号（只展示前三位和后四位）
                age: reportData.age,
                id_card: reportData.id_card.substring(0, 3) + '**********' + reportData.id_card.substring(15, 18),//身份证号（只展示前四位和后四位）
                city: reportData.city || '--',//城市（省-市）
                expire_time: moment(reportData.created_at).add(15, 'days').format('YYYY-MM-DD'),//报告有效期为报告生成日期往后推15天
            },
            blacklist: {
                blacklist_of_internet_loans: reportData.blacklist_of_internet_loans,//是否命中网贷黑名单
                blacklist_of_court_dishonesty: reportData.blacklist_of_court_dishonesty,//是否命中法院失信名单
                blacklist_of_industry: reportData.blacklist_of_industry,//是否命中行业黑名单
                blacklist_of_ds_industry: reportData.blacklist_of_ds_industry,//是否命中电商行业黑名单
                blacklist_of_bx_industry: reportData.blacklist_of_bx_industry,//是否命中保险行业黑名单
                blacklist_of_zc_industry: reportData.blacklist_of_zc_industry,//是否命中租车行业黑名单
                blacklist_of_zf_industry: reportData.blacklist_of_zf_industry,//是否命中三方支付行业黑名单
                blacklist_of_jd_industry: reportData.blacklist_of_jd_industry,//是否命中酒店行业黑名单             
            },
            dtld: {
                dtld_apply_record: 0,//多头申请是不是有记录
                dtld_credit_record: 0,//多头放放款是不是有记录
                reg_count_1month: reportData.reg_count_1month,//近1月注册笔数
                reg_count_3month: reportData.reg_count_3month,//近3月注册笔数
                reg_count_6month: reportData.reg_count_6month,//近6月注册笔数
                consume_reg_count_1month: reportData.consume_reg_count_1month,//近1月消金机构注册笔数
                consume_reg_count_3month: reportData.consume_reg_count_3month,//近3月消金机构注册笔数
                consume_reg_count_6month: reportData.consume_reg_count_6month,//近6月消金机构注册笔数
                loan_reg_count_1month: reportData.loan_reg_count_1month,//近1月网贷机构注册笔数
                loan_reg_count_3month: reportData.loan_reg_count_3month,//近3月网贷机构注册笔数
                loan_reg_count_6month: reportData.loan_reg_count_6month,//近6月网贷机构注册笔数
                consume_reg_platform_count_1month: reportData.consume_reg_platform_count_1month,//近1月注册消金机构数
                consume_reg_platform_count_3month: reportData.consume_reg_platform_count_3month,//近3月注册消金机构数
                consume_reg_platform_count_6month: reportData.consume_reg_platform_count_6month,//近6月注册消金机构数
                loan_reg_platform_count_1month: reportData.loan_reg_platform_count_1month,//近1月注册网贷机构数
                loan_reg_platform_count_3month: reportData.loan_reg_platform_count_3month,//近3月注册网贷机构数
                loan_reg_platform_count_6month: reportData.loan_reg_platform_count_6month,//近6月注册网贷机构数
                reg_platform_count_1month: reportData.reg_platform_count_1month,//近1月注册机构数
                reg_platform_count_3month: reportData.reg_platform_count_3month,//近3月注册机构数
                reg_platform_count_6month: reportData.reg_platform_count_6month,//近6月注册机构数
                credit_count_1month: reportData.credit_count_1month,//近1月放款笔数
                credit_count_3month: reportData.credit_count_3month,//近3月放款笔数
                credit_count_6month: reportData.credit_count_6month,//近6月放款笔数
                credit_amount_1month: await this.dealSection(reportData.credit_amount_1month),//近1月放款金额
                credit_amount_3month: await this.dealSection(reportData.credit_amount_3month),//近3月放款金额
                credit_amount_6month: await this.dealSection(reportData.credit_amount_6month),//近6月放款金额
                credit_closed_count_1month: reportData.credit_closed_count_1month,//近1月已结清放款笔数
                credit_closed_count_3month: reportData.credit_closed_count_3month,//近3月已结清放款笔数
                credit_closed_count_6month: reportData.credit_closed_count_6month,//近6月已结清放款笔数
                credit_closed_amount_1month: await this.dealSection(reportData.credit_closed_amount_1month),//近1月已结清放款金额
                credit_closed_amount_3month: await this.dealSection(reportData.credit_closed_amount_3month),//近3月已结清放款金额
                credit_closed_amount_6month: await this.dealSection(reportData.credit_closed_amount_6month),//近6月已结清放款金额
                consume_credit_count_1month: reportData.consume_credit_count_1month,//近1月消金机构放款笔数
                consume_credit_count_3month: reportData.consume_credit_count_3month,//近3月消金机构放款笔数
                consume_credit_count_6month: reportData.consume_credit_count_6month,//近6月消金机构放款笔数
                loan_credit_count_1month: reportData.loan_credit_count_1month,//近1月网贷机构放款笔数
                loan_credit_count_3month: reportData.loan_credit_count_3month,//近3月网贷机构放款笔数
                loan_credit_count_6month: reportData.loan_credit_count_6month,//近6月网贷机构放款笔数
                consume_credit_platform_count_1month: reportData.consume_credit_platform_count_1month,//近1月放款消金机构数
                consume_credit_platform_count_3month: reportData.consume_credit_platform_count_3month,//近3月放款消金机构数
                consume_credit_platform_count_6month: reportData.consume_credit_platform_count_6month,//近6月放款消金机构数
                loan_credit_platform_count_1month: reportData.loan_credit_platform_count_1month,//近1月放款网贷机构数
                loan_credit_platform_count_3month: reportData.loan_credit_platform_count_3month,//近3月放款网贷机构数
                loan_credit_platform_count_6month: reportData.loan_credit_platform_count_6month,//近6月放款网贷机构数
                credit_platform_count_1month: reportData.credit_platform_count_1month,//近1月放款机构数
                credit_platform_count_3month: reportData.credit_platform_count_3month,//近3月放款机构数
                credit_platform_count_6month: reportData.credit_platform_count_6month,//近6月放款机构数
                msg: '',
            },
            overdue: {//逾期详情
                list: await this.overdueAnalysis(reportData.overdue),
                msg: '',
            },
            six_months: {//近6个月关联风险
                id_card_relevant: {//身份关联风险
                    id_card_relevant_mobilephone_count: reportData.id_card_relevant_mobilephone_count,//身份证关联手机号个数
                    id_card_relevant_device_count: reportData.id_card_relevant_device_count,//身份证关联设备号个数
                    mobilephone_relevant_id_card_count: reportData.mobilephone_relevant_id_card_count,//手机号关联身份证个数
                    msg: '',
                },
                mobilephone_relecvant: {//设备关联风险
                    relevant_loan_app_count_6month: reportData.relevant_loan_app_count_6month,//近6月关联的信贷app个数
                    relevant_gamble_app_count_6month: reportData.relevant_gamble_app_count_6month,//近6月关联的赌博app个数
                    relevant_ip_app_count_6month: reportData.relevant_ip_app_count_6month,//近6月关联的代理ip或篡改gps的app个数
                    relevant_other_app_count_6month: reportData.relevant_other_app_count_6month,//近6月关联的其他app个数                  
                    msg: '',
                }
            },
            report_valid: 0//报告是否失效
        };

        //风险分值计算
        let blacklistScore = (ret.blacklist.blacklist_of_internet_loans === 1 || ret.blacklist.blacklist_of_court_dishonesty === 1) ? 40 : (ret.blacklist.blacklist_of_industry === 1 ? 30 : 0);
        let dtScore = await this.getDtScore(ret.dtld.reg_count_6month, ret.dtld.credit_count_6month);
        let idScore = await this.getIdCardScore(ret.six_months.id_card_relevant.id_card_relevant_mobilephone_count, ret.six_months.id_card_relevant.mobilephone_relevant_id_card_count);
        let appScore = (ret.six_months.mobilephone_relecvant.relevant_ip_app_count_6month > 1 || ret.six_months.mobilephone_relecvant.relevant_gamble_app_count_6month > 1) ? 10 : 0;
        ret.basic.risk_index = blacklistScore + dtScore + idScore + appScore;
        //风险标准计算
        let riskLevel = 'low';
        if (ret.blacklist.blacklist_of_internet_loans === 1 || ret.blacklist.blacklist_of_court_dishonesty === 1 || ret.blacklist.blacklist_of_industry === 1 || ret.basic.risk_index >= 50 || dtScore === 30) {
            riskLevel = 'high';
        } else if (ret.basic.risk_index >= 20 && ret.basic.risk_index < 50) {
            riskLevel = 'medium';
        } else {
            riskLevel = 'low';
        }
        ret.basic.risk_index += '%';
        ret.basic.risk_standard = RiskConfig[riskLevel].standard;
        ret.basic.msg = RiskConfig[riskLevel].msg;

        //多头雷达msg
        let dtldLevel = 'empty';
        let n = 7;
        if (ret.dtld.reg_platform_count_6month === 0) {
            dtldLevel = 'empty';
        } else if (ret.dtld.reg_platform_count_6month < n) {
            dtldLevel = 'less';
        } else {
            dtldLevel = 'more';
        }
        ret.dtld.msg = DtldConfig[dtldLevel];
        //多头雷达的是否有记录判断,前端需要
        if (_.sum([ret.dtld.reg_count_1month, ret.dtld.reg_count_3month, ret.dtld.reg_count_6month, ret.dtld.reg_platform_count_1month, ret.dtld.reg_platform_count_3month, ret.dtld.reg_platform_count_6month]) > 0) {
            ret.dtld.dtld_apply_record = 1;
        }
        if (_.sum([ret.dtld.credit_count_1month, ret.dtld.credit_count_3month, ret.dtld.credit_count_6month, ret.dtld.credit_platform_count_1month, ret.dtld.credit_platform_count_3month, ret.dtld.credit_platform_count_6month]) > 0) {
            ret.dtld.dtld_credit_record = 1;
        }

        //逾期msg
        ret.overdue.msg = '逾期次数过多，逾期天数较长，逾期金额较大等，会被认为你的还款能力弱，贷款申请被拒概率较大。如显示无记录，则未查得逾期记录，或贷款平台没有及时上传你的逾期信息。实际逾期情况，请以个人借贷情况为准。';

        //近六个月msg
        //身份关联
        let idCardLevel = 'empty';
        let idCardNeedSort = [
            {
                n: ret.six_months.id_card_relevant.id_card_relevant_mobilephone_count,
                first: '身份证',
                second: '手机号',
            },
            {
                n: ret.six_months.id_card_relevant.mobilephone_relevant_id_card_count,
                first: '手机号',
                second: '身份证',
            },
            {
                n: ret.six_months.id_card_relevant.id_card_relevant_device_count,
                first: '身份证',
                second: '设备号',
            },
        ];
        let idCardMax = _.orderBy(idCardNeedSort, ['n'], ['desc'])[0];
        if (idCardMax.n >= 2) {
            idCardLevel = 'have';
        } else {
            idCardLevel = 'empty';
        }
        ret.six_months.id_card_relevant.msg = IdCardConfig[idCardLevel].replace(/XX/, idCardMax.first).replace(/NN/, idCardMax.second);

        //设备关联
        let deviceLevel = 'empty';
        let deviceNeedSort = [
            {
                n: ret.six_months.mobilephone_relecvant.relevant_ip_app_count_6month,
                type: '代理ip/篡改GPS类',
            },
            {
                n: ret.six_months.mobilephone_relecvant.relevant_gamble_app_count_6month,
                type: '赌博类'
            },
            {
                n: ret.six_months.mobilephone_relecvant.relevant_loan_app_count_6month,
                type: '信贷类'
            },
        ];
        let deviceMax = _.orderBy(deviceNeedSort, ['n'], ['desc'])[0];
        if (deviceMax.n >= 2) {
            deviceLevel = 'high';
        } else if (deviceMax.n === 1) {
            deviceLevel = 'low';
        } else {
            deviceLevel = 'empty';
        }
        ret.six_months.mobilephone_relecvant.msg = DeviceConfig[deviceLevel].replace(/XX/, deviceMax.type);

        if (!ret.basic.report_no) {
            ret.basic.report_no = await ctx.service.credit.common.getReportNo('blacklist', reportData.id);
            await ctx.prometheusModel.CreditBlacklistReport.update({ report_no: ret.basic.report_no }, { where: { id: reportData.id } });
        }

        //订单是否在有效期内
        ret.report_valid = await ctx.service.credit.order.getReportValid('blacklist', id);

        return ret;
    }

    /**
     * 对逾期的情况处理数据
     * @param {*} overdue 
     */
    async overdueAnalysis(overdue) {
        let ret = [];
        if (!overdue || overdue === '[]') {
            return ret;
        }
        let overdueInfo = JSON.parse(overdue);
        for (let i in overdueInfo) {
            //需要对逾期的金额额外处理
            let amount = '';
            if (['0', 0].includes(overdueInfo[i].overdue_amount)) {
                amount = '0';
            } else if (overdueInfo[i].overdue_amount === '>1000000') {
                amount = '100万以上'
            } else {
                amount = await this.dealSection(overdueInfo[i].overdue_amount);
            }
            let timeLen = overdueInfo[i].overdue_time.length;
            let temp = {
                overdue_date: overdueInfo[i].overdue_date,
                overdue_amount: amount,
                overdue_time: overdueInfo[i].overdue_time.substring(1, timeLen - 1).replace(/\,/, '-') + '天',
                is_settle: overdueInfo[i].is_settle === 'N' ? '否' : '是',
            }
            ret.push(temp);
        }
        return ret;
    }

    /**
     * 处理类似(3000,50000]这样的区间的数字
     * @param {*} section 
     */
    async dealSection(section) {
        let firstLetter = section.substring(0, 1);
        if (!['(', '['].includes(firstLetter)) {
            return section;
        }
        let len = section.length;
        let arr = section.substring(1, len - 1).split(',');
        let amount = '';
        if (arr[0] > 1000) {
            amount = (Number(arr[0]) / 10000) + '-' + (Number(arr[1]) / 10000) + '万';
        } else {
            amount = Number(arr[0]) + '-' + Number(arr[1]);
        }
        return amount;
    }


    /**
     * 获取多头借贷的分值
     * @param {*} a 近6月消金机构注册笔数
     * @param {*} b 近6月放款笔数
     */
    async getDtScore(a, b) {
        let aScore = 0;
        let bScore = 0;
        if (a > 30) {
            aScore = 30;
        } else if (a > 15) {
            aScore = 20;
        } else if (a > 5) {
            aScore = 10;
        } else {
            aScore = 0;
        }
        if (b > 15) {
            bScore = 30;
        } else if (b > 7) {
            bScore = 20;
        } else if (b > 3) {
            bScore = 10;
        } else {
            bScore = 0;
        }
        let score = aScore >= bScore ? aScore : bScore;
        return score;
    }

    /**
     * 
     * @param {*} a 身份证关联手机号个数
     * @param {*} b 手机号关联身份证个数
     */
    async getIdCardScore(a, b) {
        let aScore = 0;
        let bScore = 0;
        if (a >= 3) {
            aScore = parseInt(a * 3) > 20 ? 20 : parseInt(a * 3);
        } else if (a > 1) {
            aScore = 5;
        } else {
            aScore = 0;
        }
        if (b >= 3) {
            bScore = parseInt(b * 3) > 20 ? 20 : parseInt(b * 3);
        } else if (b > 1) {
            bScore = 5;
        } else {
            bScore = 0;
        }
        let score = (aScore + bScore) > 20 ? 20 : (aScore + bScore);
        return score;
    }


    /**
     * 生成报告内容
     * @param {*} inputParams 三要素
     * @param {*} blacklistInfo 获取的黑名单信息
     */
    async createReport(inputParams, blacklistInfo) {
        const { ctx } = this;

        let birth = parseInt(inputParams.id_card.substring(6, 10));
        let age = parseInt(moment().format('YYYY')) - birth;

        // let city = await ctx.service.credit.common.getIdCardCity(inputParams.id_card);
        let city = await ctx.helper.getPhoneCity(inputParams.phone);//2019-10-14 20:36:00 lisk 改为获取手机号归属地

        let reportData = {
            name: inputParams.name,
            id_card: inputParams.id_card,
            phone: inputParams.phone,
            age: age,
            city: city,
            blacklist_of_internet_loans: blacklistInfo.pre_loan_risk.blacklist_of_internet_loans,
            blacklist_of_court_dishonesty: blacklistInfo.pre_loan_risk.blacklist_of_court_dishonesty,
            blacklist_of_industry: blacklistInfo.pre_loan_risk.blacklist_of_industry,
            blacklist_of_ds_industry: blacklistInfo.pre_loan_risk.blacklist_of_ds_industry,
            blacklist_of_bx_industry: blacklistInfo.pre_loan_risk.blacklist_of_bx_industry,
            blacklist_of_zc_industry: blacklistInfo.pre_loan_risk.blacklist_of_zc_industry,
            blacklist_of_zf_industry: blacklistInfo.pre_loan_risk.blacklist_of_zf_industry,
            blacklist_of_jd_industry: blacklistInfo.pre_loan_risk.blacklist_of_jd_industry,
            reg_count_1month: blacklistInfo.long_lending_risk.reg_count_1month,
            reg_count_3month: blacklistInfo.long_lending_risk.reg_count_3month,
            reg_count_6month: blacklistInfo.long_lending_risk.reg_count_6month,
            consume_reg_count_1month: blacklistInfo.long_lending_risk.consume_reg_count_1month,
            consume_reg_count_3month: blacklistInfo.long_lending_risk.consume_reg_count_3month,
            consume_reg_count_6month: blacklistInfo.long_lending_risk.consume_reg_count_6month,
            loan_reg_count_1month: blacklistInfo.long_lending_risk.loan_reg_count_1month,
            loan_reg_count_3month: blacklistInfo.long_lending_risk.loan_reg_count_3month,
            loan_reg_count_6month: blacklistInfo.long_lending_risk.loan_reg_count_6month,
            consume_reg_platform_count_1month: blacklistInfo.long_lending_risk.consume_reg_platform_count_1month,
            consume_reg_platform_count_3month: blacklistInfo.long_lending_risk.consume_reg_platform_count_3month,
            consume_reg_platform_count_6month: blacklistInfo.long_lending_risk.consume_reg_platform_count_6month,
            loan_reg_platform_count_1month: blacklistInfo.long_lending_risk.loan_reg_platform_count_1month,
            loan_reg_platform_count_3month: blacklistInfo.long_lending_risk.loan_reg_platform_count_3month,
            loan_reg_platform_count_6month: blacklistInfo.long_lending_risk.loan_reg_platform_count_6month,
            reg_platform_count_1month: blacklistInfo.long_lending_risk.reg_platform_count_1month,
            reg_platform_count_3month: blacklistInfo.long_lending_risk.reg_platform_count_3month,
            reg_platform_count_6month: blacklistInfo.long_lending_risk.reg_platform_count_6month,
            credit_count_1month: blacklistInfo.long_lending_risk.credit_count_1month,
            credit_count_3month: blacklistInfo.long_lending_risk.credit_count_3month,
            credit_count_6month: blacklistInfo.long_lending_risk.credit_count_6month,
            credit_amount_1month: blacklistInfo.long_lending_risk.credit_amount_1month,
            credit_amount_3month: blacklistInfo.long_lending_risk.credit_amount_3month,
            credit_amount_6month: blacklistInfo.long_lending_risk.credit_amount_6month,
            credit_closed_count_1month: blacklistInfo.long_lending_risk.credit_closed_count_1month,
            credit_closed_count_3month: blacklistInfo.long_lending_risk.credit_closed_count_3month,
            credit_closed_count_6month: blacklistInfo.long_lending_risk.credit_closed_count_6month,
            credit_closed_amount_1month: blacklistInfo.long_lending_risk.credit_closed_amount_1month,
            credit_closed_amount_3month: blacklistInfo.long_lending_risk.credit_closed_amount_3month,
            credit_closed_amount_6month: blacklistInfo.long_lending_risk.credit_closed_amount_6month,
            consume_credit_count_1month: blacklistInfo.long_lending_risk.consume_credit_count_1month,
            consume_credit_count_3month: blacklistInfo.long_lending_risk.consume_credit_count_3month,
            consume_credit_count_6month: blacklistInfo.long_lending_risk.consume_credit_count_6month,
            loan_credit_count_1month: blacklistInfo.long_lending_risk.loan_credit_count_1month,
            loan_credit_count_3month: blacklistInfo.long_lending_risk.loan_credit_count_3month,
            loan_credit_count_6month: blacklistInfo.long_lending_risk.loan_credit_count_6month,
            consume_credit_platform_count_1month: blacklistInfo.long_lending_risk.consume_credit_platform_count_1month,
            consume_credit_platform_count_3month: blacklistInfo.long_lending_risk.consume_credit_platform_count_3month,
            consume_credit_platform_count_6month: blacklistInfo.long_lending_risk.consume_credit_platform_count_6month,
            loan_credit_platform_count_1month: blacklistInfo.long_lending_risk.loan_credit_platform_count_1month,
            loan_credit_platform_count_3month: blacklistInfo.long_lending_risk.loan_credit_platform_count_3month,
            loan_credit_platform_count_6month: blacklistInfo.long_lending_risk.loan_credit_platform_count_6month,
            credit_platform_count_1month: blacklistInfo.long_lending_risk.credit_platform_count_1month,
            credit_platform_count_3month: blacklistInfo.long_lending_risk.credit_platform_count_3month,
            credit_platform_count_6month: blacklistInfo.long_lending_risk.credit_platform_count_6month,
            id_card_relevant_mobilephone_count: blacklistInfo.identity_related_risk.id_card_relevant_mobilephone_count,
            id_card_relevant_device_count: blacklistInfo.identity_related_risk.id_card_relevant_device_count,
            mobilephone_relevant_id_card_count: blacklistInfo.identity_related_risk.mobilephone_relevant_id_card_count,
            relevant_loan_app_count_6month: blacklistInfo.related_app.relevant_loan_app_count_6month,
            relevant_gamble_app_count_6month: blacklistInfo.related_app.relevant_gamble_app_count_6month,
            relevant_ip_app_count_6month: blacklistInfo.related_app.relevant_ip_app_count_6month,
            relevant_other_app_count_6month: blacklistInfo.related_app.relevant_other_app_count_6month,
            overdue: JSON.stringify(blacklistInfo.overdue_analysis)
        }
        let report = await ctx.prometheusModel.CreditBlacklistReport.create(reportData);
        return report;
    }


}

module.exports = BlacklistService;
