const rp = require('request-promise'),
    request = require('request'),
    moment = require('moment'),
    iconv = require('iconv-lite'),
    fs = require('fs'),
    rsa = require('./rsa'),
    orm = require('../orm'),
    extend = require('extend'),
    log = console.log.bind(console),
    error = console.error.bind(console)


function build_transaction_id() {
    let t = moment().format('YYYYMMDDHHmmssSSS')
    let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
    while (t.length < 32) {
        t += str[Math.round(Math.random() * (str.length - 1))]
    }
    return t
}


//  芝麻分
async function score(app_id, auth_token, user_id) {
    let transaction_id = build_transaction_id()
    let data = {
        app_id: app_id,
        method: 'zhima.credit.score.get',
        format: 'JSON',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
        version: '1.0',
        auth_token: auth_token,
        biz_content: JSON.stringify({transaction_id: transaction_id, product_code: 'w1010100100000000001'}),
    }
    data.sign = rsa.sign(data, app_id)
    let p = formatUrl(data)
    let resp = await rp.post({
        url: p.url,
        form: p.execParams,
        json: true
    })
    let row = {
        transaction_id: transaction_id,
        resp: JSON.stringify(resp),
        open_id: user_id,
        platform: 'alipay',
        method: 'score'
    }
    log('zmop_score resp: ', resp)
    await orm.create_api_task(row)
    if (resp.zhima_credit_score_get_response.code != '10000') {
        return resp.zhima_credit_score_get_response
    }
    if (rsa.verify(resp.sign, JSON.stringify(resp.zhima_credit_score_get_response), app_id)) {
        return resp.zhima_credit_score_get_response
    } else {
        error('API-[ alipay/score ] 验签失败| app_id: ', app_id)
        throw new Error('验签失败')
    }
}

//  行业关注名单
async function watch_list(app_id, auth_token, user_id) {
    let transaction_id = build_transaction_id()
    let data = {
        app_id: app_id,
        method: 'zhima.credit.watchlistii.get',
        format: 'JSON',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
        version: '1.0',
        auth_token: auth_token,
        biz_content: JSON.stringify({transaction_id: transaction_id, product_code: 'w1010100100000000022'}),
    }
    data.sign = rsa.sign(data, app_id)
    let p = formatUrl(data)
    let resp = await rp.post({
        url: p.url,
        form: p.execParams,
        json: true
    })
    let row = {
        transaction_id: transaction_id,
        resp: JSON.stringify(resp),
        open_id: user_id,
        platform: 'alipay',
        method: 'watch_list'
    }
    log('zmop_score resp: ', resp)
    await orm.create_api_task(row)
    if (resp.zhima_credit_watchlistii_get_response.code != '10000') {
        return resp.zhima_credit_watchlistii_get_response
    }
    if (rsa.verify(resp.sign, JSON.stringify(resp.zhima_credit_watchlistii_get_response), app_id)) {
        return resp.zhima_credit_watchlistii_get_response
    } else {
        console.error('API-[ alipay/score ] 验签失败| app_id: ', app_id)
        throw new Error('验签失败')
    }
}


//  芝麻分普惠版
async function brief_score(app_id, cert_no, cert_name, admit_score) {
    let transaction_id = build_transaction_id()
    let data = {
        app_id: app_id,
        method: 'zhima.credit.score.brief.get',
        format: 'JSON',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
        version: '1.0',
        biz_content: JSON.stringify({
            transaction_id: transaction_id,
            product_code: 'w1010100000000002733',
            cert_type: 'IDENTITY_CARD',
            cert_no: cert_no,
            name: cert_name,
            admittance_score: admit_score,
        }),
    }
    data.sign = rsa.sign(data, app_id)
    let p = formatUrl(data)
    let resp = await rp.post({
        url: p.url,
        form: p.execParams,
        json: true
    })
    log('zmop_brief_score resp: ', resp)
    let row = {
        transaction_id: transaction_id,
        resp: JSON.stringify(resp),
        open_id: cert_no,
        platform: 'alipay',
        method: 'brief_score'
    }
    await orm.create_api_task(row)
    if (resp.zhima_credit_score_brief_get_response.code != '10000') {
        return resp.zhima_credit_score_brief_get_response
    }
    if (rsa.verify(resp.sign, JSON.stringify(resp.zhima_credit_score_brief_get_response), app_id)) {
        return resp.zhima_credit_score_brief_get_response
    } else {
        error('API-[ alipay/score ] 验签失败| app_id: ', app_id)
        throw new Error('验签失败')
    }
}

