<template>
	<view class="container">
		<u-navbar leftIconColor="#fff" titleStyle="color:#fff;fontSize:36rpx;" :autoBack="true" bgColor="#2C6FF3"
			:placeholder="true" title="设备详情">
		</u-navbar>
		<view class="content">
			<view class="xy-card">
				<view class="top">
					<view>
						<view class="t-left">
							<view v-if="detail.deviceName">{{detail.deviceName}}<text
									style="color: #666;font-size: 26rpx;">({{detail.deviceId}})</text></view>
							<view v-else>{{detail.deviceId}}</view>
						</view>

						<view class="flex" style="white-space: nowrap;">
							<view :class="[detail.netStateName=='在线'?'t-right':'t-right off']">
								{{detail.netStateName||'离线'}}
							</view>
							<view :class="[detail.busyState==1?'t-right':'t-right off']">
								{{detail.busyState==1?'运营中':'已停运'}}
							</view>
						</view>

					</view>
					<view style="margin-top: 24rpx;">
						<xbutton size="mini" style="margin-right:12rpx;" bgColor="#fff" borderColor="#2C6FF3"
							color="#2C6FF3" @click="downloadQr">下载柜门二维码</xbutton>
						<xbutton size="mini" @click="btnClick('编辑')">编辑</xbutton>
					</view>
				</view>
				<view :class="[isMore?'center center-more':'center']">
					<view class="d-line">
						<view class="c-item">
							<view class="name">
								编号：
							</view>
							<view class="val">
								{{detail.deviceId||'/'}}
								<text @click="copy(detail.deviceId)" v-if="detail.mercDeviceCode">复制</text>
							</view>
						</view>
						<view class="c-item">
							<view class="name">
								商户：
							</view>
							<view class="val">
								{{detail.mercName||'/'}}
							</view>
						</view>
					</view>
					<view class="d-line">
						<view class="c-item">
							<view class="name">
								温度：
							</view>
							<view class="val">
								{{detail.deviceStatus.tempValue}}℃
							</view>
						</view>
						<view class="c-item">
							<view class="name">
								信号强度：
							</view>
							<view class="val net">
								{{detail.deviceStatus.netDbm||'/'}}d<text
									v-if="detail.deviceStatus.netDbm<-90">(弱)</text>
								<text
									v-else-if="detail.deviceStatus.netDbm>-90&&detail.deviceStatus.netDbm<-40">(中)</text>
								<text
									v-else-if="detail.deviceStatus.netDbm>-40&&detail.deviceStatus.netDbm<0">(强)</text>
								<text v-else-if="detail.deviceStatus.netDbm==0">(无)</text>
							</view>
						</view>
					</view>
					<view class="c-item">
						<view class="name">
							软件版本：
						</view>
						<view class="val">
							{{detail.deviceSysinfo.appUpmVersion||'/'}}
						</view>
					</view>
					<view class="c-item">
						<view class="name">
							最后更新时间：
						</view>
						<view class="val">
							{{detail.updateTime||'/'}}
						</view>
					</view>
					<view class="c-item">
						<view class="name">
							激活状态：
						</view>
						<view class="val" v-if="detail.activeState==1">
							已激活
						</view>
						<view class="val" v-else>
							未激活
						</view>
					</view>
					<view class="c-item">
						<view class="name">
							激活时间：
						</view>
						<view class="val">
							{{detail.activeTime||'/'}}
						</view>
					</view>
					<view class="c-item">
						<view class="name">
							区域：
						</view>
						<view class="val">
							{{detail.districtName||'/'}}
						</view>
					</view>
					<view class="d-line">
						<view class="c-item">
							<view class="name">
								点位：
							</view>
							<view class="val">
								{{detail.placeName||'/'}}
							</view>
						</view>
						<view class="c-item">
							<view class="name">
								线路：
							</view>
							<view class="val">
								{{detail.placeLineName||'/'}}
							</view>
						</view>
					</view>

					<view class="c-item">
						<view class="name">
							设备位置：
						</view>
						<view class="val" @click="showPos" style="width:120rpx;">
							<u-icon slot="right" size="20" name="map"></u-icon>
						</view>
					</view>

					<view class="unfold" @click="isMore=!isMore">
						<u-icon :name="isMore?'arrow-down':'arrow-up'" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="bot">
					<view>
						<button class="cu-btn cu-btn1" style="width:150rpx;" @click="btnClick('设备重启')">设备重启</button>
					</view>
					<view>
						<button class="cu-btn cu-btn2" style="width:140rpx;" @click="btnClick('声音设置')">声音设置</button>
					</view>
					<view>
						<button class="cu-btn cu-btn2" style="width: 140rpx;" @click="btnClick('温度设置')">温度设置</button>
					</view>
					<view>
						<button class="cu-btn cu-btn2" style="width: 140rpx;" @click="btnClick('灯光设置')">灯光设置</button>
					</view>

				</view>
				<view class="bot">
					<view>
						<button class="cu-btn cu-btn2" style="width: 140rpx;" @click="btnClick('清除故障')">清除故障</button>
					</view>
					<view>
						<button class="cu-btn cu-btn3" style="width: 140rpx;"
							@click="btnClick(btnState)">{{btnState}}</button>
					</view>
				</view>
			</view>

			<view class="xy-card" style="width:750rpx;margin-left: -24rpx;border-radius: 0;">
				<u-tabs :list="chartTab" :scrollable="false" @click="tabClick" lineColor="#2C6FF3"></u-tabs>
			</view>
			<view class="xy-card">
				<view class="chart-content">
					<view class="total" v-if="current=='经营数据'">
						<view style="width:200rpx;">
							<u-subsection activeColor="#2C6FF3" :list="totalTab" :current="time" @change="totalChange">
							</u-subsection>
						</view>
						<view class="t-content">
							<view class="t-item">
								<view class="t-name">
									销售额
								</view>
								<view class="t-num">
									￥<text>{{$xy.delMoney(countData.salesMoney)}}</text>
								</view>
							</view>
							<view class="t-item">
								<view class="t-name">
									订单数
								</view>
								<view class="t-num">
									<text>{{countData.salesCount||0}}</text>
								</view>
							</view>
							<view class="t-item">
								<view class="t-name">
									退款
								</view>
								<view class="t-num">
									￥<text>{{$xy.delMoney(countData.refundMoney)}}</text>
								</view>
							</view>
						</view>

						<view class="more-data">
							<xbutton width="140" @click="more">
								销售统计
							</xbutton>
						</view>
					</view>
					<view class="chart" style="height: 600rpx;" v-else>
						<qiun-data-charts canvasId="canvasString" :canvas2d="true" :ontouch="true" type="line"
							:opts="opts" :chartData="chartData" :errorMessage="errorMessage" />
					</view>
				</view>
			</view>

			<view class="xy-card">
				<view class="title">
					商品管理
				</view>
				<view class="t-content">
					<view class="t-item">
						<view class="t-name">
							在售商品种类
						</view>
						<view class="t-num">
							<text>{{goodsManageData.categoryNum||0}}</text>种
						</view>
					</view>
					<view class="t-item">
						<view class="t-name">
							在售库存
						</view>
						<view class="t-num">
							<text>{{goodsManageData.stock||0}}</text>
						</view>
					</view>
					<view class="t-item">
						<view class="t-name">
							上次补货后库存
						</view>
						<view class="t-num">
							<text>{{goodsManageData.afterFillStock||0}}</text>
						</view>
					</view>
				</view>
				<view class="bot bot1">
					<button class="cu-btn cu-btn2" style="width:140rpx;"
						@click="$tab.navigateTo(`/pages/equipment/comManage?id=${id}&deviceName=${detail.deviceName}`)">管理商品</button>
					<button class="cu-btn cu-btn2" style="width: 140rpx;margin:0 12rpx;"
						@click="$tab.navigateTo(`/pages/replenish/replenishmentRecord?id=${id}`)">补货记录</button>
					<button class="cu-btn cu-btn3" style="width: 140rpx;"
						@click="$tab.navigateTo(`/pages/replenish/replenishmentHomePage?id=${id}&&deviceName=${detail.deviceName}`)">补货</button>
				</view>
			</view>

			<xpopup :show="qrcodeShow" mode="center" @close="qrcodeClose" :showBtn="false">
				<view class="qrcode-content flex flex-direction align-center">
					<view class="canvas-box">
						<u--image width="400rpx" height="400rpx" :src="qrCodeImg" mode="aspectFit"
							:lazy-load="true"></u--image>
					</view>
					<view class="save-qrcode" slot="botton">
						<xbutton @click="handleImgSave">保存二维码</xbutton>
					</view>
				</view>
			</xpopup>

			<!-- <view class="xy-card">
				<view class="title">
					在线情况
				</view>
				<scroll-view style="height: 410rpx;" scroll-y>
					<view class="l-content" v-if="netRecords&&netRecords.length>0">
						<view class="l-item" v-for="(item,index) in netRecords" :key="item.id">
							<view class="l-time">
								{{item.createTime}}
							</view>
							<view class="l-status">
								{{item.netStatus}}
							</view>
						</view>
					</view>
					<view class="l-content" v-else>
						<u-empty text="没有记录~"></u-empty>
					</view>
				</scroll-view>
			</view>

			<view class="xy-card">
				<view class="title">
					锁异常记录
				</view>
				<scroll-view style="height: 410rpx;" scroll-y>
					<view class="l-content" v-if="errRecordLock&&errRecordLock.length>0">
						<view class="l-item" v-for="(item,index) in errRecordLock" :key="item.id">
							<view class="l-time">
								{{item.createTime}}
							</view>
							<view class="l-status">
								{{item.errorDescript}}
							</view>
						</view>
					</view>
					<view class="l-content" v-else>
						<u-empty text="设备状态很好,没有异常~"></u-empty>
					</view>
				</scroll-view>
			</view>

			<view class="xy-card">
				<view class="title">
					摄像头故障记录
				</view>
				<scroll-view style="height: 410rpx;" scroll-y>
					<view class="l-content" v-if="errRecordCamera&&errRecordCamera.length>0">
						<view class="l-item" v-for="(item,index) in errRecordCamera" :key="item.id">
							<view class="l-time">
								{{item.createTime}}
							</view>
							<view class="l-status">
								{{item.errorDescript}}
							</view>
						</view>
					</view>
					<view class="l-content" v-else>
						<u-empty text="设备状态很好,没有任何故障~"></u-empty>
					</view>
				</scroll-view>
			</view>

			<view class="xy-card">
				<view class="title">
					温度记录
				</view>
				<scroll-view style="height: 410rpx;" scroll-y>
					<view class="l-content" v-if="deviceTempRecords&&deviceTempRecords.length>0">
						<view class="l-item" v-for="(item,index) in deviceTempRecords" :key="item.id">
							<view class="l-time">
								{{item.createTime}}
							</view>
							<view class="l-status">
								温度为：{{item.tempValue}}
							</view>
						</view>
					</view>
					<view class="l-content" v-else>
						<u-empty text="没有温度信息~"></u-empty>
					</view>
				</scroll-view>
			</view>

			<view class="xy-card">
				<view class="title">
					操作记录
				</view>
				<scroll-view style="height: 410rpx;" scroll-y>
					<view class="l-content" v-if="operaRecords&&operaRecords.length>0">
						<view class="l-item" v-for="(item,index) in operaRecords" :key="item.id">
							<view class="l-time">
								{{item.createTime}}
							</view>
							<view class="l-status">
								{{item.changeBefore}}变更为{{item.changeAfter}}
							</view>
						</view>
					</view>
					<view class="l-content" v-else>
						<u-empty text="没有任何记录~"></u-empty>
					</view>
				</scroll-view>
			</view> -->

			<xpopup :show="show" @close="close" @confirm="submit" :showBtn="true" :title="title">
				<!-- 设备编辑 -->
				<view class="popup-content" v-if="title=='编辑'">
					<u--form labelPosition="left" :model="editForm">
						<u-form-item labelWidth="90" label="名称" prop="name" borderBottom ref="item1">
							<u--input placeholder="设置机器名称" v-model="editForm.name" border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="90" label="区域" prop="areaName" borderBottom ref="item1"
							@click.native="areaChoose">
							<u--input placeholder="设置机器区域" v-model="editForm.areaName" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="90" label="线路" prop="lineName" borderBottom ref="item1"
							@click.native="lineChoose">
							<u--input placeholder="设置机器线路" v-model="editForm.lineName" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="90" label="点位" prop="placeName" borderBottom ref="item1"
							@click.native="placeChoose">
							<u--input placeholder="设置机器点位" v-model="editForm.placeName" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="90" label="位置" prop="lon" borderBottom @click.native="getLocation">
							<u--input placeholder="设置机器位置" readonly v-model="devicePos" border="none"></u--input>
							<u-icon slot="right" size="26" name="map"></u-icon>
						</u-form-item>
					</u--form>
				</view>

				<!-- 设备重启 -->
				<view class="popup-content restart" v-if="title=='设备重启'">
					是否确定重启设备?
				</view>

				<!-- 暂停营业 -->
				<view class="popup-content restart" v-if="title=='暂停营业'||title=='开始营业'">
					是否确定{{btnState}}?
				</view>

				<!-- 声音设置 -->
				<view class="popup-content" v-if="title=='声音设置'">
					<u-slider :showValue="true" min="0" max="25" v-model="voice"></u-slider>
				</view>

				<!-- 温度设置 -->
				<view class="popup-content temp" v-if="title=='温度设置'">
					<view class="flex" style="margin-top: 0;">
						<view class="lab" style="margin-top: -10rpx;">工作模式:</view>
						<u-radio-group v-model="tempDetail.selTempWorkModel" placement="row">
							<u-radio :customStyle="{marginBottom:'16rpx',marginLeft:'16rpx'}"
								v-for="(item, index) in tempWorkModels" :key="index" :label="item.name" :name="item.id">
							</u-radio>
						</u-radio-group>
					</view>
					<view class="flex" style="margin-top: 0rpx; margin-bottom: 20rpx;">
						<view class="lab">工作温度(℃):</view>
						<view style=" margin-left: 20rpx;">
							<u-number-box button-size="30" v-model="tempDetail.targetTemp" class='martop'>
							</u-number-box>
						</view>

					</view>

					<view class="info">时段设置为X点至Y点，结束时间需大于起始时间</view>
					<view class="flex align-center">
						<view class="lab">时段1:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('temp',0)">
							<view class="time-box">
								{{tempDetail.start1}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{tempDetail.end1}}</view>
						</view>
					</view>
					<view class="flex align-center">
						<view class="lab">时段2:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('temp',1)">
							<view class="time-box">
								{{tempDetail.start2}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{tempDetail.end2}}</view>
						</view>
					</view>
					<view class="flex align-center">
						<view class="lab">时段3:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('temp',2)">
							<view class="time-box">
								{{tempDetail.start3}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{tempDetail.end3}}</view>
						</view>
					</view>
					<view style="height: 20rpx;"></view>
				</view>

				<!-- 灯光设置 -->
				<view class="popup-content temp" v-if="title=='灯光设置'">
					<!-- 					<view class="flex" style="margin-top: 0;">
						<view class="lab" style="margin-top: -10rpx;">是否打开:</view>
						<u-switch v-model="lightDetail.open"></u-switch>
					</view> -->

					<view class="info">时段设置为X点至Y点，结束时间需大于起始时间</view>
					<view class="flex align-center">
						<view class="lab">时段1:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('light',0)">
							<view class="time-box">
								{{lightDetail.start1}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{lightDetail.end1}}</view>
						</view>
					</view>
					<view class="flex align-center">
						<view class="lab">时段2:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('light',1)">
							<view class="time-box">
								{{lightDetail.start2}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{lightDetail.end2}}</view>
						</view>
					</view>
					<view class="flex align-center">
						<view class="lab">时段3:</view>
						<view class="flex align-center  date-container marleft"
							style="padding-left: 10rpx; padding-right: 10rpx;" @tap="pickerTimes('light',2)">
							<view class="time-box">
								{{lightDetail.start3}}
							</view>
							<view class="lab to">至</view>
							<view class="time-box">{{lightDetail.end3}}</view>
						</view>
					</view>
					<view style="height: 20rpx;"></view>
				</view>

				<!-- 清除故障 -->
				<view class="popup-content restart" v-if="title=='清除故障'">
					是否确定清除故障?
				</view>
			</xpopup>


			<!-- 区域选择弹框 -->
			<xpopup :show="areaShow" @close="areaClose" :showBtn="false" title="选择区域">
				<!-- 类目选择 -->
				<scroll-view style="height: 600rpx;" scroll-y scroll-with-animation>
					<view class="popup-content">
						<tki-tree style="width:100%;" :range="areaList" :foldAll="false" rangeKey="name" idKey="name"
							buttonName="选中" @btnClick="areaSubmit">
						</tki-tree>
					</view>
				</scroll-view>
			</xpopup>

			<!-- 线路/点位 -->
			<u-picker :show="pickerShow" @confirm="pickerConfirm" :closeOnClickOverlay="true" :columns="columns"
				keyName="label" @close="pickerClose" @cancel="pickerClose"></u-picker>
			<!-- 	温度时间选择 -->
			<u-picker :show="showTimeSelPicker" ref="uPicker" :columns="times" @confirm="pickerTimeConfirm"
				@change="pickerTimeChangeHandler"></u-picker>

		</view>

		<u-back-top :scroll-top="scrollTop" top="400"></u-back-top>
	</view>
