const express = require('express');
const router = express.Router();
const request = require('request');
const rp = require('request-promise');
let callbackMap = new Map();

const config = require('doohanpub').config;
const tj1 = config.get('tj1');
const mongoUrl = config.get('mongoUrl');
const host = config.get('host');
const hexinUrl = config.get('hexinUrl');
const sbService = config.get('sbService');
const signService = config.get('signService');


//社保任务相关的三个接口
const createTaskUrl = sbService + '/shebao/createSbTask';
const commitJobUrl = sbService + '/shebao/loginSbWeb';
const getCodeUrl = sbService + '/shebao/getSbCode';

//验证签名相关的四个接口
const signVUrl = signService + '/Access/SignValidityCheck';
const getTokenUrl = signService + '/Access/GetToken';
const getOrderSnUrl = signService + '/Order/GetOrderSn';
const getCustomerUrl = signService + '/customer/query'


//拉取登录参数接口
const getParamsUrl = hexinUrl + ':8001/JBService/GetLoginParam/sb/';

//获取城市配置，暂时自api接口获取
const getCityUrl = host + '/shebaoapi/getCity';
const myCallbackUrl = host + '/shebao/ws/result';

//存入Mongn数据库接口
const getDataUrl = mongoUrl + ':11250/shebao/';

const dealhtml = require('../../lib/showData').dealhtml;
const getParam = require('./sbFuncLib').getParam;
const getHelpPage = require('./sbFuncLib').getHelpPage;
const InsertStatus = require('./sbFuncLib').InsertStatus;
const InsertCusStatus = require('./sbFuncLib').InsertCusStatus;
const QueryStatus = require('./sbFuncLib').QueryStatus;
const getCusList = require('./sbFuncLib').getCusList;
const UpdateStatus = require('./sbFuncLib').UpdateStatus;
const queryCusStatus = require('./sbFuncLib').queryCusStatus;
const getNEWOrderSnUrl = "http://t.51gjj.com:10099/getOrderSn";

const cipherL = require('./cipherL');
function CheckParams() {
}
CheckParams.prototype = {
    getCode: function (reqBody) {
        if (!(reqBody.taskId && reqBody.type)) {
            return { code: -1, msg: '请求参数缺失' };
        }
        return { code: 0 };
    },
    getIndex: function (reqQuery) {
        if (!(reqQuery.appKey && reqQuery.token && reqQuery.timestamp && reqQuery.orderSn && reqQuery.sign && reqQuery.redirectUrl)) {
            return { code: -1, msg: '请求参数缺失' };
        }
        let regOrderId = /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/;
        if (!regOrderId.test(reqQuery.orderSn)) {
            return { code: -1, msg: 'orderSn错误' };
        }
        return { code: 0 };

    },
    getCity: function (reqQuery) {
        if (!reqQuery.cid) {
            return { code: -1, msg: '参数错误' };
        }
        return { code: 0 };

    },
    createJob: function (reqBody) {
        if (!(reqBody.cid && reqBody.orderSn && reqBody.appKey)) {
            return { code: -1, msg: '参数错误' };
        }
        let regOrderId = /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/;
        if (!regOrderId.test(reqBody.orderSn)) {
            return { code: -1, msg: 'orderSn错误' };
        }
        return { code: 0 };
    },
    getData: function (reqBody) {
        if (!(reqBody.sign && reqBody.params && reqBody.params.orderSn && reqBody.type)) {
            return { code: -1, msg: '请求参数缺失' };
        }
        let regOrderId = /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/;
        if (!regOrderId.test(reqBody.params.orderSn)) {
            return { code: -1, msg: 'orderSn错误' };
        }
        if (reqBody.type !== 'shebao') {
            return { code: -1, msg: '参数错误' };
        }
        return { code: 0 };
    }
};
var checkParams = new CheckParams();

