var express = require('express'),
    router = express.Router(),
    extend = require('extend'),
    orm = require('../lib/orm'),
    flow = require('../lib/flow'),
    utils = require('../lib/utils'),
    rp = require('request-promise'),
    pubApi = require('../lib/publicApi'),
    moment = require('moment'),
    config = require('config'),
    log = console.log.bind(console),
    warn = console.warn.bind(console),
    error = console.error.bind(console)

// router.use('*', function (req, res, next) {
//     let keys = Object.keys(req.query)
//     if (keys.length > 0) {
//         log('#######  REQUEST #########\n [ ', req.baseUrl, ' ] query: ', req.query)
//     } else {
//         log('#######  REQUEST #########\n [ ', req.baseUrl, ' ] body: ', req.body)
//     }
//     next()
// })

let partnerMap = new Map();

async function setpartnerMap() {
    let ret = await orm.selectpartner();
    for (let item of ret) {
        if (!partnerMap.has(item.app_key)) {
            partnerMap.set(item.app_key, {
                addTime: new Date().getTime(),
                count: 0,
                phone: item.phone || '',
                allcount: 0
            });
        }else{
            partnerMap.get(item.app_key).phone = item.phone || '';
        }
    }
}

setpartnerMap()
setInterval(function () {
    setpartnerMap()
}, 30 * 60 * 1000)


router.post('/score', async (req, res) => {
    try {
        req.body.type = 'zmop'
        let ret = await pubApi.signValidityCheck(req.body)
        if (partnerMap.has(req.body.params.appKey)) {
            partnerMap.get(req.body.params.appKey).allcount += 1;
        }
        if (ret.code == 0 || req.body.xxd == 'test') {
            let order_id = req.body.params.order_id
            let app_key = req.body.params.appKey
            let partner_auth = await orm.get_auth(app_key)
            if (partner_auth.get_score == 0) {
                throw new Error('您未开通权限')
            }
            if (Number(partner_auth.balance) < Number(partner_auth.score_price)) {
                throw new Error('已达到接口调用限制次数')
            }
            
            //判断是否为公信宝服务订单号
            let checkgxb = await orm.select_crawler_task(req.body.params.order_id);
            if(checkgxb.length > 0){
              req.body.type = 'crawler'
              let gxbresult = await rp.post({
              url: 'https://t.51muge.com/zm_crawler/data/score',
              form: req.body,
              json: true
              });
              return res.send(gxbresult);
            }

            //判断是否是app授权方式
            let ysRet = await orm.get3ys(order_id);
            console.log('[score] get3ys: ', ysRet)
            if (ysRet.open_id == 'micai') {
                //新增第三方拉分接口
                let appKeyInfo = await orm.get_appkey_channel(app_key);
                console.log('appKeyinfo', appKeyInfo)     
                if (appKeyInfo[0]) {
                    console.log('appKeyinfo', appKeyInfo)              
                    let scoreRet = await orm.get_task_channel(order_id);
                    console.log('scoreRet', scoreRet)
                    scoreRet[0].which_month = utils.which_month();
                    await orm.bill_record(app_key, order_id, ysRet.cert_no, scoreRet[0].score, scoreRet[0].which_month, method = 'score', req.body.refresh || 0,'micai')
                    return res.send({code: 0, data: scoreRet[0]})
                }
            }
            if (ysRet.open_id == 'lingwa') {
                //新增第三方拉分接口
                let scoreRet = await pubApi.getLingwaScore(ysRet.cert_name, ysRet.cert_no, ysRet.cert_phone);
                if ('200' == scoreRet.code) {
                    let resp = {
                        "score": scoreRet.body.zmScore,
                        "which_month": utils.which_month(),
                        "create_time": moment().format('YYYY-MM-DD HH:mm:ss'),
                        "order_id": order_id
                    };
                    orm.insert_other_channel(app_key, order_id, '', ysRet.cert_no, 'score', ysRet.open_id, JSON.stringify(scoreRet));
                    await orm.bill_record(app_key, order_id, ysRet.cert_no, scoreRet.body.zmScore, resp.which_month, method = 'score', req.body.refresh || 0,'lingwa')
                    return res.send({code: 0, data: resp})
                }
                return res.send({code: -1, "msg": "无此订单数据"})
            }

            let data = await orm.bill(order_id)
            log('111 ', data)
            let cert_no = ''
              let task = await orm.task(order_id)
            if (!data || req.body.refresh == 1) {
                data = await orm.get_score(task)
                log('#####  最新的数据: #####', data)
                if (!data || req.body.refresh == 1) {
                    data = await flow.save_score(task)
                    log('\n#### Save zm_score #### \n order_id: ', order_id, ' \n app_key: ', app_key,)
                }
                data.order_id = order_id
                cert_no = task.cert_no
            } else {
                cert_no = data.cert_no
            }
            log('####### bill_record Data ######\n', data)
            await orm.bill_record(app_key, order_id, cert_no, data.score, data.which_month, method = 'score', req.body.refresh || 0,task.platform)
            delete data.id
            delete data.open_id
            delete data.platform
            delete data.cert_no
            log('####### Return Data ######\n', data)
            res.send({code: 0, data: data})
        } else {
            log('#####  验签失败  #####\n', ret)
            res.send(ret)
        }
    } catch (e) {
        error('/zmop/data/score: ', e)
        res.send(resp_error(e))
        //sumcount(req.body.params.appKey,e);
    }
})

