const ZmopClient = require('./zmop_client/zmop_client'),
    utils = require('./utils'),
    Alipay = require('./alipay/alipay'),
    orm = require('./orm'),
    moment = require('moment'),
    rp = require('request-promise'),
    request = require('request'),
    http = require('http'),
    https = require('https'),
    URL = require('url'),
    crypto = require('crypto');
    Zmop = new ZmopClient()


// async function is_authed(cert_no, cert_name) {
//     try {
//         let auth_info = JSON.parse(await Zmop.authed(cert_no, cert_name))
//         if (auth_info.success && auth_info.authorized) {
//             //  获取芝麻分, 通知任务成功
//             // auth_info: {"success":true,"authorized":true,"open_id":"268806822853700342467205358"}
//             return auth_info.open_id
//         }
//         return false
//     } catch (e) {
//         return false
//     }
// }

// setTimeout(async () => {
//     let p = {
//         platform: 'alipay',
//         app_id: '2018051160085345',
//         access_token: 'authzmaB81ec3d1b20034e78bc5d343e3944aB48',
//         open_id: '2088802182470482'
//     }
//     try {
//         let d = await save_brief_score(p, 650)
//         console.log(d)
//     } catch (e) {
//         console.log(e)
//     }
// }, 0)

async function save_watch_list(task) {
    try {
        let list = ''
        if (task.platform == 'alipay') {
            task = await orm.openId(task);
            list = await Alipay.watch_list(task.app_id, task.access_token, task.open_id)
            if (list.code == '20001') {
                console.log('[ alipay-api ]- watch_list error: ', list)
                throw new Error('鉴权失败')
            }
            if((list.code == '40004' && list.sub_msg == '无有效合约') || list.code == '40006'){
                console.log('[ alipay-api ]- watch_list error: ', list)
                throw new Error('无有效合约')
            }
            if (list.code != '10000') {
                console.log('[ alipay-api ]- watch_list error: ', list)
                throw new Error('系统错误, 请稍后再试')
            }
        } else {
            list = await Zmop.watch_list(task.app_id, task.open_id)
            if (!list.success) {
                if (list.error_message == '鉴权失败') {
                    throw new Error('鉴权失败')
                }
                if (list.error_message == '无有效合约' || list.error_message == 'ISV权限不足，建议在开发者中心检查签约是否已经生效') {
                    throw new Error('无有效合约')
                }
                throw new Error('获取行业关注名单失败')
            }
        }
        let row = {
            id: list.biz_no,
            open_id: task.open_id,
            platform: task.platform,
            is_matched: list.is_matched ? 1 : 0,
            details: JSON.stringify(list.details || []),
            create_time: moment().format('YYYY-MM-DD HH:mm:ss')
        }
        await orm.create_watch_list(row, 'zmop_watch_list')
        delete row.id
        delete row.open_id
        return {is_matched: list.is_matched, details: list.details || [],platform:row.platform || 'zhima'}
    } catch (e) {
        if (e.message != '鉴权失败') {
            // sendWarnMsg('17774010868', '获取行业关注失败')
            //warnMsg('hygz')
        }
        throw e
    }
}


async function save_score(task) {
    try {
        let score = ''
        if (task.platform == 'alipay') {
            task = await orm.openId(task);
            score = await Alipay.score(task.app_id, task.access_token, task.open_id)
            if (score.code == '20001') {
                console.log('[ alipay-api ]- score error: ', score)
                throw new Error('鉴权失败')
            }
             if((score.code == '40004' && score.sub_msg == '无有效合约') || score.code == '40006'){
                console.log('[ alipay-api ]- score error: ', score)
                throw new Error('无有效合约')
            }
            
            if (score.code != '10000') {
                throw new Error(score.sub_msg)
            }
        } else {
            score = await Zmop.score(task.app_id, task.open_id)
            if (!score.success) {
                if (score.error_message == '鉴权失败') {
                    throw new Error('鉴权失败')
                }
                if (score.error_message == '无有效合约' || score.error_message == 'ISV权限不足，建议在开发者中心检查签约是否已经生效') {
                    throw new Error('无有效合约')
                }
                throw new Error('获取芝麻分失败')
            }
        }
        let row = {
            id: score.biz_no,
            open_id: task.open_id,
            platform: task.platform,
            score: score.zm_score,
            which_month: utils.which_month(),
            create_time: moment().format('YYYY-MM-DD HH:mm:ss')
        }
        await orm.create(row, 'zmop_score')
        delete row.id
        delete row.platform
        delete row.open_id
        return row
    } catch (e) {
        if (e.message != '鉴权失败') {
            // sendWarnMsg('17774010868', '获取芝麻分失败')
            warnMsg('zmf')
        }
        throw e
    }
}

