const { postGroup, getGroup, putGroup, delGroup } = require('../../api/group')
const { postDevice, getDevice, putDevice, delDevice } = require('../../api/device')
const { getBasic, getData, postData } = require('../../api/intell')

// pages/scene/scene.js
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		remove: true, //删除工程
		Modify: true, //修改工程名称
		array: [], //分组
		brray: [],
		keyid: [],
		inputVal: [],
		getName: [], //发送往服务器的工程名称参数
		subscript: 0,
		Id: [],
		key: [],
		developline: [],
		status: 0,
		Status: "",
		phone: '',
		displaypicture: "https://cloud.long-chi.com/resource/miniprogram-lightcontrol/image/ling.png",
		display: []
	},
	//刷新列表
	Refreshlist: function() {
		wx.showToast({
			title: '获取数据中',
			icon: 'loading',
			duration: 2000
		})
		var that = this
		getGroup().then(res => {
			if (res.data.code == 0) {
				var data = res.data.data
				if (data != null) {
					for (let i = 0; i < data.length; i++) {
						if (data[i].devices != null) {
							for (let j = 0; j < data[i].devices.length; j++) {
								if (data[i].devices[j].module == 0) {
									let id = data[i].devices[j].deviceId
									let key = data[i].devices[j].deviceKey
									getBasic(id, key).then(ever => {
										if (ever.data.errno == 0) {
											if (ever.data.data.online == true) {
												data[i].devices[j].status = '在线'
											} else {
												data[i].devices[j].status = '离线'
											}
										} else {
											wx.showModal({
												title: '错误',
												content: ever.data.error,
												showCancel: false
											})
										}
									})
								} else {
									let status = data[i].devices[j].status
									switch (status) {
										case 0:
											data[i].devices[j].status = '离线'
											break;
										case 1:
											data[i].devices[j].status = '在线'
											break
									}
								}
							}
						} else {
							wx.setStorageSync('group', data)
							let group = wx.getStorageSync('group')
							for (let i = 0; i < group.length; i++) {
								if (group[i].groupName.length > 10) {
									group[i].groupName = group[i].groupName.slice(0, 9) + '....'
								}
							}
							that.setData({ array: group })
						}
					}
				}
				setTimeout(function() {
					wx.setStorageSync('group', data)
					let tgroups = wx.getStorageSync('group')
					that.nameRestriction(tgroups)
				}, 1500)
			} else {
				wx.showModal({
					title: '错误',
					content: res.data.msg,
					showCancel: false
				})
			}
		})
	},
	//添加分组
	apption: function() {
		var that = this
		wx.showModal({
			title: '添加工程',
			editable: true,
			placeholderText: '请输入名称',
			success: function(ever) {
				if (ever.confirm) {
					if (ever.content == '') {
						wx.showModal({
							title: '提示',
							content: '请输入工程名',
							showCancel: false
						})
					} else if (ever.content.length > 15) {
						wx.showModal({
							title: '提示',
							content: '分组名称不能大于15个字符',
							showCancel: false
						})
					} else {
						postGroup({ groupName: ever.content }).then((res) => {
							if (res.data.code == 0) {
								if (wx.getStorageSync('group') == '') {
									wx.setStorageSync('group', [])
									var a = wx.getStorageSync('group')
									a.push({
										id: res.data.data.id,
										groupName: ever
											.content,
										devices: []
									})
									wx.setStorageSync('group', a)
								} else {
									var b = wx.getStorageSync('group')
									b.push({
										id: res.data.data.id,
										groupName: ever
											.content,
										devices: []
									})
									wx.setStorageSync('group', b)
								}
								var group = wx.getStorageSync('group')
								that.nameRestriction(group)
							} else {
								wx.showModal({
									title: '错误',
									content: res.data.msg,
									showCancel: false
								})
							}
						})
					}
				}
			}
		})
	},
	//删除分组
	removeapption: function(e) {
		var that = this
		wx.showModal({
			title: '提示',
			content: '确定删除该工程',
			success: function(res) {
				if (res.confirm) {
					var index = e.currentTarget.dataset.indexdel //获取对应下标
					var Idindex = that.data.array[index].id
					var groupName = that.data.array[index].groupName
					delGroup(Idindex).then((res) => {
						if (res.data.code == 0) {
							if (groupName == wx.getStorageSync('groupName')) {
								wx.setStorageSync('groupName', '')
								wx.setStorageSync('deviceName', '')
							}
							var deleteid = wx.getStorageSync('group')
							deleteid.splice(index, 1)
							wx.setStorageSync('group', deleteid)
							var Group = wx.getStorageSync('group')
							that.nameRestriction(Group)
						} else {
							wx.showModal({
								title: '提示',
								content: res.data.msg,
								showCancel: false
							})
						}
					})
				}
			}
		})
	},
	//修改分组名称
	ShowChanges: function(e) {
		var that = this
		wx.showModal({
			title: '修改工程名称',
			editable: true,
			placeholderText: '请输入名称',
			success: res => {
				if (res.confirm) {
					var index = e.currentTarget.dataset.indexdel //获取对应下标
					var Idindex = that.data.array[index].id //获取对应下标的id值
					var groupName = that.data.array[index].name
					if (res.content == '') {
						wx.showModal({
							title: '提示',
							content: '请输入工程名',
							showCancel: false
						})
					} else if (res.content.length > 15) {
						wx.showModal({
							title: '提示',
							content: '分组名称不能大于15个字符',
							showCancel: false
						})
					} else {
						putGroup({ id: Idindex, groupName: res.content }).then(ever => {
							if (ever.data.code == 0) {
								if (groupName == wx.getStorageSync('groupName')) {
									wx.setStorageSync('groupName', res.content)
								}
								let group = wx.getStorageSync('group')
								group[index].groupName = res.content
								wx.setStorageSync('group', group)
								var Group = wx.getStorageSync('group')
								that.nameRestriction(Group)
							} else {
								wx.showModal({
									title: '提示',
									content: ever.data.msg,
									showCancel: false
								})
							}
						})
					}
				}
			}
		})
	},
	//扫码(添加设备)
	scanCodeEvent: function(e) {
		var that = this
		var index = e.currentTarget.dataset.indexdel //获取对应下标
		var Idindex = that.data.array[index].id //分组Id
		Idindex = parseInt(Idindex)
		var group = wx.getStorageSync('group')
		//获取设备
		wx.scanCode({
			success(res) {
				if (res.result.substring(0, 1) == '{') {
					let parameter = res.result.match(/\d+(\.\d+)?/g)
					let ID = parameter[0]
					let SN = parameter[1]
					//添加设备
					postDevice({
						groupId: Idindex,
						deviceSn: SN,
						deviceId: ID,
						module: 1,
						deviceName: SN
					}).then(add => {
						if (add.data.code == 0) {
							//查询设备
							getDevice(add.data.data.id, Idindex).then(get => {
								var Get = get.data.data
								switch (Get.status) {
									case 0:
										Get.status = '离线'
										break
									case 1:
										Get.status = '在线'
										break
								}
								if (group[index].devices != null) {
									group[index].devices.push(Get)
								} else {
									group[index].devices = []
									group[index].devices.push(Get)
								}
								wx.setStorageSync('group', group)
								var Group = wx.getStorageSync('group')
								that.nameRestriction(Group)
							})
						} else {
							wx.showModal({
								title: '提示',
								content: add.data.msg,
								showCancel: false
							})
						}
					})
				}
				//dsx添加的设备
				else if (res.result.substring(0, 2) == 86) {
					let ID = res.result
					let SN = res.result
					//添加设备
					postDevice({
						groupId: Idindex,
						deviceSn: SN,
						deviceId: ID,
						module: 3,
            circuitNum:2,
						deviceName: SN
					}).then(add => {
						if (add.data.code == 0) {
							//查询设备
							getDevice(add.data.data.id, Idindex).then(get => {
								var Get = get.data.data
								switch (Get.status) {
									case 0:
										Get.status = '离线'
										break
									case 1:
										Get.status = '在线'
										break
								}
								if (group[index].devices != null) {
									group[index].devices.push(Get)
								} else {
									group[index].devices = []
									group[index].devices.push(Get)
								}
								wx.setStorageSync('group', group)
								var Group = wx.getStorageSync('group')
								that.nameRestriction(Group)
							})
						} else {
							wx.showModal({
								title: '提示',
								content: add.data.msg,
								showCancel: false
							})
						}
					})
				} else {
					var arr = res.result.split(' ');
					var a = arr[0] //设备id
					var b = arr[1] //设备key
					//获取该设备的在线状态和编码
					getBasic(a, b).then(ever => {
						if (ever.data.errno == 0) {
							var online = ever.data.data.online //设备在线状态
							switch (online) {
								case true:
									that.setData({ status: 1 })
									that.setData({ Status: "在线" })
									break;
								default:
									that.setData({ status: 0 })
									that.setData({ Status: "离线" })
									break;
							}
							var title = ever.data.data.title //设备编码
							getData(a, b).then(gu => {
								if (gu.data.errno == 0) {
									let trys = gu.data.data
									for (let w = 0; w < trys.length; w++) {
										if (trys[w].id == "RelayCount") {
											var num = trys[w].current_value
											num = parseInt(num)
										}
									}
									var numName = ''
									for (let p = 0; p < num; p++) {
										numName = numName + '回路' + (p + 1) + ','
									}
									numName = numName.slice(0, numName.length - 1)
									//添加设备
									postDevice({
											groupId: Idindex,
											deviceSn: title,
											deviceName: title,
											deviceId: a,
											deviceKey: b,
											status: that.data.status,
											circuitNum: num,
											circuits: numName,
											module: 0
										})
										.then(su => {
											if (su.data.code == 0) {
												//将设备的信息储存至本地
												if (group[index].devices !=
													null) {
													group[index].devices.push({
														id: su.data.data.id,
														deviceSn: title,
														deviceName: title,
														status: that.data.Status,
														deviceId: a,
														deviceKey: b,
														circuitNum: num,
														circuits: numName,
														module: 0
													})
												} else {
													group[index].devices = []
													group[index].devices.push({
														id: su.data.data
															.id,
														deviceSn: title,
														deviceName: title,
														status: that
															.data
															.Status,
														deviceId: a,
														deviceKey: b,
														circuitNum: num,
														circuits: numName,
														module: 0
													})
												}
												wx.setStorageSync('group',
													group)
												var Group = wx.getStorageSync(
													'group')
												that.nameRestriction(Group)
											} else {
												wx.showModal({
													title: '提示',
													content: su.data
														.msg,
													showCancel: false
												})
											}
										})
								} else {
									wx.showModal({
										title: '错误',
										content: gu.data.error,
										showCancel: false
									})
								}
							})
						} else {
							wx.showModal({
								title: '错误',
								content: ever.data.error,
								showCancel: false
							})
						}
					})
				}
			}
		})
	},
	//修改设备名称
	modifyequipmentname: function(e) {
		var that = this
		var key = e.currentTarget.dataset.indexdel
		var group = wx.getStorageSync('group')
		var deviceId = group[key[0]].devices[key[1]].id
		var groupName = group[key[0]].groupName //获取当前的分组名称
		var groupId = group[key[0]].id
		var deviceName = group[key[0]].devices[key[1]].deviceName //获取当前的设备名称
		wx.showModal({
			title: '修改设备名称',
			editable: true,
			placeholderText: '请输入名称',
			success: res => {
				if (res.confirm) {
					if (res.content == '') {
						wx.showModal({
							title: '提示',
							showCancel: false,
							content: '请输入名称'
						})
					} else if (res.content.length > 10) {
						wx.showModal({
							title: '提示',
							showCancel: false,
							content: '设备名称不能大于10个字符'
						})
					} else {
						putDevice({ deviceName: res.content, id: deviceId, groupId: groupId })
							.then(ever => {
								if (ever.data.code == 0) {
									if (groupName == wx.getStorageSync('groupName') &&
										deviceName == wx.getStorageSync('deviceName')) {
										wx.setStorageSync('deviceName', res.content)
									}
									group[key[0]].devices[key[1]].deviceName = res.content
									wx.setStorageSync('group', group)
									var Group = wx.getStorageSync('group')
									that.nameRestriction(Group)
								} else {
									wx.showModal({
										title: '错误',
										content: ever.data.msg,
										showCancel: false
									})
								}
							})
					}
				}
			}
		})
	},
	//删除设备
	Deletedevice: function(e) {
		var that = this
		wx.showModal({
			title: '删除设备',
			content: '确定删除该设备吗?',
			success: function(res) {
				if (res.confirm) {
					let key = e.currentTarget.dataset.indexdel //获得分组和设备的下标值([分组下标,设备下标])
					let group = wx.getStorageSync('group')
					let subscript = group[key[0]].devices[key[1]].id //设备对应的id
					var groupName = group[key[0]].groupName
					var deviceName = group[key[0]].devices[key[1]].deviceName
					delDevice(subscript).then(nrg => {
						if (nrg.data.code == 0) {
							group[key[0]].devices.splice(key[1], 1)
							wx.setStorageSync('group', group)
							var Group = wx.getStorageSync('group')
							that.nameRestriction(Group)
							if (groupName == wx.getStorageSync('groupName') &&
								deviceName == wx.getStorageSync('deviceName')) {
								wx.setStorageSync('deviceName', '')
							}
						} else {
							wx.showModal({
								title: '提示',
								content: nrg.data.msg,
								showCancel: false
							})
						}
					})
				}
			}
		})
	},
	//设备的显示隐藏
	Develop: function(e) {
		var that = this
		let array = that.data.array
		var pd = e.currentTarget.dataset.indexdel
		for (let item = 0; item < array.length; item++) {
			if (array[item].id == array[pd].id) {
				//判断当前对象中的insert是否为true(true为显示,其他为隐藏) insert是新增的一个值然后进行判断
				if (array[item].insert == "" || array[item].insert == undefined) {
					array[item].insert = "true"
				} else {
					array[item].insert = ""
				}
			}
		}
		that.setData({
			array: array
		})
	},
	//分组和设备名称的显示限制
	nameRestriction: function(Group) {
		var that = this
		for (let i = 0; i < Group.length; i++) {
			if (Group[i].groupName.length > 10) {
				Group[i].groupName = Group[i].groupName.slice(0, 9) + '....'
			}
			if (Group[i].devices != null) {
				for (let j = 0; j < Group[i].devices.length; j++) {
					if (Group[i].devices[j].deviceName.length > 10) {
						Group[i].devices[j].deviceName = Group[i].devices[j].deviceName.substr(-4)
					}
					if (Group[i].devices[j].deviceSn.length > 10) {
						Group[i].devices[j].deviceSn = Group[i].devices[j].deviceSn.substr(-4)
					}
				}
			}
		}
		that.setData({ array: Group })
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		this.Refreshlist()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		var that = this
		setTimeout(function() {
			if (that.data.array.length == 0) {
				that.Refreshlist()
			}
		}, 1000)
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})