/* GET home page. */
let cityData;
let cityDataMap = new Map();
let cityListHtml;
let cityJSON = []
getCityInfo();
getCallbackMap();
setInterval(function () {
    getCityInfo();
    getCallbackMap();
}, 1000 * 60 * 2);
function getCallbackMap() {
    rp(getCustomerUrl).then(customers => {
        customers = JSON.parse(customers);
        if (customers.code == '0') {
            customers.data.customerList.map(customer => {
                if ('callBackUrl' in customer) {
                    callbackMap.set(customer.appKey, { callbackUrl: customer.callBackUrl });
                }
            });
        }
    }).catch(err => {
        console.log(err);
    });
}
function getCityInfo() {
    rp(getCityUrl)
        .then(data => {
            data = JSON.parse(data);
            if (data.code == 0) {
                cityJSON = JSON.stringify(data);
                cityJSON = JSON.parse(cityJSON);
                cityJSON.data.map(item => {
                    item.citys.map(item => {
                        delete item.queryParam
                    })
                })
                cityData = data;

                creatCityListHtml(cityData);
            } else {
                console.log('getCitySettingFailure' + JSON.stringify(data));
            }
        })
        .catch(err => {
            console.log(err);
            console.log('[GJJ]获取城市配置出错');
        });
}
function getNewOrderSn() {
    return new Promise(function (resolve, reject) {
        let options = {
            url: getNEWOrderSnUrl,
            method: "POST",
            json: true,
            body: {timestamp: new Date().getTime(), type: "shebao"},
            headers: {
                'content-type': 'application/json'
            }
        }
        request(options, (e, r, b) => {
            if (e) {
                reject(e)
            } else {
                if (b.code === 0) {
                    resolve(b.data.orderSn)
                } else {
                    reject(b)
                }

            }
        })
    })

}
function signValidityCheck(form_data) {
    return new Promise((resolve, reject) => {
        let options = {
            url: signVUrl,
            method: 'POST',
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        };
        request(options, (e, r, vb) => {
            if (e) {
                console.error('[GJJ][signValidityCheck] signValidityCheck error: ' + JSON.stringify(e));
                reject('服务器维护');
            }
            else {
                resolve(vb);
            }
        });
    });

}
function getHelppage(cid, loginParams) {
    let helpPage = getHelpPage(cid);
    let html = createLoginHTML(loginParams, helpPage);
    return { html: html, dark: helpPage.content };
}

/*统计访问记录*/
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'
        }
    }

    return new Promise((resolve, reject) => {
        request(options, (e, r, b) => {
            if (e) {
                console.error('[analysisReq] error: ', e)
                reject(e);
            } else {
                console.log('[analysisReq] success: ', b)
                resolve(b);
            }
        })
    })
}