//  芝麻分普惠版
async function save_brief_score(task, admit_score) {
    try {
        let score = ''
        if (task.platform == 'alipay') {
            score = await Alipay.brief_score(task.app_id, task.cert_no, task.cert_name, admit_score)
            if (score.code == '20001') {
                console.log('[ alipay-api ]- brief_score error: ', score)
                throw new Error('鉴权失败')
            }
               if(score.code == '40004' && score.sub_msg == '无有效合约'){
                 console.log('[ alipay-api ]- brief_score error: ', score)
                throw new Error('无有效合约')
            }
            if (score.code != '10000') {
                throw new Error(score.sub_msg)
            }
        } else {
            throw new Error('请选择通过支付宝APP授权')
        }
        return {
            is_admittance: score.is_admittance,
            admit_score: admit_score,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
    } catch (e) {
        if (e.message != '请选择通过支付宝APP授权') {
            // sendWarnMsg('17774010868', '获取芝麻分普惠版失败')
           // warnMsg('phzmf')
        }
        throw e
    }
}


//  行业关注名单普惠版
async function save_brief_watch_list(task) {
    try {
        let list = ''
        if (task.platform == 'alipay') {
            list = await Alipay.brief_watch_list(task.app_id, task.cert_no, task.cert_name)
            if (list.code == '20001') {
                console.log('[ alipay-api ]- brief_watch_list error: ', list)
                throw new Error('鉴权失败')
            }
             if(list.code == '40004' && list.sub_msg == '无有效合约'){
                 console.log('[ alipay-api ]- brief_watch_list error: ', list)
                throw new Error('无有效合约')
            }
            if (list.code != '10000') {
                throw new Error(list.sub_msg)
            }
        } else {
            throw new Error('请选择通过支付宝APP授权')
        }
        return {
            level: list.level,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
    } catch (e) {
        if (e.message != '请选择通过支付宝APP授权') {
            // sendWarnMsg('17774010868', '获取芝麻分普惠版失败')
            warnMsg('phhygz')
        }
        throw e
    }
}


async function notify_result(state, status, error_message) {
    try {
        if (status == 'true' || status == '1') {
            status = 'success'
        } else {
            status = 'fail'
        }
        let body = {
            order_id: state.order_id,
            status: status,
            msg: error_message
        }
        if (state.extras) {
            body.extras = state.extras
        }
        let row = await orm.partner_appKey(state.order_id);
        if(row.app_key === '619AF54B6B4F4915873154E3BDB06A59' || row.app_key === 'A02E142BAE8B4AC5B852E8E1FED15CC7' || row.app_key === '421ADA909326905ECD114935F1CFB83C'){
            body.cert_no = crypto.createHash('md5').update(row.cert_no, 'utf8').digest("hex").toUpperCase();
        }
        let len = Buffer.byteLength(JSON.stringify(body), 'utf8')
        let url = decodeURIComponent(state.redirect)
        let content = URL.parse(url);
        content.method = 'POST'
        content.headers = {
            'content-type': 'application/json',
            'content-length': len,
            'encoding': 'UTF-8'
        }
        console.log(content);
        if (content.protocol == 'https:') {
            request_https(content, body)
        } else {
            request_http(content, body)
        }
    } catch (e) {
        console.error('## ERROR ## notify_result ######\n ', state, '\n', e.message)
    }
}

function request_http(options, data) {
    var req = http.request(options, function (res) {
        //console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('UTF-8');
        res.on('data', function (chunk) {
            console.log('###### NOTIFY SUCCESS ####  :BODY: ' + chunk, JSON.stringify(data));
        });
        res.on('end', function () {
            console.log('###### NOTIFY SUCCESS ####  :END: ', options.href);
        });
    });

    req.on('error', function (chunk) {
        console.log('###### NOTIFY SUCCESS ####  :ERROR: ' + chunk, JSON.stringify(data));
    });
    req.write(JSON.stringify(data));
    req.end();
}

function request_https(options, data) {
    var req = https.request(options, function (res) {
        //console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('UTF-8');
        res.on('data', function (chunk) {
            console.log('###### NOTIFY SUCCESS ####  :BODY: ' + chunk, JSON.stringify(data));
        });
        res.on('end', function () {
            console.log('###### NOTIFY END ####  :END: ', options.href);
        });
    });

    req.on('error', function (chunk) {
        console.log('###### NOTIFY SUCCESS ####  :ERROR: ' + chunk, JSON.stringify(data));
    });
    req.write(JSON.stringify(data));
    req.end();
}

// let state = {
//     appKey: '6911223ABDBF4A0588E3A0B64E18ED3A',
//     order_id: '20180524100241444pJOmyJAcarpfguU',
//     channel: 'H5',
//     redirect: 'https://ti.51gjj.com/zmop/auth'
// }
//
// let p = {
//     open_id: '268806822853700383571348420',
//     error_message: '操作成功',
//     state: 'eyJhcHBLZXkiOiI2OTExMjIzQUJEQkY0QTA1ODhFM0EwQjY0RTE4RUQzQSIsIm9yZGVyX2lkIjoiMjAxODA1MjQxMDAyNDE0NDRwSk9teUpBY2FycGZndVUiLCJjaGFubmVsIjoiSDUiLCJyZWRpcmVjdCI6Imh0dHA6Ly90dC41MWdqai5jb206MTAwMzAvZGVtb2g1L2NiUmVzdWx0In0=',
//     error_code: 'SUCCESS',
//     app_id: '300002663',
//     success: 'true'
// }

/**
 *
 * @param {*} phone String 通知的电话号码    eg: '18857785871,17774010868'
 * @param {*} msg  String  短信内容         eg: [征信] 验签失败 / 征信重启了 + 时间
 * @param {*} type Number (不填)
 * eg： send_msg('17774010868,13685747781', '你喜欢黄炜吗？')  第一个参数，`,`后不能有空格
 */
function sendWarnMsg(phone, msg, type = 0) {
    return new Promise(function (resolve, reject) {
        let url = 'http://cf.51welink.com/submitdata/Service.asmx/g_Submit'
        let sprdid = '1012808'
        switch (type) {
            case 0:
                sprdid = '1012808'  //  行业通知短信
                break
            case 1:
                sprdid = '1012812'  //  会员营销短信
                break
            case 2:
                sprdid = '1012828'  //  语音行业短信
                break
            case 3:
                sprdid = '1012888'  //  行业触发短信
                break
        }
        let body = {
            'sname': 'jbwl51kqyx',  // 账号
            'spwd': 'zKtdTO9x',  // 密码
            'scorpid': '',  // 企业代码
            'sprdid': sprdid,  // 产品编号
            'sdst': phone,  // 手机号码
            'smsg': msg
        }  // 短信内容
        let options = {
            url: url,
            method: "POST",
            form: body,
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        }
        request(options, (e, r, vb) => {
            if (e) {
                console.log('[ 发送短信失败 ]', body.sdst, body.smsg)
                reject({code: -1, msg: '发送短信失败'})
            }
            else {
                try {
                    let state = vb.match(/\<State\>(\d)+?<\/State>/)[1]
                    if (state == 0) {
                        console.log('[ 发送短信成功 ]', body.sdst, body.smsg)
                        resolve({code: 0, msg: '发送短信成功'})
                    } else {
                        console.log('[ 发送短信失败 ]', body.sdst, body.smsg)
                        reject({code: -1, msg: '发送短信失败'})
                    }
                } catch (e) {
                    console.log('[ 发送短信失败 ]', body.sdst, body.smsg)
                    reject({code: -1, msg: '发送短信失败'})
                }

            }
        })
    })
}

//  选择app_id
async function get_app_id(cert_no) {
    try {
        let rows = await orm.authed(cert_no)
        if (rows.length == 0) {
            return await orm.payload_app_id()
        } else {
            return rows[0].app_id
        }
    } catch (e) {
        throw e
    }
}

let msgCount = {
    zmf: 0,
    hygz: 0,
    phzmf: 0,
    phhygz: 0
};

function warnMsg(type) {
    
    let msgInfo = {
        zmf: '芝麻分获取失败',
        hygz: '行业关注名单获取失败',
        phzmf: '普惠芝麻分获取失败',
        phhygz: '普惠行业关注名单获取失败'
    }
    msgCount[type]++;
    if (msgCount[type] >= 100) {
        sendWarnMsg('17774010868,18805819680', msgInfo[type]);
        msgCount[type] = 0;
    }

}



module.exports = {
    //is_authed,
    save_score,
    save_watch_list,
    save_brief_score,
    save_brief_watch_list,
    notify_result,
    sendWarnMsg,
}
