
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const R = require('ramda');

class CallriskService extends Service {


    async verifyCode(code) {

        const { ctx } = this;
        const url = '';
        const params = {

        };
        // const result = await ctx.helper.send_request(url, params, {});
        // if (result.status !== 200) {
        //     ctx.failed('code error');
        // }
        return true;
    }

    async checkThreeElements(input) {

        const { ctx } = this;
        //姓名手机号和身份证校验
        const { id_card, phone, name } = input;
        let idVerify = ctx.helper.verify_id_card(id_card);
        let phoneVerify = ctx.helper.isPhoneNumber(phone);
        let nameVerify = ctx.helper.verify_real_name(name);
        if (!idVerify) {
            ctx.failed('身份证输入有误，请校验后输入');
        }
        if (!phoneVerify) {
            ctx.failed('手机号输入有误，请校验后输入');
        }
        if (nameVerify !== 1) {
            ctx.failed('姓名输入有误，请校验后输入');
        }
        //数盒魔方三要素校验
        await ctx.service.credit.common.shuhemofangCheck('callrisk', { id_card, phone, name });

        return true;
    }

    async getCallriskDetailData(input) {

        const { real_name, id_card, phone, password } = input;
        //TODO 调用运营商数据接口
        return {};
    }

    /**
     * 获取个人通话检测报告
     */
    async getReportB() {

        const { ctx } = this;

        const report = await this.formatReport();
        const ret = await this.formatHeadExplainMsg(report);


        return ret;

    }

    async getReport(report_id) {

        const { ctx } = this;

        let basics = await ctx.prometheusModel.CreditCallriskReport.one({ where: { id: report_id, user_id: ctx.userId } });
        if (!basics || !basics.id) {
            ctx.failed('error report_id');
        }

        const call_overview = await this.getCallOverview(report_id);
        const call_type = await this.getCallType(report_id);
        let call_active = await this.getCallActive(report_id);
        const call_behavior = await this.getCallBehavior(report_id);

        //订单是否在有效期内
        const net_time = basics.net_time;
        const months = parseInt(net_time / 30);
        const days = net_time % 30;
        basics.net_time = months + '月' + (days ? days + '天' : '');
        basics.mobile = basics.mobile.substring(0, 3) + '****' + basics.mobile.substring(7, 11);//手机号（只展示前三位和后四位）
        basics.dataValues.report_time = moment(basics.created_at).format('YYYY-MM-DD');
        delete basics.created_at;
        const diff = function (a, b) { return b.call_count - a.call_count };
        const city_active = R.sort(diff)(call_active.city_active).slice(0, 3);

        call_active.city_active = JSON.stringify(city_active);
        call_behavior.silence_time_3day = call_behavior.silence_time_3day * 24 * 60;//转为分钟
        call_behavior.call_rank.maximum_active_call_number = call_behavior.call_rank.maximum_active_call_number ? call_behavior.call_rank.maximum_active_call_number.substring(0, 3) + '****' + call_behavior.call_rank.maximum_active_call_number.substring(7, 11) : '';//手机号（只展示前三位和后四位）
        call_behavior.call_rank.maximum_passive_call_number = call_behavior.call_rank.maximum_passive_call_number ? call_behavior.call_rank.maximum_passive_call_number.substring(0, 3) + '****' + call_behavior.call_rank.maximum_passive_call_number.substring(7, 11) : '';//手机号（只展示前三位和后四位）
        call_behavior.call_rank.maximum_call_time_number = call_behavior.call_rank.maximum_call_time_number ? call_behavior.call_rank.maximum_call_time_number.substring(0, 3) + '****' + call_behavior.call_rank.maximum_call_time_number.substring(7, 11) : '';//手机号（只展示前三位和后四位）
        const report_valid = await ctx.service.credit.order.getReportValid('callrisk', report_id);
        let report = {
            basics: { data: basics },
            call_overview: { data: call_overview },
            call_type: { data: call_type },
            call_active: { data: call_active },
            call_behavior: { data: call_behavior },
            report_valid,
        };
        report.basics.data.call_result_assessment = await this.getEvaluationLevel(report);

        const ret = await this.formatHeadExplainMsg(report);

        return ret;
    }

