import {
	httpGet,
	RefreshToken,
	httpPost,
	setCode,
	httpGet1,
	httpPost1,
	httpGetno,
	httpPostno,
	silentRequest
} from '@/api/index'

import {
	api
} from '@/api/all'
import utils from '@/utils/util.js'
import moment from "moment"

// zg注册设备
export default class RequestSet {
  // 冻结管理 action 0-解冻，1-冻结
    static freeUserManage(action,row,callback){
      let order=""
        if(action==0){
          order=6127
        }else if(action==1){
          order=6126
        }
        var data={
          code: "zg/bleRegisterInfo",
          data: {lockerId: row.deviceNum}
        }
        httpPost(data,api.sendCommand).then(res=>{
          if(res.code==200){
            var data1={
              code: "zg/frozenUserOperation",
              data: {
                lockerId: row.deviceNum,
                lockerSuperAdminId: res.data.superId,
                lockerUserId:row.userId,
                keyId:row.keyId,
                action:action,
                frozenStartTime:row.frozenStartTime,
                frozenEndTime:row.frozenEndTime,
                authKey:res.data.authKey,
                order:order,
                roomName:row.roomName,
                cardName:row.name,
              }
            }
             httpPost(data1,api.sendCommand).then(res1=>{
               if(res1.code==200){
                  callback(res1)
               }else{
                  callback(res1)
               }
             })
          }else{
            callback(res)
          }
        })
      }
  // 冻结管理 action 0-解冻，1-冻结
    static freeManageMethods(action,row,callback){
        let order=""
        if(action==0){
          order=5103
        }else if(action==1){
          order=5104
        }
        var data={
          code: "zg/bleRegisterInfo",
          data: {lockerId: row.deviceNum}
        }
        httpPost(data,api.sendCommand).then(res=>{
          if(res.code==200){
            var data1={
              code: "zg/frozenOperation",
              data: {
                lockerId: row.deviceNum,
                lockerSuperAdminId: res.data.superId,
                keyId:res.data.superId,
                action:action,
                frozenStartTime:"1659077751",
                frozenEndTime:"1911538551",
                authKey:res.data.authKey,
                order:order,
                roomName:row.roomName,
                cardName:"管理员",
              }
            }
             httpPost(data1,api.sendCommand).then(res1=>{
               if(res1.code==200){
                  callback(res1)
               }else{
                  callback(res1)
               }
             })
          }else{
            callback(res)
          }
        })
      }
	// 注册设备
	static RegisterDevice(data, callback) {
		if (data.manufactureId == 101) {
			var str = {
				data: {
					deviceNum: data.deviceNum,
					imei: data.imei,
					imsi: data.imei, //row.imsi,
					order: 5101,
					platformId: data.platformId,
					manufactureId: data.manufactureId,
				},
				code: "/v1/isp/registerDevice",
				enterpriseId: data.enterpriseId,
				key: data.deviceNum
			}
			httpPost(str, api.registerDeviceAll).then((res) => {
				callback(res)
			});
		} else if (data.manufactureId == 201 || data.manufactureId == 221) {
			var str = {
				data: {
					lockerId: data.lockerId,
					imei: data.imei,
					customerCode: data.customerCode,
					lockerSuperAdminId: data.lockerSuperAdminId,
					authKey: data.authKey,
					type: data.type,
					manufactureId: data.manufactureId,
					order: 5101,
				},
				code: "/v1/zg/registerDevice",
				enterpriseId: data.enterpriseId,
				key: data.lockerId
			}
			httpPost(str, api.registerDeviceAll).then(res => {
				callback(res)
			});
		} else if (data.manufactureId == 799) {
			var str = {
				data: {
					deviceNum: data.deviceNum,
					validateCode: data.validateCode,
					manufactureId: data.manufactureId,
					order: 5101,
				},
				code: "/v1/ys/registerDevice",
				enterpriseId: data.enterpriseId,
				key: data.deviceNum
			}
			httpPost(str, api.registerDeviceAll).then(res => {
				callback(res)
			});
		} else if (data.manufactureId == 1003) {
			var str = {
				data: {
					deviceNum: data.deviceNum,
					order: 5101,
					platformId: data.platformId,
					manufactureId: data.manufactureId,
				},
				code: "/v1/common/registerDevice",
				enterpriseId: data.enterpriseId,
				key: data.deviceNum
			}
			httpPost(str, api.registerDeviceAll).then(res => {
				callback(res)
			});
		} else {
			var str = {
				data: {
					deviceNum: data.deviceNum,
					imei: data.imei,
					imsi: data.imei,
					order: 5101,
					platformId: data.platformId,
					manufactureId: data.manufactureId,
				},
				code: "/v1/isp/registerDevice",
				enterpriseId: data.enterpriseId,
				key: data.deviceNum
			}
			httpPost(str, api.registerDeviceAll).then(res => {
				callback(res)
			});
		}
	}
	// 删除设备
	static DeleteDevic(data, manufactureId, callback) {
		if (manufactureId == 101) {
			var str = {
				device: data.deviceNum,
				imei: data.imei,
				order: data.order
			}
			httpPost(str, api.deleteDevice).then(res => {
				callback(res)
			})
		} else if (manufactureId == 201|| data.manufactureId == 221) {
			var str = {
				lockerId: data.deviceNum,
				imei: data.imei,
				order: data.order
			}
			return httpPost(str, api.ZGdeleteDevice);
		} else if (manufactureId == 799) {
			var str = {
				deviceNum: data.deviceNum,
				order: data.order
			}
			httpPost(str, api.fluoriteDeleteDevice).then(res => {
				callback(res)
			})
		} else if (manufactureId == 707 || manufactureId == 706 || manufactureId == 702) {
			var str = {
				code: "ys/deviceUnlink",
				data: {
					deviceNum: data.deviceNum,
					gatewayDevice: data.gatewayDevice
				}
			}
			httpPost(str, api.sendCommand).then(res => {
				callback(res)
			})
		} else if (manufactureId == 1003) {
			var str = {
				code: "common/deleteDevice ",
				data: {
					deviceNum: data.deviceNum
				}
			}
			httpPost(str, api.sendCommand).then(res => {
				callback(res)
			})
		} else {
			var str = {
				device: data.deviceNum,
				imei: data.imei,
				order: data.order
			}
			httpPost(str, api.deleteDevice).then(res => {
				callback(res)
			})
		}
	}
	// 网关绑定子设备
	static gatewayBindsChildDevic(data, callback) {
		var str = {
			data: {
				deviceNum: data.deviceNum,
				gatewayDevice: data.gatewayDevice,
				manufactureId: data.manufactureId,
				order: 5101,
			},
			code: "/v1/ys/deviceLink",
			enterpriseId: data.enterpriseId,
			key: data.deviceNum
		}
		httpPost(str, api.registerDeviceAll).then(res => {
			callback(res)
		})
	}
	// 获取网关子设备
	static getGatewaySubequipment(deviceNum, callback) {
		var data2 = {
			code: "ys/childDeviceList",
			data: {
				deviceNum: deviceNum,
			}
		}
		httpPost(data2, api.sendCommand).then(res => {
			callback(res)
		})
	}
	// 获取统计
	static getAnalysis(data, type, callback) {
		silentRequest(data, `/v1/statistics/analysis/${type}`).then((res) => {
			callback(res)
		});

	}
	// 获取设备警告日志
	static getWarningLog(data, callback) {
		var data1 = {
			pageNum: 1,
			pageSize: 10,
			q: JSON.stringify({
				deviceType: data.deviceType
			}),
			orderBy: "alert_time desc"
		};
		silentRequest(data1, api.getLockAlert).then((res) => {
			callback(res)
		})
	}
	// 添加凭证(不执行)
	static staaddingCredentialsIsNotExecuted(data, callback) {
		var data = {
			cardId: data.cardId,
			content: data.content, //operateMode:NFC-10、把人员添加到凭证-1
			type: data.type,
			startTime: data.startTime,
			endTime: data.endTime,
		};
		httpPost(data, api.addCertificates).then((res) => {
			callback(res)
		})
	}
	// 获取空开信息
	static getAirSwitchMethds(data, callback) {
		var para = {
			pageNum: data.pageNum,
			pageSize: data.pageSize,
			q:data.q
		}
		httpGet(data, api.getAirSwitch).then(res => {
			callback(res)
		})
	}
	// 添加人员
	static addPeople(data, callback) {
		var data = {
			cardId: data.cardId,
			cardState: data.cardState,
			info: data.info,
			name: data.name,
			number: data.number,
			phone: data.phone,
			sex: parseInt(data.sex),
			enterpriseId: data.enterpriseId,
			type: data.type,
		};
		httpPost(data, api.addCard).then((res) => {
			callback(res)
		}).catch(err => {
			callback(err)
		})
	}








