| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535 | /** * Created by MyPC on 2019/11/5. */var models=require('../models');var moment = require('moment');const hash=require('../class/hash');//http://qa.smartcost.com.cn:2060/cld//"https://yhuat.smartcost.com.cn/cld";//var curingUrl ="https://yhuat.smartcost.com.cn/cld"; //'https://yhyun.smartcost.com.cn/cld';var curingUrl ="http://qa.smartcost.com.cn:2060/cld";var buildUrl = 'https://yun.smartcost.com.cn/cld';var cloudService={    	/**	 * 获得养护列表	 * compilation_id 编办ID	 */    getCuringList: async function(compilation_id,page=1){           	//获得远程养护用户    	//分页数据    	var limit=12;        var offset=0;        if(page!=1){            var pg=page-1;            offset=pg*limit;        }        if(!hash.isExistence(compilation_id)){        	compilation_id='';        }    	var url= curingUrl+'/getUserList?page='+page+'&pageSize='+limit+'&latestUsed='+compilation_id;    	/*	接口请求获得的信息    	 *  userInfo	    	 *  pageData    	 *  compilationlist    	 */        var curingCloudData=await curlRequest(url);        var curingCloudList=curingCloudData.userInfo;            	//组合数据以获得本地扩展数据        var mobile=[];        curingCloudList.forEach(function(v,i){        	mobile.push(v.mobile);        });        if(!hash.isExistence(mobile)){        	return {curingList:[],pageData:[]};        }               //获得指定数据        var curingList = await models.cloud_curing.getCuringInMobile(mobile,compilation_id);               //组合同步云版数据        var falg=false;        curingCloudList.forEach(async function(cclValue,cclKey){        	curingCloudList[cclKey].client_id=0        	        	falg=true;        	for(var i=0;i<=curingList.length;i++){        		if(cclValue.mobile==curingList[i].mobile){            		curingCloudList[cclKey].client_id=curingList[i].client_id;            		falg=false;            		break;            	}        	}        	        	if(falg){//新增本地扩展信息        		sid=hash.hashDecode(STAFF.sid);        		var obj = {                        mobile: cclValue.mobile,                        sso_id: cclValue.ssoId,                        //compilation_id: cclValue.filter.compilationID,                       // curingCompany: cclValue.company,                        sid: sid,                        cid: STAFF.cid,                        status: 2,                        //addtime: new Date().getTime(),                        //updateTotal: cclValue.isUserActive                    };                var detail = await models.cloud_curing.create(obj);        	}        	        });    	        //获得编办数据        var compilationList=await this.getCompilationList(); //编办信息                                //数据组合--cld客户数据        var cid=[];        curingCloudList.forEach(function(v,i){        	if(v.client_id!=0){        		cid.push(v.client_id);        	}        });        var clientList =[];        if(hash.isExistence(cid)){        	 var attributes= ['cid', 'clientname', 'companyid', 'companyname'];             clientList = await models.CLD_client.findAllInCid(cid,attributes);        }                //组合页面需要展示的数据        curingCloudList.forEach(function(v,i){        	curingCloudList[i].clientInfo={};            clientList.forEach(function(clientVal,clientI){                if(v.client_id==clientVal.cid){                	curingCloudList[i].clientInfo=clientVal;                }            });            curingCloudList[i].addtime=moment(v.create_time).format('YYYY-MM-DD HH:mm');            curingCloudList[i].latest_login=moment(v.latest_login).format('YYYY-MM-DD HH:mm');            curingCloudList[i].client_id=hash.hashEncode(v.client_id.toString());            //curingCloudList[i].sso_id=v.sso_id;            //最后使用            curingCloudList[i].latest_usedName='';            for(var i=1;i<=compilationList.lenght;i++){            	if(compilationList[i]._id==v.latest_used){            		curingCloudList[i].latest_usedName=compilationList[i].name;            		break;            	}            }                        //登录时长            if(!hash.isExistence(v.online_times)){            	curingCloudList[i].online_times='';            }        });                var parameter='?compilation_id='+compilation_id;        //分页计算        var pageData = await getPage('','',page,limit,parameter,curingCloudData.pageData.total);        //console.log(curingCloudList);                                return {curingList:curingCloudList,pageData:pageData};                                            	    	//获得本地用户    	/*var limit=12;        var offset=0;        if(page!=1){            var pg=page-1;            offset=pg*limit;        }        var option={offset: offset,            limit: limit,            raw:true,            order:[['id','desc']]};        if(hash.isExistence(compilation_id)){            option.where={compilation_id: compilation_id};        }        var curingList = await models.cloud_curing.findAll(option);        var parameter='?compilation_id='+compilation_id;        //分页计算        var pageData = await getPage(models.cloud_curing,option.where,page,limit,parameter);                        //数据组合--cld客户数据        var cid=[];        curingList.forEach(function(v,i){            cid.push(v.client_id);        });        var attributes= ['cid', 'clientname', 'companyid', 'companyname'];        var clientList = await models.CLD_client.findAllInCid(cid,attributes);                //组合页面需要展示的数据        curingList.forEach(function(v,i){            curingList[i].clientInfo={};            clientList.forEach(function(clientVal,clientI){                if(v.client_id==clientVal.cid){                    curingList[i].clientInfo=clientVal;                }            });            curingList[i].addtime=moment.unix(v.addtime).format('YYYY-MM-DD HH:mm');            curingList[i].id=hash.hashEncode(v.id.toString());            curingList[i].client_id=hash.hashEncode(v.client_id.toString());            curingList[i].sso_id=v.sso_id;        });        //curingList['pageData']=pageData;        return {curingList:curingList,pageData:pageData};*/    },    //获得本地编办列表    getCuringCompilationList:async function (){        var compilationList = await models.cloud_curing.getCuringCompilationList();        return compilationList;        /*var curingList = await models.cloud_curing.getCuringByMobile(mobile);        if (curingList!=null){            var cid=[curingList['client_id']];            var attributes= ['cid', 'clientname', 'companyid', 'companyname'];            var clientList = await models.CLD_client.findAllInCid(cid,attributes);            curingList.clientname='';            curingList.companyname='';            clientList.forEach(function(clientVal,clientI){                if(curingList.client_id==clientVal.cid){                    curingList.clientname=clientVal.clientname;                    curingList.companyname=clientVal.companyname;                }            });            curingList.addtime=moment.unix(curingList.addtime).format('YYYY-MM-DD HH:mm');        }        */    },    //获得养护编办    getCompilationList:async function (){        var url= curingUrl+'/getCompilationList';        var data= await curlRequest(url);        return data;    },    //获取本地养护数据    getBindCuringByMobile:async function (mobile){        var curingList = await models.cloud_curing.getCuringByMobile(mobile);        if (curingList!=null){            var cid=[curingList['client_id']];            var attributes= ['cid', 'clientname', 'companyid', 'companyname'];            var clientList = await models.CLD_client.findAllInCid(cid,attributes);            curingList.clientInfo={};            clientList.forEach(function(clientVal,clientI){                if(curingList.client_id==clientVal.cid){                    curingList.clientInfo=clientVal;                }            });            curingList.addtime=moment.unix(curingList.addtime).format('YYYY-MM-DD HH:mm');        }        return curingList;    },    //根据手机号码获得养护用户信息    getCuringByMobile: async function(mobile){        var url= curingUrl+'/getUsersAndCompilation?mobile='+ mobile;        var userData= await curlRequest(url);        return userData;    },    //根据通行证ID获得养护相关的所有信息    getCuringBySsoid: async function(ssoid,client_id){        var curingSsoid=ssoid;        if(!hash.isNotANumber(ssoid)){            ssoid=hash.hashDecode(ssoid);            if(!hash.isNotANumber(ssoid)){                return [];            }        }        var url= curingUrl+'/getUsersAndCompilation?ssoID='+ ssoid;        var userData= await curlRequest(url);        if(!hash.isExistence(userData)){            return [];        }        //本地养护用户        userData['curingInfo']=await models.cloud_curing.getCuringBySsoid(curingSsoid);        client_id=userData['curingInfo']['client_id'];        /*userData['clientInfo']='';        if(!hash.isNotANumber(client_id)){            client_id=hash.hashDecode(client_id);            if(!hash.isNotANumber(client_id)){                userData['clientInfo']=[];            }        }*/        var detail =[];        if(hash.isExistence(client_id)){                 detail = await models.CLD_client.findById(client_id);        }        userData['clientInfo']=detail;        //组合数据升级产品数据        userData['compilationList'].forEach(function(value,key){            userData['userInfo']['upgrade_list'].forEach(function(v,k){                if(v['compilationID']==value['_id']){                    userData['compilationList'][key]['isUpgrade']=v['isUpgrade'];                }            });        });        userData['userInfo']['ssoIdKey']=hash.hashEncode(userData['userInfo']['ssoId'].toString());        //获得操作日志        userData['operateLog']=[];        if(hash.isExistence(userData['curingInfo'])){            userData['operateLog']=await models.operate_log.findByCondition(1,hash.hashDecode(userData['curingInfo']['id']));        }        return userData;    },    upCuringDo: async function(data){        var url =  curingUrl+'/setUserUpgrade';        var ssoid=hash.hashDecode(data.ssoid);        var postData ={'ssoId':ssoid,'cid':data.compilationId};        var result= await postRequest(url,postData);        result=JSON.parse(result);        if(result.error==0){   //接口更新成            var curingDetail=await models.cloud_curing.getCuringByMobile(data.mobile);            var id='';            if(hash.isExistence(curingDetail)){ //是否需要同步同步到本地库中                var url= curingUrl+'/getUsersAndCompilation?ssoID='+ ssoid;                var userData= await curlRequest(url);                //获得更新数量updateTotal                var updateTotal=0;                userData['userInfo']['upgrade_list'].forEach(function(value,key){                    if(value['isUpgrade']){                        updateTotal++;                    }                });                //更新数量                var values = {                    updateTotal: updateTotal                }                var where={                    where: {id: curingDetail['id']}                };                await models.cloud_curing.update(values,where);                id=curingDetail['id'];            }else{            	sid=hash.hashDecode(STAFF.sid);                //获得登陆用户相关信息                var obj = {                    mobile: data.mobile,                    sso_id: data.ssoid,                    compilation_id: data.compilationId,                    curingCompany: data.name,                    sid: sid,                    cid: STAFF.cid,                    status: 1,                    addtime: new Date().getTime(),                    updateTotal: 1                };                var detail=await models.cloud_curing.create(obj);                id=detail['cloud_curing']['id'];            }            var operation=STAFF.username+'升级'+data.name;            //记录锁日志            await models.operate_log.createOperateLog(1,id,operation);            return true;        }else{            return false;        }    },    //养护用户绑定CLD客户    relevanceClientDo: async function(data){        var cid=hash.hashDecode(data.cidKey);        var id=hash.hashDecode(data.id);        if(!hash.isNotANumber(cid)||!hash.isNotANumber(id)){            return false;        }        var curingDetail=await models.cloud_curing.getCuringById(id);        if(hash.isExistence(curingDetail)) {            var clientDetail=await models.CLD_client.findById(cid);            if(hash.isExistence(clientDetail)){                //更新数量                var values = {                    client_id: cid                }                var where={                    where: {id: curingDetail['id']}                };                await models.cloud_curing.update(values,where);                //记录操作日志                var operation=STAFF.username+'关联CLD联系人'+clientDetail.clientname;                await models.operate_log.createOperateLog(1,id,operation);                return true;            }else{                return false;            }        }else{            return false;        }    },    //移除关联CLD客户    relieveClientDo: async function(data){        var id=hash.hashDecode(data.id);        if(!hash.isNotANumber(id)){            return false;        }        var curingDetail=await models.cloud_curing.getCuringById(id);        if(hash.isExistence(curingDetail)) {            //更新数量            var values = {                client_id: ''            }            var where={                where: {id: curingDetail['id']}            };            await models.cloud_curing.update(values,where);            var clientDetail=await models.CLD_client.findById(curingDetail['client_id']);            //记录操作日志            var operation=STAFF.username+'移除CLD联系人'+clientDetail.clientname;            await models.operate_log.createOperateLog(1,id,operation);            return true;        }else{            return false;        }    },}module.exports = cloudService;//接口调用var curlRequest = async function(url){    var got = require('got');    var data=[];    await got(url, { json: true,timeout:300 }).then(response => {        data= response.body.data;}).catch(error => {    console.log('GET调用接口超时');});return data;}var postRequest= async function(url,data){    //var fs = require('fs');    var got = require('got');    var qs = require('querystring');    var keysList=Object.keys(data);    var content = qs.stringify(data);    result= await got.post(url, {            body: content,            timeout:300,            headers: {                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'            }        }).catch(error => {            console.log('POST调用接口超时');    });    return result.body;//var FormData = require('form-data');//var form = new FormData();/* keysList.forEach(function(v,i){ console.log(v); form.append(v, data[v]); });*///form.append('ssoId', data.ssoId);//form.append('cid', data.cid);//console.log(form);//console.log(keysList);//form.append('my_file', fs.createReadStream('/foo/bar.jpg'));//?longle=12//url='http://cld.com/longle/list/add';//var content = qs.stringify({'longle':125});//console.log(data);}var modelsQuery= async function(sql){    var data=[];    await models.sequelize.query(sql).spread((results, metadata) => {        // 结果将是一个空数组,元数据将包含受影响的行数。        data=results;    });    return data;}/** * 分页相关数据计算 * modelsTable 数据表对象 * parameter 设置传的参数 */var getPage= async function(modelsTable,where,currentPage,pageSize,parameter,totalCount){		if(!hash.isExistence(totalCount)){		if(hash.isExistence(where)){	        totalCount=await modelsTable.count({where});	    }else{	    	totalCount=await modelsTable.count();	    }	}    currentPage=parseInt(currentPage);    var total =0;    if(totalCount!=0){    	total = Math.trunc ( totalCount / pageSize );    }    var totalPage = (totalCount % pageSize) == 0 ? total : total + 1;    var page={        'currentPage':currentPage,  //当前页        'previousPage':currentPage!=0?currentPage-1:currentPage,    //上一页        'nextPage': currentPage==totalPage ? totalPage:currentPage+1,        'totalPage':totalPage,        'parameter':encodeURI(parameter)    };    return page;}
 |