router.get('/', function (req, res, next) {
    console.log('【Router root】Req' + JSON.stringify(req.query));
    // return res.render('Err', {title: '系统维护中 预计 2018-01-14 02:00:00 恢复', tip: '对您造成的不便,我们感到十分的抱歉 '});
    if (req.query.checkCode && req.query.appKey && req.query.timestamp && req.query.channel) {
        if (req.query.channel == 'gswechat' && (req.query.appKey == '2AA60979E996470BAB00133A878ECFBB' || req.query.appKey == 'FAAC07AC633944BCA50AEB5C12D49243')) {
            if (!(req.cookies.guId)) {
                if ((new Date().getTime() - req.query.timestamp) / 1000 > 60) {
                    return res.render('Err', {title: '参数错误', tip: '时间戳超时'})
                } else {
                    let ecodeTimes = cipherL.cipher('rc4', req.query.checkCode, new Date().getTime().toString());
                    res.cookie('guId', ecodeTimes);
                }
            } else {
                if (!(req.cookies.guId && new Date().getTime() - cipherL.decipher('rc4', req.query.checkCode, req.cookies.guId) < 30 * 60 * 1000)) {
                    if ((new Date().getTime() - req.query.timestamp) / 1000 > 60) {
                        return res.render('Err', {title: '参数错误', tip: '时间戳超时'})
                    } else {
                        let ecodeTimes = cipherL.cipher('rc4', req.query.checkCode, new Date().getTime().toString());
                        res.cookie('guId', ecodeTimes);
                    }
                }
            }
            let stamp = req.query.timestamp;
            let M = '';
            for (let i = -2; i > -13; i--) {
                M = stamp.substr(i, 1);
                if (M != 0)
                    break;
            }
            let N = stamp.substr(-1, 1);
            let K = 0;
            let checkcode = '';
            while (M * K <= 12) {
                checkcode += (String(Number(stamp.substr(M * K, 1)) + Number(N)));
                K++;
            }
            if (checkcode === req.query.checkCode) {
                getNewOrderSn().then(function (orderSn) {
                    let cid = req.query.cid || '306';
                    let appKey = req.query.appKey;
                    let cityName;
                    if (!cityDataMap.has(cid)) {
                        return res.render('Err', {title: '没有该城市信息', tip: '建议城市编号是否正确'});
                    }
                    let loginParams = cityDataMap.get(cid).queryParam;
                    cityName = cityDataMap.get(cid).name;
                    let renderJSON = {
                        cityName: cityName,
                        loginHtml: '',
                        cid: cid,
                        orderSn: orderSn,
                        redirectUrl: `https://t.51gjj.com/shebao/shebaoSuccess?checkCode=${req.query.checkCode}&time=${req.query.timestamp}`,
                        forgot: '',
                    };
                    let cusList = getCusList(appKey)
                    renderJSON = Object.assign(renderJSON, cusList.theme || {});
                    if (cityDataMap.get(cid).state !== 1) {
                        renderJSON.loginHtml = backErrorPage('当前社保中心正在维护中', cityName + '社保中心正在维护中');
                        renderJSON.status = 'maintenance';
                        return res.render('sbQuery2', renderJSON);
                    }
                    let sendPage = getHelppage(cid, loginParams);
                    renderJSON.loginHtml = sendPage.html;
                    renderJSON.dark = sendPage.dark;
                    res.cookie('session',cipherL.cipher('rc4', req.query.checkCode, orderSn));
                    QueryStatus([['status', 'taskId'], 'orderId', orderSn]).then(orderStatus => {
                        if (orderStatus.length > 0) {
                            renderJSON.status = orderStatus[0].status;
                            renderJSON.taskId = orderStatus[0].taskId;
                        } else {
                            renderJSON.status = 'init';
                        }
                        res.render('sbQuery2', renderJSON);
                    }).catch(err => {
                        console.log(err);
                        renderJSON.status = 'init';
                        res.render('sbQuery2', renderJSON);
                    });
                }).catch(function (err) {
                    console.error('gswe getOrderSn error:' + err);
                    return res.render('Err', {title: '系统错误', tip: ''})
                })
            } else {
                return res.render('Err', {title: '参数错误', tip: '建议检查校验码是否正确'})
            }
        } else {
            return res.render('Err', {title: '参数错误', tip: '建议检查参数是否正确'});
        }
    } else {
    let check = checkParams.getIndex(req.query);
    if (check.code === -1) {
        console.error(JSON.stringify(req.query));
        console.error(JSON.stringify(check));
        return res.render('Err', { title: check.msg, tip: '建议检查参数是否完整' });
    }
    let cid = req.query.cid || '81';
    let orderSn = req.query.orderSn;
    let appKey = req.query.appKey;
    let token = req.query.token;
    let timestamp = req.query.timestamp;
    let sign = req.query.sign;
    let redirectUrl = req.query.redirectUrl;
    let enKey = orderSn + 'Liu';
    let refresh = req.query.refresh || 0;
    let form_data = {
        sign: sign,
        type: 'shebao',
        param: {
            orderSn: orderSn,
            timestamp: timestamp,
            appKey: appKey,
            token: token,
        }
    };
    signValidityCheck(form_data).then(data => {
        if (data.code != 0) {
            if (!(req.cookies.guId && new Date().getTime() - cipherL.decipher('rc4', enKey, req.cookies.guId) < 30 * 60 * 1000)) {
                console.error('【JAVA signValidityCheck】signParams: ' + JSON.stringify(form_data) + ' signRes: ' + JSON.stringify(data));
                return res.render('Err', { title: data.msg, tip: '建议检查参数是否正确' });
            }
        } else {
            let ecodeTimes = cipherL.cipher('rc4', enKey, new Date().getTime().toString());
            res.cookie('guId', ecodeTimes);
        }

        analysisReq(req).then(data => {
            console.log('analysisReq', data)
        }).catch(err => {
            console.error('analysisReq', err)
        })

        let cityName;
        if (!cityDataMap.has(cid)) {
            return res.render('Err', { title: '没有该城市信息', tip: '建议城市编号是否正确' });
        }
        let loginParams = cityDataMap.get(cid).queryParam;
        cityName = cityDataMap.get(cid).name;
        let renderJSON = {
            cityName: cityName,
            loginHtml: '',
            cid: cid,
            orderSn: orderSn,
            redirectUrl: redirectUrl,
            forgot: '',
        };
        let cusList = getCusList(appKey)
        renderJSON = Object.assign(renderJSON, cusList.theme || {});
        if (cityDataMap.get(cid).state !== 1) {
            renderJSON.loginHtml = backErrorPage('当前社保中心正在维护中', cityName + '社保中心正在维护中');
            renderJSON.status = 'maintenance';
            return res.render('sbQuery2', renderJSON);
        }
        let sendPage = getHelppage(cid, loginParams);
        renderJSON.loginHtml = sendPage.html;
        renderJSON.dark = sendPage.dark;
        QueryStatus([['status', 'taskId'], 'orderId', orderSn]).then(orderStatus => {
            if (orderStatus.length > 0) {
                renderJSON.status = orderStatus[0].status;
                renderJSON.taskId = orderStatus[0].taskId;
            } else {
                renderJSON.status = 'init';
            }
                if (renderJSON.status === 'success' && refresh === '1') {
                    if (appKey !== "3D6884E1400246CA9B8A4AF836DFB856" && appKey !== "153DDF6D501146BE967766294DF84F10") {
                renderJSON.status = 'refresh';
                    } else {
                        renderJSON.status = 'success';
                    }
            }
            if (appKey === 'DAFC3E82254740E2B629C4E7F45A5F09' || appKey === '12BD888F0AA647D496202B4126B3ED74') {
                res.render('index', renderJSON);
            } else {
                res.render('sbQuery2', renderJSON);
            }
        }).catch(err => {
            console.log(err);
            renderJSON.status = 'init';
            res.render('sbQuery2', renderJSON);
        });
    }).catch(err => {
        console.log('[GJJ]failed' + err);
        res.render('Err', { title: '服务器出错', tip: '请稍后重试' });
    });
}

});
router.get('/cityList', (req, res, next) => {
    res.send(cityListHtml);
});