    async getCallOverview(report_id) {

        const { ctx } = this;
        const call_overviews = await ctx.prometheusModel.CreditCallriskCallOverview.all({ where: { report_id } });
        if (!call_overviews || call_overviews.length === 0) {
            return [];
        }

        let data = [];
        const monthes = [];
        for (let i in call_overviews) {
            const call_overview = call_overviews[i];
            // monthes.push(call_overview.month);
            // data.push(call_overview);
            data.push(call_overview);
        }

        return data;
    }

    async getCallType(report_id) {

        const { ctx } = this;
        const call_type = await ctx.prometheusModel.CreditCallriskCallType.one({ where: { report_id } });
        const data = call_type;

        return data;
    }

    async getCallActive(report_id) {

        const { ctx } = this;
        const call_active = await ctx.prometheusModel.CreditCallriskCallActive.one({ where: { report_id } });
        return call_active;
    }

    async getCallBehavior(report_id) {

        const { ctx } = this;
        const call_behavior = await ctx.prometheusModel.CreditCallriskCallBehavior.one({ where: { report_id } });
        const call_behavior_silence_cycles = await ctx.prometheusModel.CreditCallriskSilenceCycle.list({ where: { report_id }, order: [['silence_end_time', 'desc']] });
        const ret = {
            silence_count_3day: call_behavior.silence_count_3day,
            silence_time_3day: call_behavior.silence_time_3day,
            silence_time_rate_3day: call_behavior.silence_time_rate_3day,
            silence_cycle: call_behavior_silence_cycles.rows,
            call_each_other: {
                active_call_count: call_behavior.active_call_count,
                passive_call_count: call_behavior.passive_call_count,
                each_call_count: call_behavior.each_call_count,
            },
            call_rank: {
                maximum_active_call_count: call_behavior.maximum_active_call_count,
                maximum_active_call_number: call_behavior.maximum_active_call_number,
                maximum_active_call_city: call_behavior.maximum_active_call_city,
                maximum_passive_call_count: call_behavior.maximum_passive_call_count,
                maximum_passive_call_number: call_behavior.maximum_passive_call_number,
                maximum_passive_call_city: call_behavior.maximum_passive_call_city,
                maximum_call_time: call_behavior.maximum_call_time,
                maximum_call_time_number: call_behavior.maximum_call_time_number,
                maximum_call_time_city: call_behavior.maximum_call_time_city,
            },
        };

        return ret;
    }