router.post('/watch_list', async (req, res) => {
    try {
        req.body.type = 'zmop'
        let ret = await pubApi.signValidityCheck(req.body)
        if (partnerMap.has(req.body.params.appKey)) {
            partnerMap.get(req.body.params.appKey).allcount += 1;
        }
        if (ret.code == 0 || req.body.xxd == 'test') {
            let order_id = req.body.params.order_id
            let app_key = req.body.params.appKey
            let partner_auth = await orm.get_auth(app_key)
            if (partner_auth.get_watch_list == 0) {
                throw new Error('您未开通权限')
            }
            if (Number(partner_auth.balance) < Number(partner_auth.score_price)) {
                throw new Error('已达到接口调用限制次数')
            }
            // let data = await orm.bill(order_id, 'watch_list')
            // log('###### BILL #########\n ', data)
            let cert_no = ''
            // if (!data || req.body.refresh == 1) {
            let task = await orm.task(order_id)

            //判断是否是app授权方式 
            let ysRet = await orm.get3ys(order_id);
            console.log('[score] get3ys: ', ysRet)
            if (ysRet.open_id == 'micai') {
                //新增第三方拉分接口
                let appKeyInfo = await orm.get_appkey_channel(app_key);
                console.log('appKeyinfo', appKeyInfo)     
                if (appKeyInfo[0] && appKeyInfo[0].channel == 'micai') {
                    console.log('appKeyinfo', appKeyInfo)
                    let ysRet = await orm.get3ys(order_id);
                    let hymdRet = await pubApi.getMicaiHymdUrl(ysRet.cert_name, ysRet.cert_no, ysRet.cert_phone);
                    console.log('hymdRet', hymdRet)
                    if ('0' == hymdRet.code) {
                        orm.insert_other_channel(app_key, order_id, '', ysRet.cert_no, 'watchlist', ysRet.open_id, JSON.stringify(hymdRet));
                        await orm.bill_record(app_key, order_id, ysRet.cert_no, JSON.stringify(hymdRet.data), hymdRet.data.is_matched, method = 'watch_list', req.body.refresh || 0,'micai')
                        hymdRet.data.order_id = order_id;
                        hymdRet.data.create_time = moment().format('YYYY-MM-DD HH:mm:ss');
                        delete hymdRet.data.success;
                        return res.send({code: 0, data: hymdRet.data})
                    }
                }
            }
            if (ysRet.open_id == 'lingwa') {
                //新增第三方拉分接口
                let scoreRet = await pubApi.getLingwaWatchlist(ysRet.cert_name, ysRet.cert_no, ysRet.cert_phone);
                if ('200' == scoreRet.code) {
                    let resp = {
                        "details": scoreRet.body.details ? scoreRet.body.details : [],
                        "is_matched": scoreRet.body.matched,
                        "create_time": moment().format('YYYY-MM-DD HH:mm:ss'),
                        "order_id": order_id
                    };
                    orm.insert_other_channel(app_key, order_id, '', ysRet.cert_no, 'watchlist', ysRet.open_id, JSON.stringify(scoreRet));
                    await orm.bill_record(app_key, order_id, ysRet.cert_no, JSON.stringify(resp), scoreRet.body.matched, method = 'watch_list', req.body.refresh || 0,'lingwa')
                    return res.send({code: 0, data: resp})
                }
                return res.send({code: -1, "msg": "无此订单数据"})
            }

            let data = await flow.save_watch_list(task)
            data.create_time = moment().format('YYYY-MM-DD HH:mm:ss')
            cert_no = task.cert_no
            log('watch_list data: ', data)
            // } else {
            //     try {
            //         data.details = JSON.parse(data.details)
            //     } catch (e) {
            //     }
            //     cert_no = data.cert_no
            // }
            await orm.bill_record(app_key, order_id, cert_no, JSON.stringify(data.details), data.is_matched, method = 'watch_list', req.body.refresh || 0,data.platform)
            delete data.cert_no
            delete data.platform
            data.order_id = order_id
            if (data.is_matched == '1') {
                data.is_matched = true
            } else {
                data.is_matched = false
            }
            log('####### Return Data ######\n', data)
            res.send({code: 0, data: data})
        } else {
            log('#####  验签失败  #####\n', ret)
            res.send(ret)
        }
    } catch (e) {
        error('/zmop/data/watch_list: ', e)
        res.send(resp_error(e))
        //sumcount(req.body.params.appKey,e);
    }
})


