const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const NodeRSA = require('node-rsa');


// def sign(privatekey, data):
//     '''
//     加签
//     :param privatekey:私钥文件路径
//     :param data:要加签的数据
//     :return string:签名
//     '''
//     signEVP = EVP.load_key(privatekey)
//     signEVP.sign_init()
//     signEVP.sign_update(data)
//     result = signEVP.sign_final()
//     return base64.b64encode(result)


const private_key = fs.readFileSync(path.join(__dirname, 'keys/private_key.pem')).toString()

const ant_public_key = {}
ant_public_key['2018042460057138'] = fs.readFileSync(path.join(__dirname, 'keys/2018042460057138_ant_public_key.pem')).toString()
ant_public_key['2018051160085345'] = fs.readFileSync(path.join(__dirname, 'keys/2018051160085345_ant_public_key.pem')).toString()
ant_public_key['2018051560161652'] = fs.readFileSync(path.join(__dirname, 'keys/2018051560161652_ant_public_key.pem')).toString()
ant_public_key['2018060760276862'] = fs.readFileSync(path.join(__dirname, 'keys/2018060760276862_ant_public_key.pem')).toString()
ant_public_key['2018062860440367'] = fs.readFileSync(path.join(__dirname, 'keys/2018062860440367_ant_public_key.pem')).toString()
ant_public_key['2018062860428388'] = fs.readFileSync(path.join(__dirname, 'keys/2018062860428388_ant_public_key.pem')).toString()
ant_public_key['2018070560531397'] = fs.readFileSync(path.join(__dirname, 'keys/2018070560531397_ant_public_key.pem')).toString()
ant_public_key['2018072660760379'] = fs.readFileSync(path.join(__dirname, 'keys/2018072660760379_ant_public_key.pem')).toString()
ant_public_key['2018062660437189'] = fs.readFileSync(path.join(__dirname, 'keys/2018062660437189_ant_public_key.pem')).toString()
ant_public_key['2018080760936372'] = fs.readFileSync(path.join(__dirname, 'keys/2018080760936372_ant_public_key.pem')).toString()
ant_public_key['2018062960509010'] = fs.readFileSync(path.join(__dirname, 'keys/2018062960509010_ant_public_key.pem')).toString()
ant_public_key['2018092861524698'] = fs.readFileSync(path.join(__dirname, 'keys/2018092861524698_ant_public_key.pem')).toString()
ant_public_key['2018092861534661'] = fs.readFileSync(path.join(__dirname, 'keys/2018092861534661_ant_public_key.pem')).toString()
ant_public_key['2018092961567412'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961567412_ant_public_key.pem')).toString()
ant_public_key['2018092961498814'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961498814_ant_public_key.pem')).toString()
ant_public_key['2018092961519845'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961519845_ant_public_key.pem')).toString()
ant_public_key['2018092961513806'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961513806_ant_public_key.pem')).toString()
ant_public_key['2018092961495835'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961495835_ant_public_key.pem')).toString()
ant_public_key['2018092961504848'] = fs.readFileSync(path.join(__dirname, 'keys/2018092961504848_ant_public_key.pem')).toString()
//params= URLEncode(Base64(RSAEncrypt(param1=URLEncode(param1value)&param2=URLEncode(param2value))))
// 加签
// :param privatekey:私钥文件路径
// :param data:要加签的数据
// :return string:签名
function RSAEncrypt(data) {
    let str = params2str(data)
    let key = new NodeRSA(private_key)
    key.setOptions({encryptionScheme: 'pkcs1'});
    let encrypted = key.encrypt(str, 'base64')
    return encrypted
}

function RSADecrypt(str) {
    let key = new NodeRSA(private_key)
    key.setOptions({encryptionScheme: 'pkcs1'});
    let encrypted = key.decrypt(str, 'utf8')
    return encrypted
}

//  转换业务参数为str
function params2str(data) {
    let str = ''
    for (let k of Object.keys(data).sort()) {
        let v = data[k]
        if (Object.prototype.toString.call(v) === '[object Object]') {
            v = JSON.stringify(v)
        }
        str += k + '=' + v + '&'
    }
    return str.slice(0, str.length - 1)
}


//  str 转为 json
function str2params(str) {
    let ret = {}
    let arr = str.split('&')
    for (let item of arr) {
        let index = item.indexOf('=')
        ret[item.slice(0, index)] = decodeURIComponent(item.slice(index + 1))
    }
    return ret
}


//  加签
function sign(data) {
    let str = params2str(data)
    let sign = crypto.createSign('RSA-SHA256')
    sign.update(str)
    return sign.sign(private_key, 'base64')
}


//  验签
//  sign_value: 签名,
//  str: 待验签的数据
function verify(sign_value, str, app_id) {
    var verify = crypto.createVerify('RSA-SHA256');
    verify.update(str);
    return verify.verify(ant_public_key[app_id], sign_value, 'base64')
}


 // let resp = { alipay_system_oauth_token_response:
 //    { access_token: 'authzmaBd3a9fe8c041843cdbd01cb6ba1c4fX48',
 //      alipay_user_id: '20881049053508330572421081610248',
 //      expires_in: 31536000,
 //      re_expires_in: 31622400,
 //      refresh_token: 'authzmaB6991f8567e38405c85803d5023550X48',
 //      user_id: '2088802182470482' },
 //   sign: 'LriQN3gcY177GL1SPqGqsnD1YuJdR9qKg4fSaS8V3KNXF/Fi2I0eDSK0t8o0lAHB3AgHF6YyD7+VwtO/pKc9yZpbTIVSrCm2kFaEJGaJgG7F7sh+CNEZnNE69usW50Y7LQUGPy8olr2+LnE6eyM4xR9KlYDTCP4RA+K0OlFSKz8V0ylwgC0H9nij+le3pyQZdESarLGMuZk24+a49lYgZfjsnI6rf2DkrCN1/0RNNuIGqS2XtXBuQCY15gzBIyY9ux65YIvEoc+LUKTyNOpXvBeQYP9JzkQqc7Nkh1f6lozcrNtoxdP8ltZU/dW3/2TpIQ4oQ1J2ztezmamZvTxjDg==' }
 //    if (verify(resp.sign, JSON.stringify(resp.alipay_system_oauth_token_response), '2018051560161652')) {
 //        console.log('success')
 //    } else {
 //        console.log('error')
 //    }

// let a = {
//     apiname: 'com.alipay.account.auth',
//     method: 'alipay.open.auth.sdk.code.get',
//     app_id: 2018042460057138,
//     app_name: 'mc',
//     biz_type: 'openservice',
//     pid: 2088031974398640,
//     product_id: 'APP_FAST_LOGIN',
//     scope: 'kuaijie',
//     target_id: 'kkkkk091125',
//     auth_type: 'AUTHACCOUNT',
//     sign_type: 'RSA2',
// }

// a.sign = encodeURIComponent(sign(a))
// console.log(sign('app_id=2018042460057138&amp;charset=utf-8&amp;code=1558df8e1bd2409dafeb9f428075SX48&amp;format=JSON&amp;grant_type=authorization_code&amp;method=alipay.system.oauth.token&amp;sign_type=RSA2&amp;timestamp=2018-05-03 16:40:45&amp;version=1.0'));


module.exports = {
    sign,
    verify,
    RSAEncrypt,
    RSADecrypt,
    params2str,
    str2params
}