	// 补全人员凭证
	static completePersonnelVouchers(item,index,type){
		var content=JSON.parse(item.content)
		var pzname='';
		if(type==1){
			if(content.pzname==""){
				pzname='密码'+(index+1)
			}else{
				pzname=content.pzname
			}
			var str ={
					userTelephone: content.userTelephone,
					userPassword: content.userPassword,
					password: content.password,
					length: content.length,
					fpTimeId: content.fpTimeId,
					operateMode: content.operateMode,
					type: 11,
					order: 6216,
					fingerprint: content.fingerprint,
					passwordStartTime: content.passwordStartTime,
					passwordEndTime: content.passwordEndTime,
					pzname: pzname,
					cardName: item.cardName
				};
			var data = {
				cardId: item.cardId,
				content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
				type: 11,
				startTime: item.startTime,
				endTime: item.endTime
			};
			httpPost(data, api.addCertificates).then((res) => {

			})
		}else if(type==2){
			if(content.pzname==""){
				pzname='身份证'+(index+1)
			}else{
				pzname=content.pzname
			}
			var str = {
				userTelephone: content.userTelephone,
				userPassword: content.userPassword,
				password: content.password,
				operateMode: content.operateMode,
				type: 12,
				order: 6213,
				fingerprint: content.fingerprint,
				passwordStartTime: content.passwordStartTime,
				passwordEndTime: content.passwordEndTime,
				pzname: pzname,
				cardName: item.cardName
			};
			var data = {
				cardId: item.cardId,
				content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
				type: 12,
				startTime: item.startTime,
				endTime: item.endTime
			};
			httpPost(data, api.addCertificates).then((res) => {

			})
		}else if(type==3){
			if(content.pzname==""){
				pzname='NFC'+(index+1)
			}else{
				pzname=content.pzname
			}
			var password=utils.cardFormatConversion(content.password)
			var str = {
				userTelephone: content.userTelephone,
				userPassword: content.userPassword,
				password: password,
				operateMode: content.operateMode,
				type: 13,
				order: 6210,
				fingerprint: content.fingerprint,
				passwordStartTime: content.passwordStartTime,
				passwordEndTime: content.passwordEndTime,
				pzname: pzname,
				cardName: item.cardName
			};
			var data = {
				cardId: item.cardId,
				content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
				type: 13,
				startTime: item.startTime,
				endTime: item.endTime
			};
			httpPost(data, api.addCertificates).then((res) => {

			})
		}else if(type==4){
			if(content.pzname==""){
				pzname='密码'+(index+1)
			}else{
				pzname=content.pzname
			}
			var str = {
				userTelephone: content.userTelephone,
				userPassword: content.userPassword,
				password: content.password,
				operateMode: content.operateMode,
				type: 14,
				order: 6207,
				fingerprint: content.fingerprint,
				passwordStartTime: content.passwordStartTime,
				passwordEndTime: content.passwordEndTime,
				pzname: pzname,
				cardName: item.cardName
			};
			var data = {
				cardId: item.cardId,
				content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
				type: 14,
				startTime: item.startTime,
				endTime: item.endTime
			};
			httpPost(data, api.addCertificates).then((res) => {

			})
		}
	}
	// 获取凭证列表
	static GetCredentialList(item,type,callback){
			var data = {
				pageNum: 0,
				pageSize: 0,
				orderBy: "create_at desc",
				q: JSON.stringify({
					cardId: item.id,
					instatus:"0,1",
					types: type,
				}),
			};
			httpGet(data, api.getCertificates).then((res) => {
					callback(res)
			}).catch(err=>{
				callback(err)
			})
	}
	// 根据id获取房源完整路径
	static getFullPathHousing(item,data,name){
			console.log(name,item)
		if(item.id==item.pid){
			name.push(item.name)
			// console.log(name,item)
			return name
		}else{
			data.map(li=>{
				if(li.id==item.id){
					name.push(li.name)
			// console.log(name,item)
					this.getFullPathHousing(li,data,name)
				}
			})
		}
	}
	// 是否可以解绑人员和房间关系
	static unbindPeopleAndRooms(personid,imei,callback){
			var data = {
				pageNum: 0,
				pageSize: 1,
				orderBy: "create_at desc",
				q: JSON.stringify({
					cardId: personid,
					imei:imei,
					instatus:"0,1",
					type: 26,
				}),
			};
			httpGet(data, api.getCertificates).then((res) => {
					callback(res)
			}).catch(err=>{
				callback(err)
			})
	}
	// 获取某个人某种凭证编号
	static getCertificatesNum(id,type,mode,content){
		if(mode == 1){
			var data = {
				pageNum: 0,
				pageSize: 1,
				orderBy: "create_at desc",
				q: JSON.stringify({
					cardId: id,
					type: type
				}),
			};
			httpGet(data, api.getCertificates).then((res) => {
				if(res.success){
					return res.data.total+1
				}else{
					return 1
				}
			}).catch(err=>{
				return 1
			})
		}else if(mode ==2){
			var data = {
				pageNum: 0,
				pageSize: 1,
				orderBy: "create_at desc",
				q: JSON.stringify({
					cardId: id,
					password:content,
					type: type,
					types: "10,11,12,13,14"
				}),
			};
			httpGet(data, api.getCertificates).then((res) => {
				if(res.success){
          let dataOne=utils.zlib_unzip(res.data)
					let pzname=JSON.parse(dataOne[0].content).pzname
					return pzname
				}else{
					return ''
				}
			}).catch(err=>{
				return ''
			})
		}
	}
	// 16进制转10进制
	static hex2int(hex, callback) {
		var len = hex.length,
			a = new Array(len),
			code;
		for (var i = 0; i < len; i++) {
			code = hex.charCodeAt(i);
			if (48 <= code && code < 58) {
				code -= 48;
			} else {
				code = (code & 0xdf) - 65 + 10;
			}
			a[i] = code;
		}
		let str = a.reduce(function(acc, c) {
			acc = 16 * acc + c;
			return acc;
		}, 0);
		callback(str)
	}
	static int2hex(num, width) {
		var hex = "0123456789abcdef";
		var s = "";
		while (num) {
			s = hex.charAt(num % 16) + s;
			num = Math.floor(num / 16);
		}
		if (typeof width === "undefined" || width <= s.length) {
			return "0x" + s;
		}
		var delta = width - s.length;
		var padding = "";
		while (delta-- > 0) {
			padding += "0";
		}
		return "0x" + padding + s;
	}
	// 判断设备最近日志是否在num秒内
	static judgmentTimestamp(alertTime) {
		var curDate = new Date().getTime() / 1000
		var endDate = parseInt(curDate - alertTime)
		if (endDate > 5) {
			return false
		} else {
			return true
		}
	}
	static voucherClassification(data) {
		let str = []
		var array = this.groupBy(data, ["type", "password"], function(cul, data) {
			return cul + 1
		})
		console.log(array)
	}
	static getAlertTypeOrder(data, type, callback) {
		silentRequest(data, `/v1/statistics/alert/by/order/${type}`).then((res) => {
			callback(res)
		});
	}