router.post('/score/brief', async (req, res) => {
    try {
        req.body.type = 'zmop'
        let ret = await pubApi.signValidityCheck(req.body)
        if (partnerMap.has(req.body.params.appKey)) {
            partnerMap.get(req.body.params.appKey).allcount += 1;
        }
        if (ret.code == 0  || req.body.xxd == 'test') {
            let admit_score = req.body.admit_score
            let app_ids = await orm.payload_brief('score', admit_score)
            let order_id = req.body.params.order_id
            let app_key = req.body.params.appKey
            let partner_auth = await orm.get_auth(app_key)
            if (partner_auth.get_brief_score == 0) {
                throw new Error('您未开通权限')
            }
            if (Number(partner_auth.balance) < Number(partner_auth.score_price)) {
                throw new Error('已达到接口调用限制次数')
            }
            // let data = await orm.brief_bill(order_id, 'score')
            // log('###### BILL #########\n ', data)
            // let cert_no = ''
            // if (!data || req.body.refresh == 1) {
            // let task = await orm.task(order_id)
            let task = {
                app_id: app_ids[0].app_id,
                cert_no: req.body.params.cert_no,
                cert_name: req.body.params.cert_name,
                platform: 'alipay'
            }
            let data = await flow.save_brief_score(task, admit_score)
            data.order_id = order_id
            log('brief_score data: ', data)
            // } else {
            //     cert_no = data.cert_no
            // }
            await orm.brief_bill_record(app_key, order_id, task.cert_no, task.cert_name, admit_score, data.is_admittance, app_ids[0].app_id, method = 'score', req.body.refresh || 0)
            delete data.cert_no
            log('####### Return Data ######\n', data)
            res.send({code: 0, data: data})
        } else {
            log('#####  验签失败  #####\n', ret)
            res.send(ret)
        }
    } catch (e) {
        error('/zmop/data/score/brief: ', e)
        res.send(resp_error(e))
        //sumcount(req.body.params.appKey,e);
    }
})