</template>

<script>
	import {
		detail,
		dataCount,
		indexDeviceRecords,
		indexDeviceNetRecords,
		indexDeviceTempRecords,
		indexDeviceError,
		modifyBusyStage,
		updateInfo,
		sendCommand,
		queryCommandResult,
		exportQrCode,
		getQrCode,
		abort
	} from "@/api/device/device.js"

	import {
		areaTree
	} from "@/api/point/area"

	import {
		linePage,
		bindDevice
	} from "@/api/point/line"

	import config from '@/config'

	import {
		pointPage
	} from "@/api/point/point"

	import {
		bindDevice as bindDevicePoint
	} from "@/api/point/point"

	import {
		base64DownLoad
	} from '@/utils/download.js'

	export default {
		data() {
			return {
				opts: {
					padding: [15, 10, 0, 15],
					dataLabel: false,
					color: ['#2D54EC', '#F49B37'],
					// 开启图表可拖拽滚动
					// enableScroll: true,
					dataPointShape: false, //是否显示折线上的点
					xAxis: {
						// 开启图表可拖拽滚动后 必配置（显示多少个）
						// itemCount: 8,
						rotateLabel: true,
						labelCount: 10,
						marginTop: 10,
					},
					yAxis: {
						splitNumber: 5,
						gridType: "dash",
						dashLength: 8,
						gridColor: "rgba(0, 0, 0, 0.15)",
						data: [{
							axisLine: false, //坐标轴轴线是否显示
						}]
					},
					extra: {
						column: {
							width: 15,
							seriesGap: 2,
							barBorderRadius: [10, 10, 10, 10],
						},
						line: {
							type: "curve",
							width: 2,
							activeType: "hollow",
							linearType: "custom",
							onShadow: true,
							animation: "horizontal"
						},
					}
				},
				current: '经营数据',
				chartTab: [{
						name: '经营数据'
					},
					{
						name: '经营图表'
					},
					{
						name: '温度图表'
					},
					{
						name: '信号图表'
					}
				],
				chartData: {
					series: [],
					categories: []
				},
				errorMessage: '无数据',

				tempDetail: {
					targetTemp: 4,
					selTempWorkModel: 2,
					start1: 0,
					end1: 0,
					start2: 0,
					end2: 0,
					start3: 0,
					end3: 0,
					curTimes: 0
				},

				tempWorkModels: [{
					name: '制热',
					id: 1
				}, {
					name: '制冷',
					id: 2
				}, {
					name: '恒温',
					id: 3
				}, {
					name: '关闭',
					id: 4
				}],
				showTimeSelPicker: false,
				timeSelPickerType: undefined,
				times: [
					[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
					[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
				],
				lightDetail: {
					open: true,
					start1: 0,
					end1: 0,
					start2: 0,
					end2: 0,
					start3: 0,
					end3: 0,
					curTimes: 0
				},
				totalTab: ['今日', '本月'],
				time: 0,
				show: false,
				popupTitle: '编辑商品',

				editForm: {
					name: null,
					areaName: null,
					areaId: null,
					lineId: null,
					placeId: null,
					lineName: null,
					placeName: null,
					lon: null,
					lat: null,
					pos: null
				},
				editRules: {
					'code': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
				},

				title: '', //弹框标题
				voice: 4, //声音设置
				light: 50, //灯光设置
				id: null, //设备id
				detail: {}, //设备详情

				allCountData: {}, //经营统计数据显示

				scrollTop: 0, //滚动距离顶部

				operaRecordsFlag: false, //操作记录
				netRecordsFlag: false, //在线情况
				errRecordCameraFlag: false, //摄像头故障情况
				errRecordLockFlag: false, //锁故障数据情况
				tempRecordsFlag: false, //温度数据情况

				operaRecords: [], //设备操作记录
				netRecords: [], //在线情况记录
				errRecordLock: [], //锁故障数据
				errRecordCamera: [], //摄像头故障数据
				deviceTempRecords: [], //温度记录

				isMore: true,

				// 编辑弹框
				areaShow: false,
				pickerShow: false,

				areaList: [], //区域数据

				columns: [], //picker数据

				pickerType: 1, //1线路2点位

				goodsManageData: {
					categoryNum: 0,
					stock: 0,
					afterFillStock: 0
				},

				countData: {
					salesMoney: 0,
					salesCount: 0,
					refundMoney: 0
				},

				pointColumns: [],
				lineColumns: [],

				qrcodeShow: false,
				qrCodeImg: null
			}
		},

		computed: {
			btnState() {
				let str = this.detail.busyState == 1 ? '暂停营业' : '开始营业';
				return str
			},

			devicePos() {
				let pos = '';
				if (this.editForm.lat || this.editForm.lon) {
					pos = this.editForm.lat + ',' + this.editForm.lon
				}
				return pos
			}
		},

		async onLoad(o) {
			if (o.id) {
				this.id = o.id;

				//设备详情
				this.getDetail()

				// 经营数据
				this.allCountData = await this.getCountData(1)
				this.countData = this.allCountData.dayBusinessData;

				//商品管理数据
				let tempData = await this.getCountData(5)
				this.goodsManageData = tempData.goodsData;
			}
		},

		methods: {
			// 获取设备详情
			getDetail() {
				detail({
					deviceId: this.id,
					isSysinfo: true,
					isStatus: true,
					isRegister: true
				}).then(res => {
					this.detail = res.data
				})
			},

			//获取统计数据
			getCountData(type) {
				return new Promise((resolve, reject) => {
					dataCount({
							deviceId: this.id,
							type: type
						}).then(res => {
							resolve(res.data)
						})
						.catch(err => {
							reject(err)
						})
				})
			},

			// 下载柜门二维码
			downloadQr() {
				this.qrcodeShow = true;
				this.drawQr(this.id)
			},

			//绘制二维码
			drawQr(id) {
				getQrCode({
					deviceId: id
				}).then(res => {
					this.qrCodeImg = res.data
				})
			},

			qrcodeClose() {
				this.qrcodeShow = false;
			},

			// 保存图片
			handleImgSave() {
				base64DownLoad(this.qrCodeImg).then(res=>{
					this.qrcodeClose()
					uni.showToast({
						title: '保存成功！',
						icon: "none",
						duration: 3000
					})
				}).catch(err=>{
					this.qrcodeClose()
				})
			},

			// 复制文字
			copy(e) {
				uni.setClipboardData({
					data: e
				});
			},

			// tab切换
			async tabClick(e) {
				console.log(e)
				this.current = e.name
				if (e.name == '经营数据') {
					this.allCountData = await this.getCountData(1)
				} else if (e.name == '经营图表') {
					let tempChartData = {};
					let data = await this.getCountData(2)
					tempChartData.series = data.businessChart ? data.businessChart.series : []
					tempChartData.categories = data.businessChart ? data.businessChart.categories : []
					this.chartData = JSON.parse(JSON.stringify(tempChartData))
				} else if (e.name == '温度图表') {
					let tempChartData = {};
					let data = await this.getCountData(3)
					tempChartData.series = data.temperatureChart ? data.temperatureChart.series : []
					tempChartData.categories = data.temperatureChart ? data.temperatureChart.categories : []
					this.chartData = JSON.parse(JSON.stringify(tempChartData))
				} else if (e.name == '信号图表') {
					let tempChartData = {};
					let data = await this.getCountData(4)
					tempChartData.series = data.signalChart ? data.signalChart.series : []
					tempChartData.categories = data.signalChart ? data.signalChart.categories : []
					this.chartData = JSON.parse(JSON.stringify(tempChartData))
				}
			},

			// 今日/本月切换
			totalChange(e) {
				this.time = e
				if (this.time == 0) { //今日
					this.countData = this.allCountData.dayBusinessData
				} else { //今月
					this.countData = this.allCountData.monthBusinessData
				}
			},

			//销量更多数据
			more() {
				let deviceName = this.detail.deviceName ? this.detail.deviceName : this.detail.deviceId
				this.$tab.navigateTo(`/pages/equipment/statistics?title=${deviceName}&id=${this.id}`)
			},

			// 显示弹框
			async btnClick(e) {
				this.title = e
				this.show = true;
				if (this.title == '编辑') {
					// 加载区域数据
					this.getAreaTree()
					//数据反显
					this.editForm = {
						name: this.detail.deviceName,
						areaName: this.detail.districtName,
						areaId: this.detail.districtId,
						lineId: this.detail.placeLineId,
						placeId: this.detail.placeId,
						lineName: this.detail.placeLineName,
						placeName: this.detail.placeName,
						lon: this.detail.lon,
						lat: this.detail.lat,
					}
				} else if (this.title == '设备重启') {

				} else if (this.title == '声音设置') {

				} else if (this.title == '灯光设置') {

				} else if (this.title == '清除故障') {

				} else { //暂停营业

				}
			},

			// 关闭弹框
			close(e) {
				this.show = false
			},

			// 弹框确定
			async submit() {

				let templet = null;
				let reSn = null;
				if (this.title == '编辑') {
					// if (this.editForm.areaName && this.editForm.lineId) {
					// 	await this.lineBind() //绑定线路
					// 	if (this.editForm.placeId) { //绑定点位
					// 		await this.placeBind()
					// 	}
					// 	this.getDetail()
					// } else {
					// 	this.$modal.msg('请选择区域和线路~')
					// }
					await this.updateDevice()
					this.getDetail()
				} else if (this.title == '设备重启') {
					await this.getDict('mqtt_cmd_templet_task', 'appTask').then(res => {
						console.log(res);
						templet = JSON.parse(res[0].value);
						templet.data.task = "restart";
						templet.data.appId = undefined;
						templet.data.src = undefined;
					});
					await sendCommand([{
						deviceId: this.id,
						templet: templet
					}]).then(res => {
						this.$modal.showToast('重启成功~')
						reSn = res.data[0].v1;
					});
				} else if (this.title == '声音设置') {
					await this.getDict('mqtt_cmd_templet_sets', 'deviceVoice').then(res => {
						console.log(res);
						templet = JSON.parse(res[0].value);
						templet.data.alound = this.voice;
					});
					await sendCommand([{
						deviceId: this.id,
						templet: templet
					}]).then(res => {
						reSn = res.data[0].v1;
					});
				} else if (this.title == '灯光设置') {
					await this.getDict('mqtt_cmd_templet_sets', 'light').then(res => {

						templet = JSON.parse(res[0].value);
						templet.data.light0.start1 = this.lightDetail.start1;
						templet.data.light0.end1 = this.lightDetail.end1;

						templet.data.light0.start2 = this.lightDetail.start2;
						templet.data.light0.end2 = this.lightDetail.end2;

						templet.data.light0.start3 = this.lightDetail.start3;
						templet.data.light0.end3 = this.lightDetail.end3;

					});
					console.log(this.id, templet);
					sendCommand([{
						deviceId: this.id,
						templet: templet
					}]).then(res => {
						reSn = res.data[0].v1;
					});
				} else if (this.title == '温度设置') {
					if (this.vilidateParams()) return //参数校验

					await this.getDict('mqtt_cmd_templet_sets', 'temperature').then(res => {

						templet = JSON.parse(res[0].value);
						templet.data.workModel = this.tempDetail.selTempWorkModel;
						templet.data.target = this.tempDetail.targetTemp;
						templet.data.start1 = this.tempDetail.start1;
						templet.data.end1 = this.tempDetail.end1;

						templet.data.start2 = this.tempDetail.start2;
						templet.data.end2 = this.tempDetail.end2;

						templet.data.start3 = this.tempDetail.start3;
						templet.data.end3 = this.tempDetail.end3;

					});
					console.log(this.id, templet);
					sendCommand([{
						deviceId: this.id,
						templet: templet
					}]).then(res => {
						reSn = res.data[0].v1;
					});
				} else if (this.title == '清除故障') {
					this.abort()
				} else { //暂停营业
					this.changeState()
				}
				this.close()
			},

			vilidateParams() {
				if (this.tempDetail.start1 > this.tempDetail.end1 || this.tempDetail.start2 > this.tempDetail.end2 ||
					this
					.tempDetail.start2 > this.tempDetail.end2) {
					this.$modal.msg('结束时间需大于等于起始时间！')
					return true
				} else {
					return false
				}
			},

			abort() {
				abort({
					deviceId: Number(this.id),
				}).then(res => {
					this.$modal.msg('清除故障成功~')
				});
			},

			//修改设备信息
			updateDevice() {
				let params = {
					deviceId: Number(this.id),
					deviceName: this.editForm.name,
					districtId: this.editForm.areaId,
					placeLineId: this.editForm.lineId,
					placeId: this.editForm.placeId,
					lon: this.editForm.lon,
					lat: this.editForm.lat
				}
				return new Promise((resolve, reject) => {
					updateInfo(params).then(res => {
						this.$modal.msg('修改成功~')
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			// 线路绑定设备
			lineBind() {
				return new Promise((resolve, reject) => {
					bindDevice({
						isBind: true,
						deviceIds: [this.id],
						id: this.editForm.lineId
					}).then(res => {
						this.$modal.msg('绑定线路成功~')
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			// 点位绑定设备
			placeBind() {
				return new Promise((resolve, reject) => {
					bindDevicePoint({
						isBind: true,
						deviceIds: [this.id],
						id: this.editForm.placeId
					}).then(res => {
						this.$modal.msg('绑定点位成功~')
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			changeState() {
				let busyState = this.detail.busyState == 1 ? 2 : 1
				modifyBusyStage({
					deviceId: this.id,
					busyState: busyState
				}).then(async res => {
					if (res.code == 200) {
						this.$modal.msg('操作成功~')
						this.detail.busyState = busyState;
						let templet = '';
						await this.getDict('mqtt_cmd_templet_sets', 'lockDevice').then(res => {
							console.log(res);
							templet = JSON.parse(res[0].value);
							templet.data.id = 0;
							templet.data.opt = (busyState == 1 ? 'unlock' : 'lock');
						});
						await sendCommand([{
							deviceId: this.id,
							templet: templet
						}]).then(res => {
							//reSn = res.data[0].v1;
						});
					} else {
						this.$modal.msg('操作失败,请重试~')
					}
				})
			},

			// 获取设备操作记录
			getDeviceRecords() {
				this.operaRecordsFlag = true;
				indexDeviceRecords({
					deviceId: this.id
				}).then(res => {
					this.operaRecords = res.data
				})
			},

			//获取设备联网记录
			getDeviceNetRecords() {
				this.netRecordsFlag = true;
				indexDeviceNetRecords({
					deviceId: this.id
				}).then(res => {
					this.deviceNetRecords = res.data;
				})
			},

			//获取设备温度记录
			getDeviceTempRecords() {
				this.tempRecordsFlag = true;
				indexDeviceTempRecords({
					deviceId: this.id
				}).then(res => {
					this.deviceTempRecords = res.data;
				})
			},

			//获取故障记录
			getDeviceErrRecords(type) {
				switch (type) {
					case 2:
						this.errRecordLockFlag = true;
						break
					case 5:
						this.errRecordCameraFlag = true;
						break
					default:
						break
				}
				indexDeviceError({
					deviceId: this.id,
					errorType: type
				}).then(res => {
					switch (type) {
						case 2:
							this.errRecordLock = res.data;
							break
						case 5:
							this.errRecordCamera = res.data;
							break
						default:
							break
					}
				})
			},

			// onPageScroll(e) {
			// 	this.scrollTop = e.scrollTop;
			// 	if (this.scrollTop > 140 && !this.netRecordsFlag) { //联网记录
			// 		this.getDeviceNetRecords()
			// 	}

			// 	if (this.scrollTop > 400 && !this.errRecordLockFlag) { //门锁故障情况 2
			// 		this.getDeviceErrRecords(2)
			// 	}

			// 	if (this.scrollTop > 660 && !this.errRecordCameraFlag) { //摄像头故障情况 5
			// 		this.getDeviceErrRecords(5)
			// 	}

			// 	if (this.scrollTop > 850 && !this.tempRecordsFlag) { //操作记录
			// 		this.getDeviceTempRecords()
			// 	}

			// 	if (this.scrollTop > 1110 && !this.operaRecordsFlag) { //操作记录
			// 		this.getDeviceRecords()
			// 	}
			// },

			//获取区域树
			getAreaTree() {
				areaTree().then(res => {
					this.areaList = res.data
				})
			},

			//获取线路options
			getLineOption(regionName) {
				linePage({
					page: {
						current: 1,
						size: 1000,
					},
					regionName: regionName
				}).then(res => {
					let data = res.data.records;
					let newData = data.map(i => {
						return {
							id: i.id,
							label: i.lineName
						}
					})
					this.lineColumns = [newData];
				})
			},

			//获取点位分页
			getPointList(lineId) {
				pointPage({
					page: {
						current: 1,
						size: 1000,
					},
					lineId: lineId
				}).then(res => {
					let data = res.data.records;
					let newData = data.map(i => {
						return {
							id: i.id,
							label: i.placeName
						}
					})
					this.pointColumns = [newData];
				})
			},

			//区域选择
			areaChoose() {
				this.areaShow = true
			},

			areaClose() {
				this.areaShow = false
			},

			//区域选择提交
			areaSubmit(res) {
				this.editForm.areaName = res.name;
				this.editForm.areaId = res.key;
				console.log(res)
				this.getLineOption(res.name)
				this.areaClose()

				//清空线路，点位信息
				this.editForm.lineId = null
				this.editForm.lineName = null
				this.editForm.placeId = null
				this.editForm.placeName = null
			},

			//线路选择
			lineChoose() {
				this.columns = this.lineColumns;
				this.pickerType = 1

				if (this.columns && this.columns.length > 0 && this.columns[0].length > 0) {
					this.pickerShow = true
				} else {
					this.$modal.msg('当前无线路~')
				}
			},

			//点位选择
			placeChoose() {
				this.columns = this.pointColumns;
				this.pickerType = 2
				if (this.columns && this.columns.length > 0 && this.columns[0].length > 0) {
					this.pickerShow = true
				} else {
					this.$modal.msg('当前无点位~')
				}
			},

			getLocation() {
				uni.chooseLocation({
					success: (res) => {
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
						this.editForm.lat = res.latitude;
						this.editForm.lon = res.longitude;
					}
				})
			},

			showPos() {
				if (this.detail.lat && this.detail.lon) {
					uni.openLocation({ //​使用微信内置地图查看位置。
						latitude: Number(this.detail.lat), //要去的纬度-地址 
						longitude: Number(this.detail.lon), //要去的经度-地址
						success: res => {
							console.log('success');
						}
					})
				} else {
					this.$modal.msg('请先编辑设备位置信息~')
				}
			},

			//picker弹框确认
			pickerConfirm(e) {
				if (e.value[0]) {
					if (this.pickerType == 1) { //线路
						this.editForm.lineId = e.value[0].id
						this.editForm.lineName = e.value[0].label
						this.getPointList(e.value[0].id)

						//清空点位信息
						this.editForm.placeId = null
						this.editForm.placeName = null
					} else { //点位
						this.editForm.placeId = e.value[0].id
						this.editForm.placeName = e.value[0].label
					}
				}
				this.pickerClose()
			},

			pickerClose() {
				this.pickerShow = false
			},

			pickerTimes(type, o) {
				this.timeSelPickerType = type;
				this.showTimeSelPicker = true;
				if (this.timeSelPickerType === 'light') {
					this.lightDetail.curTimes = o;
				} else if (this.timeSelPickerType === 'temp') {
					this.tempDetail.curTimes = o;
				}
			},
			pickerTimeChangeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e

				//picker.setColumnValues(0, this.times[0][0])
				// picker.setColumnValues(1,  this.times[1][0])
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				//    if (columnIndex === 0) {
				//            // picker为选择器this实例，变化第二列对应的选项
				// 	var col1 = values.slice(index,23)
				//        picker.setColumnValues(1, values.slice(index,23))

				//    }
			},
			pickerTimeConfirm(e) {
				console.log('confirm', this.timeSelPickerType, e.value[0])
				this.showTimeSelPicker = false
				if (this.timeSelPickerType === 'light') {
					if (0 == this.lightDetail.curTimes) {
						this.lightDetail.start1 = e.value[0];
						this.lightDetail.end1 = e.value[1];
					} else if (1 == this.lightDetail.curTimes) {
						this.lightDetail.start2 = e.value[0];
						this.lightDetail.end2 = e.value[1];
					} else {
						this.lightDetail.start3 = e.value[0];
						this.lightDetail.end3 = e.value[1];
					}
				} else if (this.timeSelPickerType === 'temp') {
					if (0 == this.tempDetail.curTimes) {
						this.tempDetail.start1 = e.value[0];
						this.tempDetail.end1 = e.value[1];
					} else if (1 == this.tempDetail.curTimes) {
						this.tempDetail.start2 = e.value[0];
						this.tempDetail.end2 = e.value[1];
					} else {
						this.tempDetail.start3 = e.value[0];
						this.tempDetail.end3 = e.value[1];
					}
				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		.content {
			padding: 24rpx;

			.xy-card {
				margin-bottom: 24rpx;
			}

			.top {

				>view:nth-child(1) {
					display: flex;
					flex-flow: row nowrap;
					justify-content: space-between;

					.t-left {
						width: 380rpx;

						>view:nth-child(1) {
							font-size: 36rpx;
							font-weight: bold;
						}

						>view:nth-child(2) {
							font-size: 26rpx;
							color: #2C6FF3;
							border: 1rpx solid #2C6FF3;
							border-radius: 6rpx;
							padding: 0 8rpx;
							background-color: rgb(243, 249, 525);
							margin-left: 12rpx;
						}
					}

					.t-right {
						font-size: 30rpx;
						color: #f56c6c;
						position: relative;
						margin-left: 24rpx;

						&::before {
							content: '';
							display: inline-block;
							background-color: green;
							width: 16rpx;
							height: 16rpx;
							border-radius: 16rpx;
							margin-right: 12rpx;
						}

						&.off {
							color: #666;

							&::before {
								background-color: #666;
							}
						}
					}
				}

				>view:nth-child(2) {
					display: flex;
					flex-direction: row;
					justify-content: flex-end;
					margin-top: 12rpx;

					>.cu-btn {
						height: 40rpx;
					}

					.down-qr {
						font-size: 26rpx;
						color: #2C6FF3;
						border: 1rpx solid #2C6FF3;
						border-radius: 6rpx;
						padding: 4rpx 8rpx;
						background-color: rgb(243, 249, 525);
					}

					.edit {
						font-size: 26rpx;
						color: #fff;
						border: 1rpx solid #2C6FF3;
						border-radius: 6rpx;
						padding: 4rpx 8rpx;
						background-color: rgb(243, 249, 525);
						margin-left: 12rpx;
						background-color: #2C6FF3;
					}
				}
			}

			.center {
				border-radius: 8rpx;
				background-color: rgb(245, 248, 251);
				padding: 24rpx 12rpx 42rpx;
				font-size: 30rpx;
				margin-top: 24rpx;
				overflow: hidden;
				position: relative;
				height: 560rpx;
				transition: all 0.5s ease 0s;

				.unfold {
					position: absolute;
					bottom: 8rpx;
					right: 24rpx;
				}

				&.center-more {
					height: 170rpx;
				}

				.d-line {
					display: flex;
					flex-flow: row nowrap;
					justify-content: flex-start;

					>view:nth-child(1) {
						width: 50%;
					}

					>view:nth-child(2) {
						width: 50%;
					}
				}

				.c-item {
					display: flex;
					flex-flow: row nowrap;
					justify-content: flex-start;
					font-size: 28rpx;
					margin-bottom: 18rpx;
					align-items: flex-end;

					.name {
						min-width: 100rpx;
						color: #999;
					}

					.val {
						color: #333;
						padding-left: 6rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						text {
							margin-left: 12rpx;
							text-decoration: underline;
							color: #2C6FF3;
						}

						&.net {
							text {
								text-decoration: none;
							}
						}
					}
				}


			}

			.bot {
				display: flex;
				flex-flow: row nowrap;
				justify-content: space-between;
				margin-top: 24rpx;

				.cu-btn {
					padding: 0 12rpx;
					font-size: 26rpx;
					height: 60rpx;
					line-height: 50rpx;
				}

				.cu-btn1 {
					background-color: red;
					color: #fff;
				}

				.cu-btn2 {
					background-color: #fff;
					color: #2C6FF3;
					border: 1rpx solid #2C6FF3;
				}

				.cu-btn3 {
					background-color: #2C6FF3;
					color: #fff;
				}
			}

			.qrcode-content {
				padding: 24rpx;

				.save-qrcode {
					margin-top: 24rpx;
				}
			}

			.chart-content {
				width: 100%;

				.total {
					display: flex;
					flex-direction: column;
					align-items: center;
				}

				.more {
					background-color: #2C6FF3;
					padding: 0 24rpx;
					font-size: 26rpx;
					height: 50rpx;
					line-height: 50rpx;
					margin-top: 24rpx;
				}
			}

			.t-content {
				display: flex;
				flex-flow: row nowrap;
				width: 100%;
				box-sizing: border-box;
				text-align: center;

				.t-item {
					width: 50%;
					margin-top: 24rpx;

					.t-name {
						font-size: 28rpx;
						line-height: 40rpx;
					}

					.t-num {
						font-size: 28rpx;
						line-height: 46rpx;
						padding: 12rpx 0;

						text {
							font-size: 40rpx;
							font-weight: bold;
						}
					}
				}
			}

			.title {
				font-size: 34rpx;
				font-weight: bold;
				color: #333;
				line-height: 54rpx;

			}

			.bot1 {
				display: flex;
				justify-content: flex-end;
			}

			.l-content {
				padding-top: 24rpx;

				.l-item {
					font-size: 28rpx;
					line-height: 50rpx;
					display: flex;
					flex-direction: row;

					.l-status {
						margin-left: 24rpx;
					}
				}
			}

			.popup-content {
				padding: 0 24rpx;
			}

			.restart {
				padding: 40rpx 0;
				font-size: 34rpx;
				text-align: center;
			}
		}
	}

	.temp {
		.info {
			color: red;
			height: 60rpx;
			line-height: 60rpx;
			text-align: center;
		}

		.flex {
			margin-top: 20rpx;
			height: 60rpx;

			.lab {
				line-height: 60rpx;
				height: 60rpx;
				text-align: center;
				font-weight: 600;
				margin-top: 20rpx;
			}

			.to {
				width: 60rpx;
				margin-left: 20rpx;
				margin-top: 0;
				font-weight: 500;
			}

			.time-box {
				height: 50rpx;
				width: 200rpx;
				line-height: 50rpx;
				margin-left: 20rpx;
				text-align: center;
				border-radius: 10rpx;
				border-style: solid;
				border-width: 1px;
			}
		}
	}
</style>