    async formatReport() {

        const ret = {
            basics: {
                msg: '我们将依据您授权的运营商通话认证，对您的通话行为进行多维度的分析和评估，帮助您更清楚的了解目前的贷款风险点。',//解析文案
                data: {
                    mobile: '159****2898', //手机号
                    operator: '美国长城', //运营商
                    net_time: '10月10天', //入网时长 
                    call_result_assessment: '优质', //通话结果评估 
                    report_time: '2019-09-03', //报告生成时间 
                    report_No: '1312312312321312', //报告编号 
                }

            },
            call_overview: {//通话概览
                msg: '解读：您当前检测的手机号码入网时长，若少于6个月，会在一定程度影响您的贷款通过率。近6个月的月均话费和通话次数，反应了您个人通话的稳定性，在一定程度会影响到贷款机构对您的评估。',
                monthes: ['2月', '2月', '2月', '2月', '2月', '2月',],
                data: {
                    '2月': {
                        call_time_month: '233', //月通话时长统计
                        call_fee_month: '333', //月话费
                        call_active_count_month: '233', //月主叫次数
                        call_passive_count_month: '233', //月被叫次数
                        call_count_month: '466', //月总通话次数 
                    },
                    '3月': {
                        call_time_month: '332', //月通话时长统计
                        call_fee_month: '332', //月话费
                        call_active_count_month: '332', //月主叫次数
                        call_passive_count_month: '332', //月被叫次数
                        call_count_month: '664', //月总通话次数 
                    },
                    '2月': {
                        call_time_month: '233', //月通话时长统计
                        call_fee_month: '333', //月话费
                        call_active_count_month: '233', //月主叫次数
                        call_passive_count_month: '233', //月被叫次数
                        call_count_month: '466', //月总通话次数 
                    },
                    '3月': {
                        call_time_month: '332', //月通话时长统计
                        call_fee_month: '332', //月话费
                        call_active_count_month: '332', //月主叫次数
                        call_passive_count_month: '332', //月被叫次数
                        call_count_month: '664', //月总通话次数 
                    },
                    '2月': {
                        call_time_month: '233', //月通话时长统计
                        call_fee_month: '333', //月话费
                        call_active_count_month: '233', //月主叫次数
                        call_passive_count_month: '233', //月被叫次数
                        call_count_month: '466', //月总通话次数 
                    },
                    '3月': {
                        call_time_month: '332', //月通话时长统计
                        call_fee_month: '332', //月话费
                        call_active_count_month: '332', //月主叫次数
                        call_passive_count_month: '332', //月被叫次数
                        call_count_month: '664', //月总通话次数 
                    },
                }
            },
            call_type: {//通话类型分析
                msg: `解读：近6个月，贷款类通话累计为【次】，金融业务通话【正常/较异常】您在短期内可能的申请贷款次数较正常，有利于贷款机构对您的评估；`,
                data: {
                    bank_call_count: '12', //银行通话次数 
                    bank_call_time: '34', //银行通话时长 
                    bank_number_count: '232', //银行通话号码个数 
                    loan_call_count: '433', //贷款通话次数 
                    loan_call_time: '232', //贷款通话时长 
                    loan_number_count: '2323', //贷款通话号码个数 
                    court_call_count: '123', //法院通话次数 
                    collection_call_count: '123', //催收通话次数 
                    laywer_call_count: '34', //律师通话次数 
                    macao_call_count: '3434', //澳门电话通话次数 
                    c110_call_count: '542', //110通话次数
                    c120_call_count: '123', //120/119通话次数
                }
            },
            call_active: {//通话活跃分析
                msg: '',
                data: {
                    routine_call_time: '132', //常规时间通话时长 
                    night_call_time: '323', //深夜时间通话时长 
                    routine_call_count: '343', //常规时间通话次数 
                    night_call_count: '343', //深夜时间通话次数 
                    time_interval: ['0-3', '3-6', '6-9', '9-12', '12-15', '15-18', '18-21', '21-24',],//时间间隔
                    time_interval_active: {
                        '0-3': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '3-6': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '6-9': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '9-12': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '12-15': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '15-18': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '18-21': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                        '21-24': {
                            call_count: '23', //通话次数 
                            call_time: '111', //通话时长 
                        },
                    },
                    cities: ['杭州', '上海', '北京'],
                    city_active: [
                        {
                            city: '杭州', //具体城市 
                            ranking: '1', //通话次数排名 
                            call_count: '123', //通话次数 
                            call_time: '222', //通话时长 
                        },
                        {
                            city: '杭州2', //具体城市 
                            ranking: '2', //通话次数排名 
                            call_count: '123', //通话次数 
                            call_time: '222', //通话时长 
                        },
                        {
                            city: '杭州3', //具体城市 
                            ranking: '3', //通话次数排名 
                            call_count: '123', //通话次数 
                            call_time: '222', //通话时长 
                        },
                    ],
                }
            },
            call_behavior: {//通话行为分析
                msg: '解读：您的静默时长、静默次数以及周期，占整',
                data: {
                    silence_count_3day: '2323', //静默3天以上的次数
                    silence_time_3day: '423', //静默总时长
                    silence_time_rate_3day: '2342', //静默时长占比 
                    silence_cycle: [
                        {
                            silence_begin_time: '2019-09-03 18:53:49', //静默开始时间 
                            silence_end_time: '2019-09-03 18:53:52', //静默结束时间 
                        },
                        {
                            silence_begin_time: '2019-09-03 18:53:49', //静默开始时间 
                            silence_end_time: '2019-09-03 18:53:52', //静默结束时间 
                        },
                        {
                            silence_begin_time: '2019-09-03 18:53:49', //静默开始时间 
                            silence_end_time: '2019-09-03 18:53:52', //静默结束时间 
                        },
                    ],
                    call_each_other: {//互通电话统计
                        active_call_count: 122,//主叫电话数
                        passive_call_count: 233,//被叫电话数
                        each_call_count: 100,//互相叫电话数
                    },
                    call_rank: {
                        maximum_active_call_count: '2423',//最多主叫通话次数 
                        maximum_active_call_city: '浙江温州',//最多主叫通话城市
                        maximum_active_call_number: '23',//最多主叫通话次数对应号码 
                        maximum_passive_call_count: '321',//最多被叫通话次数 
                        maximum_passive_call_city: '浙江丽水',//最多被叫通话城市
                        maximum_passive_call_number: '123',//最多被叫通话次数对应号码 
                        maximum_call_time: '132',//最多通话时长 
                        maximum_call_time_city: '浙江杭州',//最多通话时长城市
                        maximum_call_time_number: '1231',//最多通话时长对应号码 
                    }
                }
            }
        }

        return ret;

    }