router.get('/cityConfig', (req, res, next) => {
    // console.log('getConfig',req.body)
    // signValidityCheck(req.body).then(ret=>{
    //     if(ret.code==="0"){
            res.send(cityJSON)
    //     }else{
    //         res.send(ret)
    //     }
    // }).catch(err=>{
    //     res.send({code:-1,msg:"服务出错"})
    // })
});

router.post('/centersInfo', (req, res, next) => {
    console.log('centersInfo',req.body)
    signValidityCheck(req.body).then(ret=>{
        if(ret.code==0){
            let options = {
                url: 'http://tm.51gjj.com:1010/ShebaoExportFile/GetCentersJson',
                gzip: true,
                json:true
            };
            request(options, (e, r, b) => {
                if (e) {
                    console.error('getcentersInfo');
                    console.error(e);
                    res.send(e);
                } else { 
                    if(b){
                        res.send({code:0,data:b})
                    }else{
                        res.send({code:-1,msg:"服务器出错"})
                    }
                   
                }
            });
        }else{
            res.send(ret)
        }
    }).catch(err=>{
        res.send({code:-1,msg:"服务出错"})
    })
});





router.get('/getCity', (req, res, next) => {
    console.log('【Router getCity】' + JSON.stringify(req.query));
    let cid = req.query.cid;
    let cityName = cityDataMap.get(cid).name;
    if (!cityDataMap.has(cid)) {
        let data = {
            code: -1,
            cid: cid,
            html: backErrorPage('请求城市不存在', cityName + '社保中心正在维护中'),
            cityName: cityName + '社保中心'
        };
        return res.send(data);
    }
    if (cityDataMap.get(cid).state !== 1) {
        let data = {
            code: -1,
            cid: cid,
            html: backErrorPage('当前社保中心正在维护中', cityName + '社保中心正在维护中'),
            cityName: cityName + '社保中心'
        };
        return res.send(data);
    }
    let loginParams = cityDataMap.get(cid).queryParam || cityDataMap.get(3).queryParam;
    let data = {
        code: 0,
        cid: cid,
        html: getHelppage(cid, loginParams).html,
        dark: getHelppage(cid, loginParams).dark,
        cityName: cityName + '社保中心'
    };
    res.send(data);
});
router.post('/ajax/createTask', function (req, res, next) {
    console.log('【Router createTask】' + JSON.stringify(req.body));
    let check = checkParams.createJob(req.body);
    if (check.code === -1) {
        console.error(JSON.stringify(req.body));
        console.error(JSON.stringify(check));
        return res.send(check);
    }
    newJob(req.body.cid).then(b => {
        let obj = {
            orderId: req.body.orderSn,
            taskId: String(b.data.taskId),
            status: 'init',
            appkey: req.body.appKey,
            callbackUrl: callbackMap.get(req.body.appKey) && callbackMap.get(req.body.appKey).callbackUrl || '',
            userId: req.body.userId ? req.body.userId : '',
            cityId: b.data.cityId,
        };
        InsOrUpdSta(obj).then(chanSta => {
            res.send(b);
        }).catch(err => {
            console.error("InsOrUpdSta" + JSON.stringify(err));
            res.send({ code: -1, msg: '任务创建失败' });

        });
    }).catch(err => {
        res.send(err);
    });
});
router.post('/ajax/commitParams', function (req, res, next) {
    console.log('【Router commitParams】' + JSON.stringify(req.body));
    let params;
    try {
        params = JSON.parse(req.body.params);
    } catch (err) {
        return res.send('err');
    }
    commitJob(params, req.body.orderSn, req.body.taskId, req.body.appKey).then(b => {
        res.send(b)
    }).catch(err => {
        res.send(err);
    });

});
router.post('/ajax/getCode', function (req, res, next) {
    console.log('【Router getCode】' + JSON.stringify(req.body));

    getCode(req.body.taskId, req.body.type).then(b => {
        res.send(b);
    }).catch(err => {
        res.send(err);
    });

});
router.post('/getOrderSn', function (req, res) {
    let form_data = req.body;
    let options = {
        url: getOrderSnUrl,
        method: 'POST',
        json: true,
        body: form_data,
        headers: {
            'content-type': 'application/json'
        }
    };
    console.log('[getOrderSN] body', form_data);
    request(options, (e, r, b) => {
        if (e) {
            console.error('[getOrderSN] e', e);
            res.send(e);
        } else {
            console.log('[getOrderSN] res', b);
            res.send(b);
        }
    });
});
router.post('/getToken', function (req, res) {
    let form_data = req.body;
    let options = {
        url: getTokenUrl,
        method: 'POST',
        json: true,
        body: form_data,
        headers: {
            'content-type': 'application/json'
        }
    };
    console.log('[getToken] body', form_data);
    request(options, (e, r, b) => {
        if (e) {
            console.log('[getToken] e', e);
            res.send(e);
        } else {
            console.log('[getToken] b', b);
            res.send(b);
        }
    });
});
router.post('/getData', function (req, res) {
    console.log('【Router getData】' + JSON.stringify(req.body));
    let check = checkParams.getData(req.body);
    if (check.code === -1) {
        console.error(JSON.stringify(req.body));
        console.error(JSON.stringify(check));
        return res.send(check);
    }
    signValidityCheck(req.body).then(sign => {
        if (sign.code === 0) {
            let url = getDataUrl + req.body.params.orderSn;
            let options = {
                url: url,
                gzip: true
            };
            if (req.body.params.appKey === "3D6884E1400246CA9B8A4AF836DFB856" || req.body.params.appKey === "153DDF6D501146BE967766294DF84F10") {
                let queryP = [["orderSn"], req.body.params.orderSn]
                queryCusStatus(queryP).then(rows => {
                    if (rows.length > 0) {
                        console.error("南京消金数据Err", req.body.params.orderSn, rows);
                        return res.send({code: -1, msg: '无此订单号'});
                    } else {
                        console.log("南京消金数据正常", req.body.params.orderSn, rows);
                        request(options, (e, r, b) => {
                            if (e) {
                                console.error('getDataMongo');
                                console.error(e);
                                res.send(e);
                            } else {
                                try {
                                    b = JSON.parse(b);
                                    if (b.code === 0) {
                                        let obj = {
                                            orderSn: req.body.params.orderSn,
                                            appKey: req.body.params.appKey,
                                            type: 'sbH5'
                                        };
                                        InsertCusStatus(obj).then(data => {
                                            console.log(data);
                                        }).catch(err => {
                                            console.log(err);
                                        });
                                        res.send(b);
                                    } else {
                                        res.send(b);
                                    }
                                } catch (err) {
                                    console.error(err);
                                    return res.send(b);
                                }
                            }
                        });
                    }
                }).catch(err => {
                    console.error("南京消金数据", err);
                    return res.send({code: -1, msg: '服务器出错'});
                })
            } else {
                request(options, (e, r, b) => {
                    if (e) {
                        console.error('getDataMongo');
                        console.error(e);
                        res.send(e);
                    } else {
                        try {
                            b = JSON.parse(b);
                            if (b.code === 0) {
                                let obj = {
                                    orderSn: req.body.params.orderSn,
                                    appKey: req.body.params.appKey,
                                    type: 'sbH5'
                                };
                                InsertCusStatus(obj).then(data => {
                                    console.log(data);
                                }).catch(err => {
                                    console.log(err);
                                });
                                res.send(b);
                            } else {
                                res.send(b);
                            }
                        } catch (err) {
                            console.error(err);
                            return res.send(b);
                        }
                    }
                });
            }
        } else {
            console.error('getData');
            console.error(req.body);
            console.error(sign);
            res.send(sign);
        }
    }).catch(err => {
        console.error('getData sign');
        console.error(err);
        console.error(req.body);
        res.send(err);
    });
});

