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

var server_url   = config.get('service_url');
var server_url_2 = config.get('service_url_2');

/*************************************************************************************
 * Description: updateOrderStatus
 *              (thxd/updateThxdTaskStatus) 更新通话详单任务状态 http://120.26.227.26/index.php?s=/38&page_id=473
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: orderId，  String 订单号
 *              taskId，   String 任务Id
 *              status，   String 任务状态
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function updateOrderStatus(orderId, taskId, status) {

    return new Promise((resolve, reject) => {
        let form_data = {
            orderSn: orderId,
            taskId: taskId,
            status: status
        };
        let options = {
            url: server_url + 'thxd/updateThxdTaskStatus',
            method: "POST",
            form: form_data,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        };
        request(options,(e,r,b)=>{
            if(e) {
                // console.error('[updateOrderStatus] error: ' + JSON.stringify(e));
                reject(e);
            }
            else {
                b = JSON.parse(b);
                console.log('[updateOrderStatus] b: ' + JSON.stringify(b));
                resolve(b);
            }
        })
    })

}

/*************************************************************************************
 * Description: getThxdCitySettings
 *              (thxd/getThxdCitySettings) 获取通话详单城市配置 http://120.26.227.26/index.php?s=/38&page_id=475
 *      Author: xaj
 *        Date: 2017/5/27
 *   Parameter: appKey,    String 标识符
 *              token，    String 访问令牌
 *              province， String 手机号省份信息
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getThxdCitySettingsForPhoneHtml(appKey, token, province) {
    return new Promise((resolve, reject) => {
        let url = server_url + 'thxd/getThxdCitySettings/?appKey=' + appKey + '&token=' + token + '&provName=' + encodeURI(province)
        rp(url)
            .then(data => {
                data = JSON.parse(data);
                resolve(data)
            })
            .catch(err => {
                console.error('[getThxdCitySettings] getThxdCitySettingsForPhoneHtml error: ' + JSON.stringify(err));
                reject(err)
            })
    })
}

/*************************************************************************************
 * Description: getThxdCitySettings
 *              (thxd/getThxdCitySettings) 获取通话详单城市配置 http://120.26.227.26/index.php?s=/38&page_id=475
 *        Date: 2017/5/27
 *   Parameter: appKey,    String 标识符
 *              token，    String 访问令牌
 *              province， String 手机号省份信息
 *              type，     String 运营商名称
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getThxdCitySettingsForFormHtml(appKey, token, province, type) {
    return new Promise((resolve, reject) => {
        let url = server_url + 'thxd/getThxdCitySettings/?appKey=' + appKey + '&token=' + token + '&provName='
            + encodeURI(province) + '&operatorTypeName=' + encodeURI(type.substr(-2,2));
        rp(url)
            .then(data=> {
                data = JSON.parse(data)
                // console.log(data.data.citySetting.queryStepParam[0].loginParam)
                resolve(data)
            })
            .catch(err => {
                reject(err)
            })
    })
}


/*************************************************************************************
 * 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 = server_url + "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);
            }
        })
    })

}

/*************************************************************************************
 * Description: getThxdStatus  (thxd/queryThxdTaskStatus) 查询通话详单任务状态 http://120.26.227.26/index.php?s=/38&page_id=474
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: orderId,   String 订单Id
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getThxdStatus(orderId) {
    return new Promise((resolve, reject) => {
        // let reqUrl = server_url +  "thxdDataService/queryThxdTaskStatus?orderSn=" + orderId;
        let reqUrl = server_url +  "thxd/queryThxdTaskStatus?orderSn=" + orderId;
        rp(reqUrl)
            .then(data => {
                resolve(data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/*************************************************************************************
 * Description: createThxdTask
 *              (thxdServices/createThxdTask) 用户在选择好城市后创建通话详单任务 http://120.26.227.26/index.php?s=/23&page_id=337
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: cityId,    String 城市Id
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function createThxdTask(cityId) {
    return new Promise((resolve, reject) => {
        let form_data = {cityId: cityId};
        let url = server_url_2 + 'thxdServices/createThxdTask';
        let options = {
            url: url,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options, (e, r, b) => {
            if (e) {
                console.log('[createThxdTask]  error: ' + JSON.stringify(e))
                reject(e)
            } else {
                console.log("[createThxdTask]  create TaskId");
                console.log("[createThxdTask]  b: " + JSON.stringify(b));
                resolve(b);
            }
        });
    })
}

/*************************************************************************************
 * Description: queryThxd
 *              (thxdServices/queryThxd) 查询通话详单接口 API文档：http://120.26.227.26/index.php?s=/23&page_id=339
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: data,      String 请求参数
 *   Parameter: orderId,   String 订单Id
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function queryThxd(data, taskId) {
    return new Promise((resolve, reject) => {
        console.log('[queryThxd] args data: %s, taskId: %s', JSON.stringify(data), taskId)
        let form_data = {
            data: data,
            taskId: taskId,
            callbackUrl: "https://t.51gjj.com/query/taskId/result"
        }
        let url = server_url_2 + 'thxdServices/queryThxd';
        let options = {
            url: url,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options, (e, r, b) => {
            if (e) {
                console.log('[queryThxd] error: ' + JSON.stringify(e));
                reject(e)
            } else {
                console.log('[queryThxd] b:' + JSON.stringify(b));
                resolve(b)
            }
        })
    })
}

/*************************************************************************************
 * Description: getThxdData (thxdServices/getThxdData) 查询通话详单任务
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: taskId,   String 任务Id
 *    Callback: promise
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function getThxdData(taskId) {
    return new Promise((resolve, reject) => {
        let form_data = {taskId: taskId};
        let url = server_url_2 + 'thxdServices/getThxdData';
        var options = {
            url: url,
            method: "POST",
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options, function (e, r, b) {
            if (e) {
                console.log('[getThxdData] error: ' + JSON.stringify(e));
                reject(e);
            } else {
                console.log('[getThxdData] success b: ' + JSON.stringify(b))
                resolve(b);
            }
        })
    })
}

/*************************************************************************************
 * Description: uploadDataToAnalysis
 *      Author: xaj
 *        Date: 2017/5/31
 *   Parameter: data,     {}
 *              taskId,   String 订单Id
 *    Callback:
 *      Return: N/A
 *     Caution:
 *************************************************************************************/