    //参数只要最终输出的报告格式数据
    async getEvaluationLevel(report) {

        const { ctx } = this;
        const basics = report.basics.data;
        const call_overview = report.call_overview.data;
        const call_type = report.call_type.data;
        const call_active = report.call_active.data;
        const call_behavior = report.call_behavior.data;

        //入网时长分数计算
        const net_time = parseInt(basics.net_time);//入网时长
        let net_time_score = 0;
        if (net_time < 3) {
            net_time_score = 40;
        } else if (net_time < 6) {
            net_time_score = 30;
        } else if (net_time < 12) {
            net_time_score = 15;
        } else if (net_time < 24) {
            net_time_score = 10;
        }

        //话费分数计算
        let month_fee_sum = 0;
        for (let i in call_overview) {
            const month_call_overview = call_overview[i];
            month_fee_sum += month_call_overview.call_fee_month;
        }
        const fee_avg = month_fee_sum / call_overview.length;//平均月话费
        let fee_avg_score = 0;
        if (fee_avg < 20) {
            fee_avg_score = 20;
        } else if (fee_avg < 30) {
            fee_avg_score = 10;
        }

        //通话类型分数计算
        const loan_call_count = call_type.loan_call_count;
        const bank_call_count = call_type.bank_call_count;
        const court_call_count = call_type.court_call_count;
        const collection_call_count = call_type.collection_call_count;
        const laywer_call_count = call_type.laywer_call_count;
        const macao_call_count = call_type.macao_call_count;
        let call_type_score = 0;
        if (loan_call_count >= 1) {
            call_type_score += loan_call_count * 7;
        }
        if (bank_call_count >= 1) {
            call_type_score += bank_call_count * 2;
        }
        if (court_call_count >= 1) {
            call_type_score += court_call_count * 5;
        }
        if(call_type_score > 30){
            call_type_score = 30;
        }
        if (collection_call_count >= 1) {
            call_type_score += collection_call_count * 10;
        }
        if (laywer_call_count >= 1) {
            call_type_score += call_type_score * 4;
        }
        if (macao_call_count >= 1) {
            call_type_score += macao_call_count * 4;
        }

        //通话活跃分数计算
        const call_time_percent = call_active.routine_call_time ? (call_active.night_call_time / call_active.routine_call_time).toFixed(2) : 0;
        const call_count_percent = call_active.routine_call_count ? (call_active.night_call_count / call_active.routine_call_count).toFixed(2) : 0;
        let call_time_score = 0;
        let call_count_score = 0;
        if (call_time_percent >= 0.2) {
            call_time_score = 30;
        } else if (call_time_percent > 0.15) {
            call_time_score = 25;
        } else if (call_time_percent > 0.07) {
            call_time_score = 20;
        } else if (call_time_percent > 0.03) {
            call_time_score = 10;
        }
        if (call_count_percent >= 0.2) {
            call_count_score = 30;
        } else if (call_count_percent > 0.15) {
            call_count_score = 25;
        } else if (call_count_percent > 0.07) {
            call_count_score = 20;
        } else if (call_count_percent > 0.03) {
            call_count_score = 10;
        }
        const call_active_score = call_time_score < call_count_score ? call_count_score : call_time_score;

        //通话行为分数计算
        let call_behavior_socre = 0;
        const silence_count_3day = call_behavior.silence_count_3day;
        if (silence_count_3day >= 7) {
            call_behavior_socre = 30;
        } else if (silence_count_3day >= 4) {
            call_behavior_socre = 20;
        } else if (silence_count_3day >= 1) {
            call_behavior_socre = 10;
        }

        console.info(net_time_score, fee_avg_score, call_type_score, call_active_score, call_behavior_socre);
        const sum_score = net_time_score + fee_avg_score + call_type_score + call_active_score + call_behavior_socre;

        let call_result_assessment = '优质';
        if (sum_score >= 60) {
            call_result_assessment = '高';
        } else if (sum_score >= 20) {
            call_result_assessment = '中';
        } else if (sum_score >= 10) {
            call_result_assessment = '低';
        }

        return call_result_assessment;

    }