router.post('/ajax/createTask', function (req, res, next) {
    console.log('【Router createTask】' + JSON.stringify(req.body));
    let check = checkParams.createJob(req.body);
    if (check.code === -1) {
        console.error(JSON.stringify(req.body));
        console.error(JSON.stringify(check));
        return res.send(check);
    }
    newJob(req.body.cid).then(b => {
        let obj = {
            orderId: req.body.orderSn,
            taskId: String(b.data.taskId),
            status: 'init',
            appkey: req.body.appKey,
            callbackUrl: callbackMap.get(req.body.appKey) && callbackMap.get(req.body.appKey).callbackUrl || '',
            userId: req.body.userId ? req.body.appKey + req.body.userId : '',
            cityId: b.data.cityId,
        };
        InsOrUpdSta(obj).then(chanSta => {
            res.send(b);
        }).catch(err => {
            console.error(err);
            res.send({ code: -1, msg: '任务创建失败' });
        });
    }).catch(err => {
        res.send(err);
    });
});

router.post('/ajax/refresh', function (req, res, next) {
    console.log('【Router refresh】' + JSON.stringify(req.body));
    let orderSn = req.body.orderSn;
    if (req.body.hasCode === 'true') {
        let taskId = req.body.taskId;
        getLoginParams(orderSn).then(params => {
            params.params.code = req.body.code;
            commitJob(params.params, orderSn, taskId, 1).then(resData => {
                res.send(resData);
            }).catch(err => {
                res.send(err);
            });
        }).catch(err => {
            res.send(err);
        });
    } else {
        getLoginParams(orderSn).then(params => {
            newJob(params.cid).then(taskId => {
                commitJob(params.params, orderSn, taskId.data.taskId).then(resData => {
                    let ipObj = {
                        taskId: String(taskId.data.taskId),
                        status: 'init',
                        orderId: orderSn
                    };
                    InsOrUpdSta(ipObj).then(data => {
                        console.log("更新任务成功")
                        res.send(resData);
                    }).catch(err => {
                        console.error(err);
                        res.send({ code: -1, msg: '刷新任务创建失败' });
                    });
                }).catch(err => {
                    res.send(err);
                });
            }).catch(err => {
                res.send(err);
            });
        }).catch(err => {
            res.send(err);
        });
    }
    // res.send(resData)
});
router.post('/ajax/redirect', function (req, res, next) {
    console.log('【Router redirect】' + JSON.stringify(req.body));
    res.send('ok');
});

