<template>
	<view class="deviceRegistWrapper" ref="contentWrapper">

		<!-- 筛选框start -->
		<view>

			<view style="height:206rpx"></view>
			<view class="ding">
				<view class="cu-bar search bg-gray filter-section" style="with:50%;">
					<view class="search-form round bg-white">
						<select name="" id="" placeholder="" v-model="dwtype">
							<option value="0">请选择设备类型</option>
							<option value="1">用传</option>
							<option value="2">水表</option>
							<option value="3">烟感</option>
							<option value="4">消防栓</option>
							<option value="5">液位</option>
							<option value="6">RTU</option>
							<option value="7">电气火灾</option>
							<option value="16">视频监测</option>
						</select>
					</view>
				</view>

				<view class="cu-bar search bg-gray filter-section">
					<view class="search-form round bg-white" style="margin-bottom:26rpx">
						<select name="" id="" placeholder="" v-model="transmission_mode">
							<option value="0">请选择传输方式</option>
							<option value="NB">NB</option>
							<option value="4G">4G</option>
							<option value="Lora">Lora</option>
						</select>
					</view>
					<view class="action">
						<button class="cu-btn bg-blue round" @click="searchList">查询</button>
					</view>
				</view>
			</view>

		</view>
		<!-- 筛选框end -->

		<!-- 设备注册列表start -->
		<block class="">
			<view class="processList deviceRegistList" style="height: calc(100vh - 470rpx);">
				<checkbox-group @change="changeCheckbox">
					<view class="cu-list menu-avatar ">
						<view class=" site-item text-center margin-top" v-if="!this.deviceManage.length&&this.deviceManage==1">暂无数据</view>
						<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''"
							v-for="(item,index) in deviceManage" :key="index" :data-target="'move-box-' + index">
							<view class="cu-form-group margin-top">
								<checkbox :value="String(item.id)" :checked="checkedArr.includes(String(item.id))"
									:class="{'checked':checkedArr.includes(String(item.id))}"></checkbox>
							</view>
							<view class="cu-avatar round lg" style="background-image:url(../../static/device-icon.png)">
							</view>
							<view class="content" @longpress="showDetail(item)">
								<view class="pro-title">
									<view class="cut">{{item.owner_name}}</view>
								</view>
								<view class="pro-des  ">
									<view class="text-cut">
										{{item.unitinfo}}
									</view>
								</view>
								<view class="pro-date ">{{item.install_time}}</view>

								<view class="showDetailEdit" v-if="item.isShow">
									<view @tap="goDeviceEdit(item)">修改设备</view>
									<!-- 	<view @tap="deleteItem2" data-target="DialogModal2" :data-id='item.id'
										:data-index='index'>删除设备</view> -->
								</view>



							</view>
							<view class="nav-right num">
								<view class="text-grey">
									<span class="online" v-if="item.device_state=='在线'">在线</span>
									<span class="offline" v-if="item.device_state==='离线'">离线</span>
									<span class="error" v-if="item.device_state==='故障'">故障</span>
									<text class="icon iconfont margin-right-xs margin-left-lg">&#xe629;</text>
								</view>
							</view>
						</view>
					</view>
				</checkbox-group>
			</view>
		</block>
		<!-- 设备注册列表end -->

		<!-- 分享区域  start-->
		<view class="share grid col-3 ">
			<view class="share-item  text-center">
				<view><text class="icon iconfont margin-xs" style="color:#19A402">&#xe66d;</text></view>
				<view @tap="goDeviceAdd">新增</view>
			</view>
			<view class="share-item  text-center">
				<view><text class="icon iconfont margin-xs" style="color:#FF0303">&#xe66c;</text></view>
				<view @tap="deleteItem" data-target="DialogModal2">删除</view>
			</view>
			<view class="share-item  text-center">
				<view><text class="icon iconfont margin-xs" style="color:#FF642E">&#xe66e;</text></view>
				<view @tap="showModal" data-target="DialogModal">
						导出
				</view>
				<!-- <view @tap="showModal" data-target="DialogModal" v-else>
					<download-excel class="export-excel-wrapper" :data="exportData" :fields="json_fields" header='导出数据'
						name="设备管理数据表.xls">
						导出
					</download-excel>
					
				</view> -->

			</view>
			<view class="checkAll" style="display:inline-block">

				<checkbox-group @change="allChoose" v-if="deviceManage.length">
					<label>
						<checkbox value="all" :class="{'checked':allChecked}" :checked="allChecked?true:false">
						</checkbox> <text class="margin-left-xs">全选</text>
					</label>
				</checkbox-group>
			</view>
		</view>
		<!-- 分享区域  end-->

		<!-- 导出弹框 -->
		<!-- <export-modal :modalName='modalName' @fatherHideModal="hideModal()"></export-modal> -->
		<!-- 导出弹框 end -->

		<!-- 删除弹框 -->
		<view class="cu-modal export-modal" :class="modalName=='DialogModal2'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close"></text>
					</view>
				</view>
				<view class="padding-sm bg-white">
					<image src="../../static/chart3-2.png" style="width:100rpx;height:100rpx"></image>
					<view style="margin:20rpx 0" v-if="checkedArr.length>1">确定删除这些设备吗？</view>
					<view style="margin:20rpx 0" v-else>确定删除该设备吗？</view>
				</view>
				<view class="cu-bar operate bg-white" style="min-height: 100rpx;">
					<view class="action margin-0   " @tap="hideModal">
						取消</view>
					<view class="action margin-0  solid-left text-blue" @tap="openConfirmModal"
						data-target="DialogModal3">确定</view>
				</view>
			</view>
		</view>
		<!-- 删除弹框 end -->

		<!-- 再次确认删除弹框 -->
		<view class="cu-modal export-modal" :class="modalName=='DialogModal3'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close"></text>
					</view>
				</view>
				<view class="padding-sm bg-white">
					<view style="margin:20rpx 0">请输入图片中的验证码</view>
					<valid-code :value.sync="validCode"></valid-code>
				</view>
				<view class="cu-bar operate bg-white" style="min-height: 100rpx;">
					<view class="action margin-0" @tap="hideModal">
						取消</view>
					<view class="action margin-0  solid-left text-blue" @tap="confirmDelete">确定</view>
				</view>
			</view>
		</view>
		<!-- 再次确认删除弹框 end -->
	</view>