    //参数只要最终输出的报告格式数据
    async formatHeadExplainMsg(report) {

        const { ctx } = this;

        const call_type = report.call_type.data;
        const call_active = report.call_active.data;

        const call_behavior = report.call_behavior.data;

        const basics_msg = `我们将依据您授权的运营商通话认证，对您的通话行为进行多维度的分析和评估，帮助您更清楚的了解目前的贷款风险点。`;

        const call_overview_msg = `解读：您当前检测的手机号码入网时长，若少于6个月，会在一定程度影响您的贷款通过率。近6个月的月均话费和通话次数，反应了您个人通话的稳定性，在一定程度会影响到贷款机构对您的评估。`;


        //通话类型解析
        const loan_call_count = call_type.loan_call_count;
        const court_call_count = call_type.court_call_count;
        const collection_call_count = call_type.collection_call_count;
        const laywer_call_count = call_type.laywer_call_count;
        const macao_call_count = call_type.macao_call_count;
        let advantage_text = '有利于';
        let loan_call_status = '正常';
        if (loan_call_count >= 3) {
            loan_call_status = '较异常';
            advantage_text = '不利于';
        }
        let risk_call_status = '正常';
        if (court_call_count > 1 || collection_call_count > 1 || laywer_call_count > 3 || macao_call_count > 3) {
            risk_call_status = '多';
            advantage_text = '不利于';
        }
        if (collection_call_count == 0 && laywer_call_count <= 3 && macao_call_count <= 3 && court_call_count <= 1) {
            risk_call_status = '少';
        }
        let illegal_text = '低';
        if (court_call_count > 1 || collection_call_count > 1 || laywer_call_count > 3) {
            illegal_text = '高';
            advantage_text = '不利于';
        }
        const call_type_msg = `解读：近6个月，贷款类通话累计为【${loan_call_count}次】，金融业务通话【${loan_call_status}】，您在短期内可能的申请贷款次数较正常，有利于贷款机构对您的评估；近6个月来，您的疑似风险通话次数较【${risk_call_status}】，您与违法违规事件关联度较【${illegal_text}】，【${advantage_text}】贷款机构对您的评估`;


        //通话活跃度解析
        let call_count_array = ['较低', '比较符合', '有利于'];
        const call_count_percent = call_active.night_call_time / call_active.routine_call_time;
        if (call_count_percent > 0.1) {
            call_count_array = ['较高', '不符合', '不利于'];
        }
        //TODO 计算近6个月每个月通话的城市有几个。
        const call_most_city = call_active.city_active.slice(0, 3);
        const total_time = parseInt(call_active.routine_call_time) + parseInt(call_active.night_call_time);
        let top_three_city_total_time = 0;
        for (let i in call_most_city) {
            const call_city = call_most_city[i];
            top_three_city_total_time += parseInt(call_city.call_time);
        }
        // for (let j in call_active.city_active) {
        //     const call = call_active.city_active[j];
        //     total_time += call.call_time;
        // }
        const percent = (top_three_city_total_time / total_time).toFixed(2);
        let call_active_text = ['变化不大', '较好', '有利于'];
        if (percent <= 0.6) {
            call_active_text = ['变动较大', '一般', '不利于'];
        }
        const call_active_msg = `您的夜间通话次数占【${call_count_array[0]}】，【${call_count_array[1]}】日常社交时间，【${call_count_array[2]}】贷款机构对您的放贷评估。您的通话活跃地区【${call_active_text[0]}】，您当前个人的社交/社会状态稳定度【${call_active_text[1]}】，【${call_active_text[2]}】贷款机构对您的放贷评估。`;

        //通话行为解析
        let call_behavior_array = ['较少', '稳定', '有利于',];
        if (call_behavior.silence_count_3day > 3) {
            call_behavior_array = ['较多', '较大', '不利于',];
        }
        const call_behavior_msg = `您的静默时长、静默次数以及周期，占整体比例【${call_behavior_array[0]}】，通话活跃变动幅度【${call_behavior_array[1]}】，【${call_behavior_array[2]}】贷款机构对您的放贷评估`;

        report.basics.msg = basics_msg;
        report.call_overview.msg = call_overview_msg;
        report.call_type.msg = call_type_msg;
        report.call_active.msg = call_active_msg;
        report.call_behavior.msg = call_behavior_msg;

        return report;

    }