	static classification() {
		let day = []
		for (let i = 0; i < 7; i++) {
			var time = moment(new Date()).subtract(i, "days").format("YYYY-MM-DD")
			day.push(time)
		}
		return day.reverse()
	}
	static loopObjectSum(array, alertTypeList) {
		var objectArray = []
		var days = this.classification()
		for (let i in array) {
			var alertTypeDesc = alertTypeList.filter(item => item.code == i)[0]
			var obj = {}
			if (alertTypeDesc) {
				obj = {
					name: alertTypeDesc.desc,
					value: array[i]
				}
			} else {
				obj = {
					name: '',
					value: array[i]
				}
			}
			objectArray.push(obj)
		}
		return objectArray
	}
	static loopObject(array, alertTypeList) {
		var objectArray = []
		var days = this.classification()
		for (let i in array) {
			var alertTypeDesc = alertTypeList.filter(item => item.code == i)[0]
			var obj = {}
			if (alertTypeDesc) {
				obj = {
					name: alertTypeDesc.desc,
					type: 'line',
					// stack: 'Total',
					arr: array[i],
					data: new Array(7).fill(0)
				}
			} else {
				obj = {
					name: '',
					type: 'line',
					// stack: 'Total',
					arr: {},
					data: new Array(7).fill(0)
				}
			}
			objectArray.push(obj)
		}

		objectArray.map((li, index) => {
			for (let j in li.arr) {
				var index1 = days.map(item => item).indexOf(j)
				if (index1 != -1) {
					li.data[index1] = li.arr[j]
				}
			}
		})
		return objectArray
	}
	/**
	 * 分组统计
	 * @param datas 数据集合
	 * @param keys 分组键值
	 * @param callback 回调函数(例如求和还是计算总数)
	 * @returns {{}}
	 */
	static deWeight(arr, ...arguements) {
	  // console.log(arguements);//获得需要去重的字段数组
	  function getBoolean(o, m) {
		let list = arguements.map(x => o[x] == m[x]); //值均为布尔
		return list.every(i => i); //要使这些布尔值都真才能满足条件，因为要求的条件是 并且
	  }
	  let result = [];//新数组
	  //总数组与新数组比较，遍历总数组时用新数组的some方法进行判断
	  arr.map(o => !result.some(m => getBoolean(o, m)) ? result.push(o) : '');
	  return result;
	}
	static groupBy(datas, keys, callback) {
		var groups = {};
		var len = keys.length;
		datas.forEach(function(data) {
			var tempObj = null;
			keys.forEach(function(key, index) {
				var val = data[key];
				if (tempObj == null) {
					tempObj = groups;
				}
				//最后一个元素赋值操作
				if (index == len - 1) {
					var cal = 0;
					if (tempObj.hasOwnProperty(val)) {
						cal = tempObj[val];
					}
					tempObj[val] = callback(cal, data);
				} else {
					if (tempObj.hasOwnProperty(val)) {
						tempObj = tempObj[val];
					} else {
						tempObj[val] = {};
						tempObj = tempObj[val];
					}
				}
			})

		});

		return groups;
	}
}