// setTimeout(async () => {
//
//     let a = await score('2018042460057138', 'authzmaBc696f4cdee00454782876eca3f31dD48', '2088802182470482', '700')
// })

//  行业关注名单普惠版
async function brief_watch_list(app_id, cert_no, cert_name) {
    let transaction_id = build_transaction_id()
    let data = {
        app_id: app_id,
        method: 'zhima.credit.watchlist.brief.get',
        format: 'JSON',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
        version: '1.0',
        biz_content: JSON.stringify({
            transaction_id: transaction_id,
            product_code: 'w1010100000000002977',
            cert_type: 'IDENTITY_CARD',
            cert_no: cert_no,
            name: cert_name,
        }),
    }
    data.sign = rsa.sign(data, app_id)
    let p = formatUrl(data)
    let resp = await rp.post({
        url: p.url,
        form: p.execParams,
        json: true
    })
    let row = {
        transaction_id: transaction_id,
        resp: JSON.stringify(resp),
        open_id: cert_no,
        platform: 'alipay',
        method: 'brief_watch_list'
    }
    log('zmop_brief_watch_list resp: ', resp)
    await orm.create_api_task(row)
    if (resp.zhima_credit_watchlist_brief_get_response.code != '10000') {
        return resp.zhima_credit_watchlist_brief_get_response
    }
    if (rsa.verify(resp.sign, JSON.stringify(resp.zhima_credit_watchlist_brief_get_response), app_id)) {
        return resp.zhima_credit_watchlist_brief_get_response
    } else {
        error('API-[ alipay/score ] 验签失败| app_id: ', app_id)
        throw new Error('验签失败')
    }
}

async function access_token(app_id, auth_code,) {
    let data = {
        app_id: app_id,
        method: 'alipay.system.oauth.token',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
        version: '1.0',
        grant_type: 'authorization_code',
        code: auth_code
    }
    data.sign = rsa.sign(data, app_id)
    let resp = await rp.post({
        url: 'https://openapi.alipay.com/gateway.do',
        json: true,
        form: data
    })
    console.log('##### Access_token #####\n', resp)
    if (resp.error_response) {
        return resp.error_response
    }
    if (rsa.verify(resp.sign, JSON.stringify(resp.alipay_system_oauth_token_response), app_id)) {
        console.log('access_token: ', resp)
        return resp.alipay_system_oauth_token_response
    } else {
        error('API-[ alipay/access_token ] 验签失败| app_id: ', app_id)
        throw new Error('验签失败')
    }
}


module.exports = {
    build_transaction_id,
    access_token,
    score,
    watch_list,
    brief_score,
    brief_watch_list,
}

function formatUrl(params) {
    let requestUrl = 'https://openapi.alipay.com/gateway.do';
    // 需要放在 url 中的参数列表
    const urlArgs = [
        'app_id', 'method', 'format', 'charset',
        'sign_type', 'sign', 'timestamp', 'version',
        'notify_url', 'return_url', 'auth_token', 'app_auth_token',
    ];
    for (const key in params) {
        if (urlArgs.includes(key)) {
            const val = encodeURIComponent(params[key]);
            requestUrl = `${requestUrl}${requestUrl.includes('?') ? '&' : '?'}${key}=${val}`;
            // 删除 postData 中对应的数据
            delete params[key];
        }
    }
    return {execParams: params, url: requestUrl};
}

// brief_watch_list('2018051160085345', '370882199212085812', '肖爱江').then(r => {
//     log(r)
// }).catch(e => {
//     log(e)
// })