    //获取验证码
    async getCode(order_id) {

        const { ctx } = this;
        const user_id = ctx.userId;

        const order_info = await ctx.prometheusModel.CreditOrder.findOne({ where: { id: order_id } });
        const apply_info = await ctx.prometheusModel.CreditApply.findOne({ where: { id: order_info.apply_id } });
        if (!order_info || !order_info.id) {
            ctx.failed('error order');
        }
        const order_sn = apply_info.r_order_id;
        const input_params = {
            phone: order_info.phone,
            name: order_info.name,
            ID: order_info.id_card,
            password: apply_info.service_code,
        };

        const operator_params = apply_info.operator.params;
        let get_code_params = { orderSn: order_sn, data: {} };
        for (let k in operator_params) {
            const operator_params_val = operator_params[k];
            get_code_params.data[operator_params_val.name] = input_params[operator_params_val.name];
        }

        const ret = await ctx.service.credit.yys.getCode(get_code_params);
        if (ret.code !== 0) {
            ctx.failed('getCode error msg:' + ret.msg);
        }

        return { order_id };
    }

    //提交任务
    async commitTask(input) {

        const { ctx } = this;
        let user_id = ctx.userId;
        const { order_id, code } = input;
        const order_info = await ctx.prometheusModel.CreditOrder.findOne({ where: { id: order_id } });
        const apply_info = await ctx.prometheusModel.CreditApply.findOne({ where: { id: order_info.apply_id } });
        if (!order_info || !order_info.id) {
            ctx.failed('error order_sn');
        }
        const times_key = `commit_task_times_${apply_info.r_order_id}`;
        const times = await this.app.memcache.get(times_key) ? Number(await this.app.memcache.get(times_key)) : 0;
        const input_params = {
            phone: order_info.phone,
            name: order_info.name,
            ID: order_info.id_card,
            password: apply_info.service_code,
            phoneCode: code,
        };
        const operator = apply_info.operator;
        const params = operator.params;
        let request_params = {};
        for (let i in params) {
            const column = params[i].name;
            request_params[column] = input_params[column];
        }
        let request_data = { orderSn: apply_info.r_order_id, params: request_params };
        if (times > 0) {
            request_data = { orderSn: apply_info.r_order_id, params: { phoneCode: code } };
        }

        const yys_commit = await ctx.service.credit.yys.commit(request_data);
        if (yys_commit.code !== 0) {
            ctx.failed('commit error msg:' + yys_commit.msg);
        }

        await this.app.memcache.set(times_key, times + 1, 1800);

        return { order_id };
    }


