/**
 * Created by xaj on 2017/5/26.
 */
var rp      = require('request-promise');
var request = require('request');
var config = require('config')

var tj1   = config.get('tj1');
var tj2 = config.get('tj2');


/*************************************************************************************
 * Description: getToken
 *      Author: xaj
 *        Date: 2017/6/05
 *   Parameter: body       Obeject    传进来的参数
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getToken(body) {
    return new Promise((resolve, reject) => {
        let form_data = body
        let reqUrl = tj2 + "access/getToken";
        let options= {
            url: reqUrl,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options,(e,r,b)=>{
            if(e){
                console.error('[getToken] error: ' + JSON.stringify(e),JSON.stringify(body));
                reject(e);
            }else{
                console.log('[getToken] success result: ' + JSON.stringify(b),JSON.stringify(body));
                resolve(b);
            }
        })
    })
}

/*************************************************************************************
 * Description: getOrderSn
 *      Author: xaj
 *        Date: 2017/6/05
 *   Parameter: body      Object	传进来的参数
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getOrderSn(body) {
    return new Promise((resolve, reject) => {
        let form_data = body;
        let reqUrl = tj2 + "order/getOrderSn";
        let options= {
            url: reqUrl,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options,(e,r,b)=>{
            if(e){
                console.error('[getOrderSn] error: ' + JSON.stringify(e));
                reject(e);
            }else{
                console.log('[getOrderSn] success result: ' + JSON.stringify(b));
                resolve(b);
            }
        })
    })
}

/*************************************************************************************
 * Description: 检查签名是否失效
 *      Author: xaj
 *        Date: 2017/5/27
 *   Parameter: body,      Object 传进来的参数
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function signValidityCheck(body) {
    return new Promise((resolve, reject) => {
        let form_data = body;
        let url = tj2 + "access/signValidityCheck";
        let options= {
            url: url,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options,(e,r,vb)=>{
            if(e) {
                console.error('[signValidityCheck] signValidityCheck error: ' + JSON.stringify(e));
                reject("服务器维护")
            }
            else {
                console.log('[signValidityCheck] signValidityCheck success: ' + JSON.stringify(vb));
                resolve(vb);
            }
        })
    })

}

async function app_key_info(app_key) {
    try {
        let resp = await rp.get({
            url: tj2 + 'customer/query/?appKey=' + app_key,
            json: true
        })
        if (resp.code == 0) {
            if (resp.data.customerList.length > 0) {
                return resp.data.customerList[0]
            } else {
                throw new Error('无效的appKey')
            }
        } else {
            throw new Error('API-[app_key_info] error ', resp)
        }
    } catch (e) {
        throw e
    }
}



async function getMicaiUrl(name, card, phone, returnUrl) {
    try {
        let baseUrlOfZzb = `http://47.96.253.64/zm/?m=getzmurl&name=${encodeURIComponent(name)}&card=${card}&phone=${phone}&returnUrl=${encodeURIComponent(returnUrl)}`
        console.log('[getMicaiUrl] res: ', baseUrlOfZzb)
        let resp = await rp.get({
            url: baseUrlOfZzb,
            json: true
        })
        console.log('[getMicaiUrl] res: ', resp)
        return resp;
    } catch (e) {
        console.error('[getMicaiUrl] try catch error: ', e);
        return {code: -1, msg: '系统错误'}
    }
}
async function getMicaiHymdUrl(name, card, phone) {
    try {
        let baseUrlOfZzb = `http://47.96.253.64/zm/?m=gethydata&name=${encodeURIComponent(name)}&card=${card}&phone=${phone}`
        console.log('[getMicaiHymdUrl] res: ', baseUrlOfZzb)
        let resp = await rp.get({
            url: baseUrlOfZzb,
            json: true
        })
        console.log('[getMicaiHymdUrl] res: ', resp)
        return resp;
    } catch (e) {
        console.error('[getMicaiHymdUrl] try catch error: ', e);
        return {code: -1, msg: '系统错误'}
    }
}


async function rc4Deciper(data) {
    try {
        let baseUrlOfZzb = `http://47.96.253.64/zm/?m=getzmdata&data=${encodeURIComponent(data)}`
        let resp = await rp.get({
            url: baseUrlOfZzb,
            json: true,
            // body: data
        })
        console.log('[rc4Deciper] success: ', resp, typeof resp);
        return resp;
    } catch (e) {
        console.error('[rc4Deciper] try catch error: ', e);
        return {code: -1, msg: '系统错误'}
    }
}


/**
 * @description 获取Lingwa芝麻认证链接
 * @author xaj
 * @param {*} name 姓名
 * @param {*} idcard 身份证
 * @param {*} phone 手机号
 */