</template>

<script>
	import json from '../../data/json.js';
	import validCode from './component/validCode/validCode';
	// import searchArea from './component/searchArea.vue';
	import exportModal from './component/exportModal.vue';

	export default {
		components: {
			validCode,
			// searchArea,
			exportModal
		},
		data() {
			return {
				deviceManage: 0,
				
				json_fields: {
					"单位编号": "company", //常规字段
					"状态": "device_state",
					"设备编号": "owner_code", 
					"设备名称": "owner_name",
					"单元地址": "unitinfo",
					"创建时间": "install_time",
				},

				deviceManage: [],
				validCode: '',

				checkbox: [{
					value: 'A',
					checked: false
				}],

				// deviceManage: json.deviceManage,
				siteListRes: 0,

				type: '0',
				siteListData: [],
				modalName: null,
				listTouchStart: 0,
				listTouchDirection: null,
				CustomBar: this.CustomBar,

				deleteIndex: '',
				deleteId: '',
				dwtype: 0,
				transmission_mode: 0,

				// checkAllFlag:false,

				exportData:[],
				isChecked: false,
				checkedArr: [], //复选框选中的值
				allChecked: false //是否全选
			};
		},


		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		computed: {
			newDeviceManage() {
				return this.deviceManage.map(item => {
					this.$set(item, "isShow", false)
					return item
				})
			}

		},

		mounted() {
			// document.addEventListener('click', (event) => {
			// 	if (event.target.className != 'showDetailEdit') {
			// 		this.deviceManage.forEach(item => {
			// 			item.isShow = false;
			// 		})
			// 	}
			// })
		},
		onLoad: function(option) {
			this.getDataList({
				'company_code': uni.getStorageSync('selectedCode')
			})
		},
		methods: {

			//筛选
			searchList() {
				this.getDataList({
					"transmission_mode": this.transmission_mode,
					"dwtype": this.dwtype,
					'company_code': uni.getStorageSync('selectedCode')
				})
			},

			// 列表数据请求
			async getDataList(params = {}) {
				const res = await this.$myRequest({
					url: 'DeviceConfig/getDeviceList',
					data: params,
					showLoading: true
				})
				this.deviceManage = res.data.data;
				this.deviceManageRes=1;
			},

			// 页面跳转
			goDeviceAdd() {
				uni.navigateTo({
					url: '/pages/deviceManage/deviceAdd/deviceAdd',
				});
			},
			goDeviceEdit(item) {
				uni.navigateTo({
					url: '/pages/deviceManage/deviceEdit/deviceEdit?type=' + item.id + '',
				});
			},
			//导出弹框
			showModal(e) {
				var ua = window.navigator.userAgent.toLowerCase();
				if(ua.match(/MicroMessenger/i) == 'micromessenger'){
					alert('点击右上角 ┇，选择默认浏览器进行导出操作')
				}else{
					if (this.checkedArr.length == 0) {
						alert('请选择至少一条需要导出的数据')
					} else {
						
						this.modalName = e.currentTarget.dataset.target;
						
						this.getDataExport()
					}
				}
				
			},
			getDataExport() {
				const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
				// let exportData = [];
				let newData = [];
				this.exportData = this.deviceManage.filter((item) => this.checkedArr.includes(item.id));
				this.exportData.forEach(function(item, index) {
					newData.push({
						company: item.company,
						device_state: item.device_state,
						owner_code: item.owner_code,
						unitinfo: item.unitinfo,
						owner_name: item.owner_name,
						install_time: item.install_time,
					})
				});
				console.log('newData')
				console.log(newData);
				let str =
					'<tr style="text-align:center"><th>单位编号</th><th>状态</th><th>设备编号</th><th>设备名称</th><th>单位地址</th><th>创建时间</th></tr>';
				// 循环遍历，每行加入tr标签，每个单元格加td标签
				for (let i = 0; i < newData.length; i++) {
					str += '<tr style="text-align:center">';
					for (const key in newData[i]) {
						// 增加\t为了不让表格显示科学计数法或者其他格式
						str += `<td x:str>${ newData[i][key] + '\t'}</td>`;
					}
					str += '</tr>';
				}
				// Worksheet名
				const worksheet = 'Sheet1'
				const uri = 'data:application/vnd.ms-excel;base64,';

				// 下载的表格模板数据
				let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
				          xmlns:x="urn:schemas-microsoft-com:office:excel"
				          xmlns="http://www.w3.org/TR/REC-html40">
				          <head><meta charset='UTF-8'><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
				            <x:Name>${worksheet}</x:Name>
				            <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
				            </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
				            </head><body><table>${str}</table></body></html>`;
				

				// 通过创建a标签实现
				const link = document.createElement("a");
				link.href = uri + base64(template);
				// 对下载的文件命名
				link.download = "设备注册管理数据表.xls";
				link.click();
			},

			//关闭弹框
			hideModal(e) {
				this.modalName = null
			},

			//删除弹出框操作
			deleteItem(e) {

				// uni.showModal({
				// 	showCancel: false,
				// 	content: '暂不支持删除功能'
				// });
				if (this.checkedArr.length == 0) {
					alert('请选择至少一条需要删除的数据')
				} else {
					this.modalName = e.currentTarget.dataset.target;
				}
			},
			deleteItem2(e) {
				this.checkedArr.push(e.target.dataset.id);
				this.deleteIndex = e.target.dataset.index;
				console.log('this.checkedArr  单个点击删除按钮 存入要删除的索引')
				console.log(this.checkedArr)
				this.modalName = e.currentTarget.dataset.target;
			},
			confirmDelete() {
				this.deviceManage = this.deviceManage.filter((item) => !this.checkedArr.includes(item.id));
				console.log('this.deviceManage')
				console.log(this.deviceManage)
				this.modalName = null
			},
			//再次确认弹框
			openConfirmModal(e) {
				this.modalName = e.currentTarget.dataset.target;
			},


			// 隐藏显示
			showDetail(e) {

				console.log(this.deviceManage)
				// console.log('e')
				// console.log(e)
				// 存储点击那一项的状态
				const nowStatu = e.isShow;

				//判断如果长摁弹框出来时，情况选中状态 ？？？
				if (!nowStatu) {
					this.checkedArr = [];
					this.allChecked = false;
				}
				// 将每一项列表的isShow设置为false,让所有的列表都隐藏
				this.deviceManage.forEach(item => {
					item.isShow = false
				})
				// 用于再次点击该项的取反
				e.isShow = !nowStatu
			},


			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},

			// 多选复选框改变事件
			changeCheckbox(e) {
				this.checkedArr = e.detail.value;
				// 如果选择的数组中有值，并且长度等于列表的长度，就是全选
				if (this.checkedArr.length > 0 && this.checkedArr.length == this.newDeviceManage.length) {
					this.allChecked = true;
				} else {
					this.allChecked = false;
				}
			},
			// 全选事件
			allChoose(e) {
				let chooseItem = e.detail.value;
				// 全选
				if (chooseItem[0] == 'all') {
					this.allChecked = true;
					for (let item of this.newDeviceManage) {
						let itemVal = String(item.id);
						if (!this.checkedArr.includes(itemVal)) {
							this.checkedArr.push(itemVal);
						}
					}
				} else {
					// 取消全选
					this.allChecked = false;
					this.checkedArr = [];
				}
			}
		},

	}
</script>

<style>
	.showDetailEdit {
		position: absolute;
		background: #fff;
		box-shadow: 0 1px 6px 0 rgb(32 33 36 / 28%);
		border-radius: 10rpx;
		top: 50rpx;
		right: 47%;
		z-index: 3000000;
		font-size: 28rpx;
	}

	.showDetailEdit view {
		padding: 0rpx 20rpx;
	}

	.showDetailEdit view:first-child {
		border-bottom: 1px solid #EDEDED;
	}
</style>