    //查询任务状态
    async queryTaskStatus(order_id) {

        const { ctx } = this;
        const user_id = ctx.userId;
        const app_type_id = ctx.appTypeId;
        const app_user_id = ctx.appUserId;
        const app_id = ctx.appId;
        const code_array = [];
        // const yys_order = await ctx.prometheusModel.CreditYysOrder.findOne({ where: { order_id } });
        const order_info = await ctx.prometheusModel.CreditOrder.findOne({ where: { id: order_id } });
        const apply_info = await ctx.prometheusModel.CreditApply.findOne({ where: { id: order_info.apply_id } });

        const order_sn = apply_info.r_order_id;
        const query_resp = await ctx.service.credit.yys.query(order_sn);
        const r_code = query_resp.code === undefined ? -999 : query_resp.code;
        // return query_resp;
        if (r_code === -999) {
            return { code: r_code, msg: query_resp.message };
        }
        if (r_code !== 0) {
            return query_resp;
        }
        // const query_resp = { code: 0, msg: 'sdfsdfsd' };
        //获取报告内容
        const yys_report_data = await ctx.service.credit.yys.getData(order_sn);//拉取报告数据

        if (yys_report_data.code !== 0) {
            return { code: -1, msg: yys_report_data.msg }
        }

        //创建报告信息
        const user_brief = yys_report_data.data.user_brief;
        const report = {
            report_no: '',
            user_id: user_id || -51,
            app_type_id: app_type_id || -51,
            app_user_id: app_user_id || -51,
            app_id: app_id || -51,
            mobile: user_brief.mobile,
            operator: user_brief.operator,
            net_time: user_brief.net_time,
            call_result_assessment: user_brief.call_result_assessment,
        }
        const report_id = await ctx.prometheusModel.CreditCallriskReport.add(report);
        const report_no = await ctx.service.credit.common.getReportNo('callrisk', report_id);
        await ctx.prometheusModel.CreditCallriskReport.edit({ params: { report_no, }, where: { id: report_id } });

        //添加通话概览
        const call_overview = yys_report_data.data.call_overview;
        const call_overview_report = [];
        for (let i in call_overview) {
            const call_overview_val = call_overview[i];
            call_overview_report.push({
                report_id,
                month: call_overview_val.month,
                call_time_month: call_overview_val.call_time_month,
                call_fee_month: call_overview_val.call_fee_month,
                call_active_count_month: call_overview_val.call_active_count_month,
                call_passive_count_month: call_overview_val.call_passive_count_month,
                call_count_month: call_overview_val.call_count_month,
            });
        }
        await ctx.prometheusModel.CreditCallriskCallOverview.bulkCreate(call_overview_report);

        //通话类型分析
        const call_type_analysis = yys_report_data.data.call_type_analysis;
        const call_type_report = {
            report_id,
            bank_call_count: call_type_analysis.bank_call_count,
            bank_call_time: call_type_analysis.bank_call_time,
            bank_number_count: call_type_analysis.bank_number_count,
            loan_call_count: call_type_analysis.loan_call_count,
            loan_call_time: call_type_analysis.loan_call_time,
            loan_number_count: call_type_analysis.loan_number_count,
            court_call_count: call_type_analysis.court_call_count,
            collection_call_count: call_type_analysis.collection_call_count,
            laywer_call_count: call_type_analysis.laywer_call_count,
            macao_call_count: call_type_analysis.macao_call_count,
            c110_call_count: call_type_analysis['110_call_count'],
            c120_call_count: call_type_analysis['120_call_count'],
        }
        await ctx.prometheusModel.CreditCallriskCallType.add(call_type_report);

        //通话活跃分析
        const call_active = yys_report_data.data.call_active_analysis;
        const call_active_report = {
            report_id,
            routine_call_time: call_active.routine_call_time,
            night_call_time: call_active.night_call_time,
            routine_call_count: call_active.routine_call_count,
            night_call_count: call_active.night_call_count,
            time_interval_active: JSON.stringify(call_active.time),
            city_active: JSON.stringify(call_active.location),
        }
        await ctx.prometheusModel.CreditCallriskCallActive.add(call_active_report);

        //通话活跃分析
        const call_behavior = yys_report_data.data.call_behavior_analysis;
        const call_behavior_report = {
            report_id,
            active_call_count: call_behavior.active_call_number_count,
            passive_call_count: call_behavior.passive_call_number_count,
            each_call_count: call_behavior.mutual_call_number_count,

            silence_count_3day: call_behavior.silence_count_3day,
            silence_time_3day: call_behavior.silence_time_3day,
            silence_time_rate_3day: call_behavior.silence_time_rate_3day,
            maximum_active_call_count: call_behavior.maximum_active_call_count,
            maximum_active_call_number: call_behavior.maximum_active_call_number,
            maximum_active_call_city: call_behavior.maximum_active_call_location,
            maximum_passive_call_count: call_behavior.maximum_passive_call_count,
            maximum_passive_call_number: call_behavior.maximum_passive_call_number,
            maximum_passive_call_city: call_behavior.maximum_passive_call_location,
            maximum_call_time: call_behavior.maximum_call_time,
            maximum_call_time_number: call_behavior.maximum_call_time_number,
            maximum_call_time_city: call_behavior.maximum_call_time_location,
        }
        const call_behavior_id = await ctx.prometheusModel.CreditCallriskCallBehavior.add(call_behavior_report);

        //通话活跃静默周期记录
        const silence_cycle_report = [];
        for (let j in call_behavior.silence_cycle) {
            const silence_cycle = call_behavior.silence_cycle[j];
            silence_cycle_report.push({
                report_id,
                call_behavior_id,
                silence_begin_time: silence_cycle.silence_begin_time,
                silence_end_time: silence_cycle.silence_end_time,
            });
        }
        await ctx.prometheusModel.CreditCallriskSilenceCycle.bulkCreate(silence_cycle_report);

        await ctx.prometheusModel.CreditOrder.update({ report_id, valid: 1, state: '待支付', order_time: moment().format('YYYY-MM-DD HH:mm:ss'), state_time: moment().format('YYYY-MM-DD HH:mm:ss') }, { where: { id: order_id } });

        return Object.assign({ report_id, order_id }, query_resp);
    }



}

module.exports = CallriskService;