
'use strict';

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

class CheckService extends Service {

    /**
     * 获取用户的手机号(打码)
     */
    async getUserHidePhone() {
        const { ctx } = this;
        let ret = {
            hide_phone: '',
            is_reject: false,//30天之内是否有被拒记录
        };
        if (!ctx.oldUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return ret;
        }
        let userSid = isNaN(ctx.oldUserId) ? ctx.helper.decodeUserSid(ctx.oldUserId) : ctx.oldUserId;
        let filter = {
            attributes: ['passport'],
            where: {
                sid: userSid,
                yys_cid: 10
            }
        }
        let userInfo = await ctx.gjjModel.SysUser.findOne(filter);
        if (!userInfo) {
            ctx.failed('没有找到对应的手机号');
        }
        ret.hide_phone = userInfo.passport.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');

        //最近30天是否有被拒记录
        let rejectFilter = {
            attributes: ['user_sid'],
            where: {
                user_sid: userSid,
                created_at: { $gt: moment().subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss') },
                is_target_user: { $ne: 1 }
            }
        }
        let rejectRecord = await ctx.prometheusModel.DuxiaomanLog.findOne(rejectFilter);
        ret.is_reject = !rejectRecord ? false : true;

        return ret;
    }

    /**
     * 签名,加密
     * @param {object} params 需要加密的参数对象
     */
    async sign(params) {
        const { ctx } = this;
        let signKey = this.config.DXM_SECRET;
        let sign = '';
        if (!params) {
            ctx.failed('params is empty');
        }
        //键名排序
        const sortParamsKey = Object.keys(params).sort();
        //键值拼接-升序
        let sortValues = '';
        for (let i in sortParamsKey) {
            if (['sign', 'Sign'].includes(sortParamsKey[i])) {
                continue;
            }
            sortValues += sortParamsKey[i] + '=' + params[sortParamsKey[i]] + '&';
        }
        sortValues = sortValues.substring(0, sortValues.length - 1) + signKey;
        sign = ctx.helper.md5(sortValues);
        ctx.logger.info({ sign: sign });
        return sign;
    }

    async check(inputParams) {
        const { ctx } = this;
        let ret = {
            is_target_user: 0,//1 true 0 false -1 NOT_FOUND
            url: ''
        }
        if (!ctx.oldUserId || !ctx.userId) {
            //如果没有登录就不做处理
            ctx.failed('登录异常');
        }
        let userSid = isNaN(ctx.oldUserId) ? ctx.helper.decodeUserSid(ctx.oldUserId) : ctx.oldUserId;
        let filter = {
            attributes: ['passport'],
            where: {
                sid: userSid,
                yys_cid: 10
            }
        }
        let userInfo = await ctx.gjjModel.SysUser.findOne(filter);
        if (!userInfo) {
            ctx.failed('没有找到对应的手机号');
        }

        let fr = this.config.CFG_ENV === 'pro' ? (inputParams.fr ? inputParams.fr : 'jmall_list54') : (inputParams.fr ? inputParams.fr : 'gjj_test');
        let params = {
            app_id: this.config.DXM_APP_ID,
            datetime: new Date().getTime(),
            phone_md5: ctx.helper.md5(userInfo.passport),
            fr: fr,
            sign: '',
        }
        params.sign = await this.sign(params);
        let dxmUrl = this.config.DXM_URL + '?';
        for (let i in params) {
            dxmUrl += i + '=' + params[i] + '&';
        }
        dxmUrl = dxmUrl.substring(0, dxmUrl.length - 1);
        let result = await ctx.helper.send_request(dxmUrl, {}, { method: 'GET' });
        ctx.logger.info('result:' + JSON.stringify(result));
        if (result.status === 200) {
            if (result.data.retCode === 0) {
                ret.is_target_user = result.data.result.is_target_user;
            }
            //数据库记录
            let addData = {
                user_id: ctx.userId,
                app_user_id: ctx.appUserId,
                app_id: ctx.appId,
                app_type_id: ctx.appTypeId,
                user_sid: userSid,
                phone: userInfo.passport,
                is_target_user: result.data.result.is_target_user,
                request: JSON.stringify(params),
                response: JSON.stringify(result.data),
            }
            await ctx.prometheusModel.DuxiaomanLog.create(addData);
        } else {
            ctx.failed('服务异常,请稍后再试');
        }
        if (ret.is_target_user === 1) {
            //pro环境 142对应193 143对应194 133-195
            //uat环境 174对应175 176对应177
            let bid = inputParams['business_id'] ? Number(inputParams['business_id']) : 142;
            let businessId = 1;
            if (this.config.CFG_ENV === 'pro') {
                if (bid === 142) {
                    businessId = 193;
                } else if (bid === 143) {
                    businessId = 194;
                } else if (bid === 133) {
                    businessId = 195
                } else {
                    ctx.failed('配置信息异常');
                }
            } else if (this.config.CFG_ENV === 'uat') {
                businessId = bid === 174 ? 175 : 177;
            }
            let businessInfo = await this.getBusinessInfo(businessId);
            ret.url = businessInfo.url;
        }
        return ret;
    }



    /**
     * 获取业务信息,type=4表示普通贷款
     * @param {integer|string} id 业务编号
     * @returns {object} businessInfo 业务相关信息
     */
    async getBusinessInfo(id) {
        const { ctx } = this;
        let url = this.config.CASSANDRA_API + '/huodong/bu_basic/' + id + '?type=4';
        let result = await ctx.helper.send_request(url, {}, {
            method: 'GET',
        });
        ctx.logger.info(url + ':' + JSON.stringify(result));
        let businessInfo = (result.status === 200 && result.data && result.data.ret) ? result.data.ret : {};
        return businessInfo;
    }






}

module.exports = CheckService;