router.post('/ajax/sbregister', function (req, res, next) {
    console.log('【Router sbregister】' + JSON.stringify(req.body));
    let url = `https://t.51gjj.com/sbregister/query?appKey=${req.body.appKey}&type=shebaoH5`;
    request(url, (e, r, b) => {
        if (e) {
            console.error("login sbregister err", e);
            res.send({code: -1, msg: '系统出错'});
        } else {
            console.log(b);
            b = JSON.parse(b)
            if (b.code == 0) {
                if (req.body.userId != '') {
                    res.send({code:0,href:`https://t.51gjj.com/sbregister?appKey=${req.body.appKey}&type=shebaoH5&cid=${req.body.cid}&orderSn=${b.orderSn}&userId=${req.body.userId}&selectCity=1`});
                } else {
                    res.send({code:0,href:`https://t.51gjj.com/sbregister?appKey=${req.body.appKey}&type=shebaoH5&cid=${req.body.cid}&orderSn=${b.orderSn}&selectCity=1`});
                }
            } else {
                res.send({code: -1, msg: '访问失败,请稍后重试'});
            }
        }
    })
});

router.get('/registersuccess',function (req, res) {
    console.log("registersuccess" , JSON.stringify(req.query))
    res.render('registersuccess',{});
})

router.post('/test', function (req, res, next) {
    res.send('ok');
});

router.get('/shebaoSuccess', function (req, res) {
    console.log("shebaoSuccess", JSON.stringify(req.query));
    if (req.cookies.session && req.query.timestamp && req.query.time && req.query.checkCode) {
        let stamp = req.query.time;
        let M = '';
        for (let i = -2; i > -13; i--) {
            M = stamp.substr(i, 1);
            if (M != 0)
                break;
        }
        let N = stamp.substr(-1, 1);
        let K = 0;
        let checkcode = '';
        while (M * K <= 12) {
            checkcode += (String(Number(stamp.substr(M * K, 1)) + Number(N)));
            K++;
        }
        let orderSn = cipherL.decipher('rc4', req.query.checkCode, req.cookies.session);
        if (checkcode === req.query.checkCode) {
            let url = 'http://tv.51gjj.com:11250/shebao/' + orderSn;
            let options = {
                url: url,
                gzip: true
            };
            request(options, (e, r, b) => {
                if (e) {
                    console.error("shebaoSuccess req Err", url, JSON.stringify(e));
                    return res.render('Err', {title: '系统错误', tip: ''})
                } else {
                    try {
                        b = JSON.parse(b);
                        if (b.code === 0) {
                            let html  = dealhtml(b);
                            return res.render('showData', html);
                        } else {
                            return res.render('Err', {title: b.msg, tip: ''})
                        }
                    }catch (err){
                        return res.render('Err', {title: '系统错误', tip: ''})
                    }
                }
            })
        } else {
            return res.render('Err', {title: '参数错误', tip: '校验码错误'})
        }
    } else {
        return res.render('Err', {title: '参数错误', tip: '请检查参数是否正确'})
    }
})



router.get('/nago', (req, res, next) => {
    res.render('nago');
});