function getLingwaUrl(name, idcard, phone, returnUrl) {

    return new Promise((resolve, reject) => {
        let form_data = {
            appId: '60120098',
            appKey: '2cbe25a398530a38ea47ce72f5efc149',
            name: name,
            phone: phone,
            idcard: idcard,
            returnUrl: encodeURIComponent(returnUrl),
        };
        let options = {
            url: 'https://api.wqd360.cn/services/zm/getAuthUrl',
            method: "POST",
            form: form_data,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        };
        request(options, (e, r, b)=>{
            if(e) {
                console.error('[getLingwaUrl] error: ' + JSON.stringify(e));
                reject(e);
            }
            else {
                b = JSON.parse(b);
                console.log('[getLingwaUrl] b: ' + JSON.stringify(b));
                resolve(b);
            }
        })
    })

}

/**
 * @description 获取Lingwa芝麻分
 * @author xaj
 * @param {*} name 姓名
 * @param {*} idcard 身份证
 * @param {*} phone 手机号
 * @returns 
 */
function getLingwaScore(name, idcard, phone) {

    return new Promise((resolve, reject) => {
        let form_data = {
            appId: '60120098',
            appKey: '2cbe25a398530a38ea47ce72f5efc149',
            name: name,
            phone: phone,
            idcard: idcard,
        };
        let options = {
            url: 'https://api.wqd360.cn/services/zm/getScore',
            method: "POST",
            form: form_data,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        };
        request(options, (e, r, b)=>{
            if(e) {
                console.error('[getLingwaScore] error: ' + JSON.stringify(e));
                reject(e);
            }
            else {
                b = JSON.parse(b);
                console.log('[getLingwaScore] b: ' + JSON.stringify(b));
                resolve(b);
            }
        })
    })

}

/**
 * @description 获取Lingwa行业关注名单
 * @author xaj
 * @param {*} name 姓名
 * @param {*} idcard 身份证
 * @param {*} phone 手机号
 * @returns 
 */
function getLingwaWatchlist(name, idcard, phone) {

    return new Promise((resolve, reject) => {
        let form_data = {
            appId: '60120098',
            appKey: '2cbe25a398530a38ea47ce72f5efc149',
            name: name,
            phone: phone,
            idcard: idcard,
        };
        let options = {
            url: 'https://api.wqd360.cn/services/zm/getWatchList',
            method: "POST",
            form: form_data,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        };
        request(options, (e, r, b)=>{
            if(e) {
                console.error('[getLingwaUrl] error: ' + JSON.stringify(e));
                reject(e);
            }
            else {
                b = JSON.parse(b);
                console.log('[getLingwaUrl] b: ' + JSON.stringify(b));
                resolve(b);
            }
        })
    })

}


/*统计访问记录*/
function analysisReq(req) {
    let url = "http://tt.51gjj.com:20001/getDev";
    let bodyReq = {'req': req}
    let options = {
        url: url,
        method: "POST",
        json: true,
        body: bodyReq,
        headers: {
            'content-type': 'application/json'
        }
    }
    request(options, (e, r, b) => {
        if (e) {
            console.error('[analysisReq] error: ', e)
        } else {
            console.log('[analysisReq] success: ', b)
        }
    })
}

// app_key_info('122818D0E79CCEB3B8D3D6BB51BF615E').then(r=>{console.log(r)}).catch(e=>{console.log(e)})

exports.getToken = getToken;
exports.app_key_info = app_key_info;
exports.getOrderSn = getOrderSn;
exports.signValidityCheck = signValidityCheck;

exports.getMicaiUrl = getMicaiUrl;
exports.rc4Deciper = rc4Deciper;getMicaiHymdUrl
exports.getMicaiHymdUrl = getMicaiHymdUrl;

exports.getLingwaUrl = getLingwaUrl;
exports.getLingwaScore = getLingwaScore;
exports.getLingwaWatchlist = getLingwaWatchlist;


exports.analysisReq = analysisReq;