router.post('/watch_list/brief', async (req, res) => {
    try {
        req.body.type = 'zmop'
        let ret = await pubApi.signValidityCheck(req.body)
        if (partnerMap.has(req.body.params.appKey)) {
            partnerMap.get(req.body.params.appKey).allcount += 1;
        }
        if (ret.code == 0) {
            let app_ids = await orm.payload_brief('watch_list')
            let app_id = utils.load_balance(app_ids)
            let order_id = req.body.params.order_id
            let app_key = req.body.params.appKey
            let partner_auth = await orm.get_auth(app_key)
            if (partner_auth.get_brief_watch_list == 0) {
                throw new Error('您未开通权限')
            }
            if (Number(partner_auth.balance) < Number(partner_auth.score_price)) {
                throw new Error('已达到接口调用限制次数')
            }
            let task = {
                app_id: app_ids[0].app_id,
                cert_no: req.body.params.cert_no,
                cert_name: req.body.params.cert_name,
                platform: 'alipay'
            }
            // let data = await orm.brief_bill(order_id, 'watch_list')
            // log('###### BILL #########\n ', data)
            // let cert_no = ''
            // if (!data || req.body.refresh == 1) {
            //     let task = await orm.task(order_id)
            // task.app_id = app_id
            let data = await flow.save_brief_watch_list(task)
            data.order_id = order_id
            // cert_no = task.cert_no
            log('brief_watch_list data: ', data)
            // } else {
            //     cert_no = data.cert_no
            // }
            await orm.brief_bill_record(app_key, order_id, task.cert_no, task.cert_name, data.level, '', app_id, method = 'watch_list', req.body.refresh || 0)
            // delete data.cert_no
            log('####### Return Data ######\n', data)
            res.send({code: 0, data: data})
        } else {
            log('#####  验签失败  #####\n', ret)
            res.send(ret)
        }
    } catch (e) {
        error('/zmop/data/watch_list/brief: ', e)
        res.send(resp_error(e))
        //sumcount(req.body.params.appKey,e);
    }
})

function sumcount(appKey,e) {
    if (resp_error(e).msg == '系统错误, 请稍后再试') {
    console.log("sumcount ++",appKey)
        if (partnerMap.has(appKey)) {
            partnerMap.get(appKey).count += 1;
        }
    }
}

function resp_error(e) {
    if (e.message == '已达到接口调用限制次数') {
        return {code: -1, msg: '已达到接口调用限制次数'}
    }
    if (e.message == '请选择正确的准入分') {
        return {code: -1, msg: '请选择正确的准入分'}
    }
    if (e.message == '请选择通过支付宝APP授权') {
        return {code: -1, msg: '请通过支付宝APP授权'}
    }
    if (e.message == '您未开通权限') {
        return {code: -1, msg: '您未开通权限'}
    }
    if (e.message == '无此订单号') {
        return {code: -1, msg: '无此订单号'}
    }
    if (e.message == '无效的appKey') {
        return {code: -1, msg: '无效的appKey'}
    }
    if (e.message == '鉴权失败') {
        return {code: -1, msg: '鉴权失败'}
    }
    if (e.message == '无有效合约') {
        return {code: -1, msg: '无有效合约'}
    }
    return {code: -1, msg: '系统错误, 请稍后再试'}
}

setInterval(function () {
    let dateNow = new Date().getTime();
    partnerMap.forEach(function (value, key) {
        if ((value.allcount > 10) && (value.count / value.allcount  > 0.5)) {
      //      flow.sendWarnMsg(value.phone, '合作方您好，监控显示目前芝麻信用接口不稳定，可能会对贵司业务产生影响，请知悉。我们也会密切关注接口情况，有任何问题请微信或电话联系。旭咪网络');
       //         flow.sendWarnMsg('18805819680,17774010868', `${key}合作方ERROR`);
        }
        if (dateNow - value.addTime >= 1000 * 60 * 20) {
            partnerMap.get(key).addTime = new Date().getTime();
            partnerMap.get(key).count = 0;
            partnerMap.get(key).allcount = 0;
        }
    });
}, 10 * 1000 * 60);

module.exports = router;