function getLoginParams(orderSn) {
    return new Promise((resolve, reject) => {
        let url = getParamsUrl + orderSn;
        request(url, (e, r, b) => {
            if (e) {
                console.error('【HX getLoginParams】 Err获取登录参数服务出错' + JSON.stringify(e));
                reject({ code: -2, msg: '获取登录参数服务出错' });
            } else {
                try {
                    b = JSON.parse(b);
                } catch (err) {
                    console.error('【HX getLoginParams】JSON.parse Err获取登录参数解析出错' + JSON.stringify(e));
                    return reject({ code: -2, msg: '获取登录参数解析出错' });
                }
                if (b.Code === 0) {
                    resolve({ params: b.LoginParam.step1, cid: b.Cid });
                } else {
                    console.error('【HX getLoginParams】 JSON.parse Err未找到登录信息数' + JSON.stringify(b));
                    console.error(url);
                    reject({ code: -2, msg: '未找到登录信息数' });
                }
            }
        });
    });
}
function newJob(cid) {
    return new Promise((resolve, reject) => {
        let form_data = { cityId: cid };
        let options = {
            url: createTaskUrl,
            method: 'POST',
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        };
        request(options, (e, r, b) => {
            if (e) {
                console.error('【JAVA newJob】[ err创建社保任务服务器出错]req:' + JSON.stringify(form_data) + ' Res: ' + JSON.stringify(e));
                reject({ code: -3, msg: '创建社保任务服务器出错' });
            } else {
                if (b.code === 0) {
                    console.log('【JAVA newJob】创建任务成功req:' + JSON.stringify(form_data) + ' Res: ' + JSON.stringify(b));
                    resolve(b);
                } else {
                    console.error('【JAVA newJob】创建任务失败req:' + JSON.stringify(form_data) + ' Res: ' + JSON.stringify(b));
                    reject({ code: -3, msg: '创建社保任务失败' });
                }
            }
        });
    });
}
function commitJob(params, orderSn, taskId, appKey) {
    return new Promise((resolve, reject) => {
        let submitParamsUrl = myCallbackUrl + '?orderSn=' + orderSn + '&appKey=' + appKey;
        let commitParams = {
            data: params,
            taskId: taskId,
            callbackUrl: submitParamsUrl
        };
        let options = {
            url: commitJobUrl,
            method: 'POST',
            json: true,
            body: commitParams,
            headers: {
                'content-type': 'application/json'
            }
        };
        console.log(commitJobUrl)
        request(options, (e, r, b) => {
            if (e) {
                console.error('【JAVA commitJob】提交任务服务出错Req：+' + JSON.stringify(commitParams) + ' Res: ' + JSON.stringify(e));
                reject({ code: -6, msg: '提交任务服务出错' });
            } else {
                if (b.code === 0) {
                    console.log('【JAVA commitJob】提交任务成功Req：+' + JSON.stringify(commitParams) + ' Res: ' + JSON.stringify(b));
                    resolve(b);
                } else {
                    console.error('【JAVA commitJob】提交任务出错Req：+' + JSON.stringify(commitParams) + ' Res: ' + JSON.stringify(b));
                    reject({ code: -6, msg: '提交任务出错' });
                }
            }
        });
    });
}
function getCode(taskId, type) {
    return new Promise((resolve, reject) => {
        let form_data = {
            taskId: taskId,
            type: type === "phone_code" ? "shebaoV2_phone_code" : "shebaoV2_yzm"
        };
        let options = {
            url: getCodeUrl,
            method: 'POST',
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        };
        request(options, (e, r, b) => {
            if (e) {
                console.error('【JAVA getImgCode】获取验证码服务出错' + JSON.stringify(form_data) + 'Res:' + JSON.stringify(e));
                reject({ code: -5, msg: '获取验证码服务出错' });
            } else {
                if (b.code === 0) {
                    resolve(b);
                } else {
                    console.error('【JAVA getImgCode】获取验证码出错Req:' + JSON.stringify(form_data) + 'Res:' + JSON.stringify(b));
                    reject(b);
                }
            }
        });
    });
}


function InsOrUpdSta(obj) {
    return new Promise((resolve, reject) => {
        QueryStatus([['taskId', 'status'], 'orderId', obj.orderId]).then(status => {
            if (status.length > 0) {
                let ipObj = {
                    taskId: obj.taskId,
                    status: obj.status,
                    cityId: obj.cityId
                };
                if (status[0].status !== "init") {
                    ipObj.text2 = status[0].taskId
                }
                UpdateStatus([ipObj, 'orderId', obj.orderId]).then(data => {
                    console.log('【DB UpdateStatus】 params' + JSON.stringify([ipObj, 'orderId', obj.orderId]) + "Res" + JSON.stringify(data))
                    resolve(data);
                }).catch(err => {
                    console.error('【DB UpdateStatus Err】 params' + JSON.stringify([ipObj, 'orderId', obj.orderId]) + "Res" + JSON.stringify(err))
                    reject(err);
                });
            } else {
                InsertStatus(obj).then(status => {
                    console.log('【DB InsertStatus】 params' + JSON.stringify(obj) + "Res" + JSON.stringify(status))
                    resolve(status);
                }).catch(err => {
                    console.error('【DB InsertStatus】 params' + JSON.stringify(obj) + "Res" + JSON.stringify(err))
                    reject(err);
                });
            }
        }).catch(err => {
            console.error('【DB QueryStatus】 params' + JSON.stringify([['taskId', 'status'], 'orderId', obj.orderId]) + "Res" + JSON.stringify(err))
            reject(err);
        });
    });
}