function uploadDataToAnalysis(data, taskId) {
    let url = 'http://112.124.121.109:3001/dataProcessing';
    let form_data = {
        data: data,
        callbackUrl: 'https://t.51gjj.com/query/taskId/dataProcessingResult',
        orderId: taskId
    };
    var options = {
        url: url,
        method: "POST",
        json: true,
        body: form_data,
        headers: {
            'content-type': 'application/json'
        }
    };
    request(options, (e, r, b) => {
        if (e) {
            console.error('[uploadDataToAnalysis] dataProcessing error: ' + JSON.stringify(e));
        }
        else {
            console.log('[uploadDataToAnalysis] dataProcessing error: ' + JSON.stringify(b));
        }
    })
}

/*************************************************************************************
 * 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 = server_url + "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));
                reject(e);
            }else{
                console.log('[getToken] success result: ' + JSON.stringify(b));
                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 = server_url + "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);
            }
        })
    })
}

exports.getThxdStatus = getThxdStatus;
exports.createThxdTask = createThxdTask;
exports.queryThxd = queryThxd;
exports.getThxdData = getThxdData;
exports.signValidityCheck = signValidityCheck;
exports.updateOrderStatus = updateOrderStatus;
exports.uploadDataToAnalysis = uploadDataToAnalysis;
exports.getThxdCitySettingsForFormHtml = getThxdCitySettingsForFormHtml;
exports.getThxdCitySettingsForPhoneHtml = getThxdCitySettingsForPhoneHtml;
exports.getToken = getToken;
exports.getOrderSn = getOrderSn;
