/**
 * Created by MyPC on 2019/11/5.
 */
var models=require('../models');
var moment = require('moment');
const hash=require('../class/hash');
const urlObj=require("url");

//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={

    
	/**
	 * 获得养护列表
	 * paramsCompilation	传参包含
	 * -compilation			已升级编办	
	 * -latestCompilation	最近使用编办
	 */
    getCuringList: async function(req, res){
       
    	//获得远程养护用户
    	//分页数据
    	var page=1;
    	
    	
    	
    	
        var compilation='';
    	var latestCompilation='';
    	var sortField='create_time';
        var sort='-1';
    	
    	//编办参数-排序参数-当前页
        if(hash.isExistence(req.url)){
        	var params = urlObj.parse(req.url, true).query;
        	
        	if(hash.isExistence(params.compilation)){
        		compilation=params.compilation;
        	}
        	if(hash.isExistence(params.latestCompilation)){
        		latestCompilation=params.latestCompilation;
        	}
        	//排序
        	var mAge=1000*60*60*24*28;
        	if(hash.isExistence(params.sortField)){
        		res.cookie('sortField','create_time', {maxAge: mAge});
        		if(params.sortField=='latest_login'){
        			res.cookie('sortField','latest_login', {maxAge: mAge});
        		}
        	}
        	if(hash.isExistence(params.sort)){
        		res.cookie('sort','-1', {maxAge: mAge});
        		if(params.sortField=='1'){
        			res.cookie('sort','1', {maxAge: mAge});
        		}
        	}
        	//当前页数
        	var page=req.params.currentPage;
    	    if(!hash.isNotANumber(page)){
    	    	page=1;
    	    }
        	
        }
        
        if(hash.isExistence(req.cookies.sortField)){
        	sortField=req.cookies.sortField;
    	}
        if(hash.isExistence(req.cookies.sort)){
        	sort=req.cookies.sort;
    	}
        
        //分页参数
        var limit=12;
        var offset=0;
        if(page!=1){
            var pg=page-1;
            offset=pg*limit;
        }
        
        //排序参数
        //var sortField=curingInterfaceConfig.sort[0];
        //var sort=curingInterfaceConfig.sort[1];
        
    	var url= curingUrl+'/getUserList'+
    	'?page='+page+'&pageSize='+limit+'&latestUsed='+latestCompilation+'&upGrade='+compilation+'&sortField='+sortField+'&sort='+sort;
    	/*	接口请求获得的信息
    	 *  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);
       
        //组合同步云版数据
        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,
                        
                       // 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(); //编办信息
        
        //console.log(compilationList);
        
        //数据组合--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 ci=0;ci<compilationList.length;ci++){
            	if(compilationList[ci]._id==v.latest_used){
            		curingCloudList[i].latest_usedName=compilationList[ci].name;
            		break;
            	}
            }
            //登录时长
            if(hash.isExistence(v.online_list)){
            	var onlineTimeLength=v.online_list.length-1;
            	curingCloudList[i].online_newest=v.online_list[onlineTimeLength].online_times+'('+v.online_list[onlineTimeLength].dateString+')';
            }else{
            	curingCloudList[i].online_newest='';
            }
            //已升级专业版
            curingCloudList[i].upgradeListName='';
            for(var gi=1;gi<v.upgrade_list.length;gi++){
            	for(var ci=0;ci<compilationList.length;ci++){
            		if( compilationList[ci]._id == v.upgrade_list[gi].compilationID) {
            			curingCloudList[i].upgradeListName+='<span class="badge badge-primary"><%= compilation.name %></span>';
            			break;
            		}
            	}
            }
            
        });
        
        var parameter='?compilation='+compilation+'&latestCompilation='+latestCompilation;
        //分页计算
        var pageData = await getPage('','',page,limit,parameter,curingCloudData.pageData.total);
        
//console.log(curingCloudList);
        
        
        
        return {curingList:curingCloudList,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;
    },

    /**
     * 用户详情页-数据
     */
    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 pageMax=1;
    var pageWidth=15;
    //开始页数
    var startPage=1;
    if (currentPage >= pageWidth) {
    	pageMax = parseInt ( currentPage / pageWidth ) + 1;
    	startPage = parseInt ( currentPage / pageWidth ) * pageWidth - 1;
	}
    
    //结束页数
    var endPage=pageWidth * pageMax;
    if(endPage>totalPage){
    	endPage=totalPage;
    }
    
    var page={
        'currentPage':currentPage,  //当前页
        'previousPage':currentPage!=0?currentPage-1:currentPage,    //上一页
        'nextPage': currentPage==totalPage ? totalPage:currentPage+1,
        'totalPage':totalPage,
        'startPage':startPage,
        'endPage':endPage,
        'pageWidth':pageWidth,
        'parameter':encodeURI(parameter)
    };
    return page;
}