function backErrorPage(errMsg, errTip) {
    return `<div class="pannel">
        <div class="wrapper ">
            <div class="failed">
                <div class="icon"></div>
                <span class="title">${errMsg}</span>
               
                
            </div>

        </div>
    </div>`;
}


function creatCityListHtml(cityList) {
    let backHtml = '<div id="switcher-tpl"><section class="search-bar"><div><input placeholder="社保中心的中文/拼音/简拼"/></div></section><section class="gjj-list-pannel"><h4>按行政区域查找</h4>';
    cityList.data.map(prov => {
        prov.citys = prov.citys == null ? [] : prov.citys;
        if (prov.citys.length > 0) {
            backHtml += `<ul><li> <h5>${prov.provinceName}</h5><ul>`;
            prov.citys.map(city => {
                if (city.state != '1' && city.state != '-1') {
                    return;
                }
                cityDataMap.set(String(city.id), city);
                backHtml += `<li data-id="${city.id}">${city.name}社保中心</li>`;
            });
            backHtml += '</ul></li></ul>';
        }
    });
    backHtml += '</section><section class="gjj-filter-list-pannel"><ul></ul><span></span></section></div>';
    cityListHtml = backHtml;
}

function createLoginHTML(loginParams, helpPage) {
    let backHtml = '';
    let contentHtml = '';
    backHtml += '<div class="tab-control"><div class="tab-nav">';
    contentHtml += '<div id="tab-content">';
    for (let i = 0; i < loginParams.length; i++) {
        backHtml += `<label class="${i == 0 ? 'active' : ''} d-${loginParams.length}"  data-ref="account" data-tag="">${getParam(loginParams[i].loginParam[0].name)}</label>`;
        contentHtml += `<ul style="display: ${i == 0 ? 'block' : 'none'};" class="${i == 0 ? 'active' : ''}">`;
        for (let j = 0; j < loginParams[i].loginParam.length; j++) {
            let param = loginParams[i].loginParam[j];
            if (param.type !== 'radio') {
                switch (param.name) {
                    case 'code':
                        contentHtml += `
                                  <div class="input-wrapper">
                                            <label>${getParam(param.name)}</label>
                                            <div class="content">
                                                <div class="code">
                                                    <div class="captcha-wrapper loading"><img src=""></div>
                                                </div>
                                                <div class="input"><input name=${param.name} placeholder="${param.note}" class="input-option required" data-label="验证码"></div>
                                            </div>
                                        </div>`;
                        break;
                    case 'password':
                        contentHtml += `
                                  <div class="input-wrapper">
                                        <label>${getParam(param.name)}</label>
                                        <div class="content">
                                            <div class="input">
                                                <input name=${param.name} type="password" placeholder="${param.note}" class="input-option required" data-label="${param.name}">
                                            </div>
                                        </div>
                                    </div>`;
                        break;
                    default:
                        contentHtml += `
                                  <div class="input-wrapper">
                                        <label>${getParam(param.name)}</label>
                                        <div class="content">
                                            <div class="input">
                                                <input name=${param.name} type="text" placeholder="${param.note}" class="input-option required" data-label="${param.name}">
                                            </div>
                                        </div>
                                    </div>`;
                }
            } else {
                let note = JSON.parse(param.note);
                let menuHtml = '';
                for (let menu in JSON.parse(param.note)) {
                    menuHtml += `<option value="${menu}" ${menu == 0 ? 'selected' : ''} >${note[menu]}</option>`;
                }
                contentHtml += `
                                  <div class="input-wrapper">
                                            <div class="content" >
                                               
                                                <div class="select" >
                                                <select name=${param.name}>${menuHtml}</select>
    
                                                </div>
                                            </div>
                                        </div>`;
            }


        }
        contentHtml += '</ul>';
    }
    backHtml += '<span class="cursor"></span></div></div>';
    contentHtml += '</div>';
    if (loginParams.length > 1) {
        return helpPage.title + backHtml + contentHtml;
    } else {
        return helpPage.title + contentHtml;
    }
}

module.exports = router;
