const request = require('request');
const DBQUERY = require('./db.js').DBQUERY;

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


var helpPageMap = new Map();
let sbregisterCityMap = new Map();
let cusCityMap=new Map();
let sbforgetPwdMap = new Map();
let paramMap = {
    ID: '身份证号',
    password: '密码',
    name: '姓名',
    socialNumber: '社保编号',
    userName: '用户名',
    personalEmail: '市民邮箱',
    account: '身份证/别名',
    passport:'护照',
    phone:'手机号',
    pcNumber:'个人电脑编号',
    medicalNumber:'医保卡号',
    staffNumber:'职工编号',
    socialCard:'社保卡号',
    code:'验证码',
    companyID:'单位登记证编号',
    personalID:'个人编号',
    loginNum:'登录号',
    nickName:'昵称',
    socialQueryPassword:'查询密码',
    email:'邮箱'
};

let defaultColor={
    'IconC':'#439df8',
    'noticeC':'#dcebfe',
    'linkC':'#439df8',
    'btnC':'#439df8',
    'btnAC':'#4883c0',
    'btnDC':'#cbcbcb',
    'btnDCC':'#868686',
    'circleC':'0x439df8'
}

function getParam(params) {
    if (paramMap.hasOwnProperty(params)) {
        return paramMap[params];
    } else {
        return params;
    }
}

getHelpPageData();
getCusCityList();
getsbreigsterCityInfo();
setInterval(function () {
    getHelpPageData();
    getCusCityList();
    getsbreigsterCityInfo();
}, 1000 * 60 * 5);

function getsbreigsterCityInfo() {
    getsbreigsterCityList().then(data => {
        if (data.code == 0) {
            data.data.map(prov => {
                prov.citys = prov.citys == null ? [] : prov.citys;
                prov.citys.map(city => {
                    if (city.state != '1' && city.state != '-1') {
                        return;
                    }
                    sbregisterCityMap.set(String(city.id), city);
                })
            })
        } else {
            console.log('getCitySettingFailure' + JSON.stringify(data));
        }
    }).catch(err => {
        console.log(err);
        console.log('[sbregister]获取城市配置出错');
    });

    getsbforgetPwdCityList().then(data => {
        if (data.code == 0) {
            data.data.map(prov => {
                prov.citys = prov.citys == null ? [] : prov.citys;
                prov.citys.map(city => {
                    if (city.state != '1' && city.state != '-1') {
                        return;
                    }
                    sbforgetPwdMap.set(String(city.id), city);
                })
            })
        } else {
            console.log('getCitySettingFailure' + JSON.stringify(data));
        }
    }).catch(err => {
        console.log(err);
        console.log('[sbforget]获取城市配置出错');
    });


}
function getsbreigsterCityList() {
    return new Promise((resolve, reject) => {
        let form_data = {
            type: 'shebao'
        };
        let options = {
            url: 'http://ts1.51gjj.com:4853/register/queryRegisterCitySettings',
            method: 'POST',
            json: true,
            body: form_data,
            headers: {
                'content-type': 'application/json'
            }
        };
        request(options, (e, r, b) => {
            if (e) {
                reject(e);
            } else {
                resolve(b);
            }
        })
    })
}

function getsbforgetPwdCityList() {
    return new Promise((resolve, reject) => {
        let options = {
            url: 'http://ts1.51gjj.com:18523/shebaofindpwd/getSettings',
            method: 'GET',
            json: true
        };
        request(options, (e, r, b) => {
            if (e) {
                reject(e);
            } else {
                resolve(b);
            }
        })
    })
}

function getHelpPageData() {
    let sql = 'SELECT ??,?? FROM `sb_help`';
    DBQUERY(sql, ['cid', 'help'], (err, rows) => {
        if (err) {
            console.error(err);
            return;
        }
        try {
            rows.map(row => {
                helpPageMap.set(row.cid, row);
            });
        } catch (e) {
            console.error(e);
        }

    });
}

function getCusCityList() {
    let sql='SELECT ?? FROM `customer_config` WHERE service="SB" AND type="H5"'
    DBQUERY(sql, [['appKey', 'gjjH5City','gjjH5All','gjjH5Theme','gjjH5ThemeDefault','gjjAuto']], (err, rows) => {
        if (err) {
            console.error(err);
            return;
        }
        try {
            rows.map(row => {
                console.log(row)
                try{
                    if(row.gjjH5ThemeDefault===1){
                        cusCityMap.set(row.appKey, {cityList:JSON.parse(row.gjjH5City),cityHtml:'',all:row.gjjH5All,theme:defaultColor,themeDefault:row.gjjH5ThemeDefault,autoPwd:row.gjjAuto});
                    }else{
                        cusCityMap.set(row.appKey, {cityList:JSON.parse(row.gjjH5City),cityHtml:'',all:row.gjjH5All,theme:JSON.parse(row.gjjH5Theme),themeDefault:row.gjjH5ThemeDefault,autoPwd:row.gjjAuto});
                    }
                }catch (err){
                    console.log(err)
                    cusCityMap.set(row.appKey, {cityList:[],cityHtml:'',all:1,theme:defaultColor,themeDefault:1});
                }
            });
        } catch (e) {
            console.error(e);
        }
    });
}

function getCusList(appKey) {
    if(cusCityMap.has(appKey)){
        return cusCityMap.get(appKey)
    }else{
        return {all:1,theme:defaultColor,autoPwd:0}
    }
}

function getHelpPage(cid) {
    if (!helpPageMap.has(Number(cid))) {
        return {title: ''};
    } else {
        let title = '<section class="header-notice">不知道怎么查?</section>';
        let content ='';
        let help = JSON.parse(helpPageMap.get(Number(cid)).help);
        if(help.length===0){
            return {title: ''};
        }
        for(let i=0;i<help.length;i++){
            let page=help[i];
            content+=`<p><label class="sequence">${i+1}</label>${page.desc}`;
            if('link' in page){
             if (sbregisterCityMap.has(String(cid)) && sbregisterCityMap.get(String(cid)).state === 1 && (/注册/).test(page.link.label)){
                    content+=`<a href="javascript:sbregister()">${page.link.label}</a>`;
                }else if (sbforgetPwdMap.has(String(cid)) && sbforgetPwdMap.get(String(cid)).state === 1 && (/找回|忘记密码/).test(page.link.label)) {
                       content += `<a onclick="sbforgetPwd()">${page.link.label}</a>`;
                   } else {
                       content += `<a href="${page.link.url}">${page.link.label}</a>`;
                   }
            }
            content+='</p>';
        }
        return {title: title, content: content};
    }


}




function InsertStatus(params) {
    return new Promise((resolve, reject) => {
        let sql = 'INSERT INTO `sbh5_status` SET ?';
        params.updateDate=new Date().toLocaleString()
        DBQUERY(sql, params, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                if (rows.affectedRows === 1) {
                    resolve({Code: 0, Msg: 'insert success'});
                } else {
                    resolve({Code: -1, Msg: 'insert failed'});
                }
            }
        });
    });
}

function UpdateStatus(params) {
    return new Promise(function (resolve, reject) {
        let sql = 'UPDATE `sbh5_status` SET ? where ??=?';
        params[0].updateDate=new Date().toLocaleString()
        DBQUERY(sql, params, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                if (rows.changedRows === 1) {
                    resolve({Code: 0, msg: 'updateSucc'});
                } else {
                    reject(rows);
                }

            }
        });
    });
}

function QueryStatus(params) {
    return new Promise((resolve, reject) => {
        let sql = 'select ?? from `sbh5_status` where ?? =?';
        DBQUERY(sql, params, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
        });

    });
}

function InsertCusStatus(params) {
    return new Promise((resolve, reject) => {
        let sql = 'INSERT INTO `cus_data`  SET ? ';
        DBQUERY(sql, params, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                if (rows.affectedRows === 1) {
                    resolve({Code: 0, Msg: 'insert cus_data success'});
                } else {
                    resolve({Code: -1, Msg: 'insert cus_data failed'});
                }
            }
        });
    });
}

function queryCusStatus(params) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT ?? FROM `cus_data` WHERE appkey="153DDF6D501146BE967766294DF84F10"  And orderSn=?';
        DBQUERY(sql, params, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
        });
    });
}

module.exports.getParam = getParam;
module.exports.getHelpPage = getHelpPage;
module.exports.InsertStatus = InsertStatus;
module.exports.InsertCusStatus = InsertCusStatus;
module.exports.QueryStatus = QueryStatus;
module.exports.UpdateStatus = UpdateStatus;
module.exports.getCusList = getCusList;
module.exports.queryCusStatus = queryCusStatus;