<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>测报系统</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/index/cbd' }">虫情测报</el-breadcrumb-item>
			<el-breadcrumb-item>数据详情</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="equipInfo">
			<div class="equipMsg">
				<span>设备ID：{{this.$route.params.e_id}}</span>
				<span>设备名称：{{equipStatus.device_name || '无'}}</span>
				<span>位置：{{equipStatus.address || "无"}}</span>
			</div>
			<DateSearch @dateChange="dateChange"></DateSearch>
		</div>
		<div class="ctrl-check">
			<el-button type="primary" size="mini" @click="refresh">刷新</el-button>
			<el-button type="primary" size="mini" @click="lookSIMCode('sim')">SIM 卡</el-button>
		</div>
		<!-- 统计图 -->
		<el-row :gutter="10">
			<el-col :md="24" :lg="15">
				<el-card class="box-card">
					<div class="charts">
						<template v-if="Object.keys(options).length>0">
							<highcharts :options="options"></highcharts>
						</template>
						<template v-else>
							<div style="text-align:center;font-size:20px;line-height:450px">暂无数据</div>
						</template>
					</div>
				</el-card>
			</el-col>
			<el-col :md="24" :lg="9">
				<el-card class="box-card">
					<el-row :gutter="10">
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon1.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.device_status?"在线":"离线"}}</strong>
									<p>在线状态</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon2.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.ts?"时控":"光控"}}</strong>
									<p>定时模式</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon3.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.gs?"落虫":"排水"}}</strong>
									<p>通道状态</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon4.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.hs?"加热":"正常"}}</strong>
									<p>加热状态</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon5.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.upds?"打开":"关闭"}}</strong>
									<p>上仓门</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon6.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.dpds?"打开":"关闭"}}</strong>
									<p>下仓门</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon7.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.csq}}</strong>
									<p>信号强度</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon8.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.dver}}</strong>
									<p>设备版本</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon9.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.tph}}</strong>
									<p>高温限值</p>
								</div>
							</div>
						</el-col>
						<el-col :xs="12" :sm="12" :md="6" :lg="12">
							<div class="equipStatus">
								<div class="equipIcon">
									<img src="@/assets/images/forecasting/cbd/staticIcon10.png" alt />
								</div>
								<div class="equipParams">
									<strong>{{equipStatus.tpl}}</strong>
									<p>低温限值</p>
								</div>
							</div>
						</el-col>
					</el-row>
				</el-card>
			</el-col>
		</el-row>
		<div class="dataTableSearch">
			<div>
				<el-button type="primary" size="mini">导出</el-button>
			</div>
		</div>
		<el-card class="box-card" v-if="showControl">
			<el-table :data="tableData" stripe style="width: 100%">
				<el-table-column
					v-for="(item,index) in tableHeadTxt"
					:key="index"
					:prop="item[1]"
					:label="item[0]"
				>
					<template slot-scope="scope">{{scope.row[scope.column.property]}}</template>
				</el-table-column>
			</el-table>
			<el-pagination
				background
				layout="prev, pager, next"
				:total="total"
				:current-page="queryInfo.page"
				@current-change="changePage"
			></el-pagination>
		</el-card>
		<!-- SIM卡对话框 -->
		<el-dialog title="SIM卡"  :visible.sync="simCodeVisible" width="30%">
			<template>
				<el-tabs v-loading="simLoading" element-loading-text="数据请求中" v-model="activeName" @tab-click="handleClick">
					<el-tab-pane label="SIM卡流量" name="sim">
						<div class="simCodeBox">
							<div>
								<span class="simCodeTitle">ICCID：</span>
								<div>{{sim.iccid}}</div>
							</div>
							<div>
								<span class="simCodeTitle">状态：</span>
								<div>{{sim.account_status | simStatus}}</div>
							</div>
							<div>
								<span class="simCodeTitle">套餐：</span>
								<div>
									<el-progress :show-text="false" :percentage="100"></el-progress>
								</div>
								<span>{{sim.data_plan}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">已用流量：</span>
								<div>
									<template v-if="!isNaN(data_usage_Per)">
										<el-progress :show-text="false" :percentage="data_usage_Per"></el-progress>
									</template>
								</div>
								<span>{{sim.data_usage}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">剩余流量：</span>
								<div>
									<template v-if="!isNaN(data_balance_per)">
										<el-progress :show-text="false" :percentage="data_balance_per"></el-progress>
									</template>
								</div>
								<span>{{sim.data_balance}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">到期时间：</span>
								<div>{{sim.expiry_date*1000 | formatTime}}</div>
							</div>
							<div class="operateBtn">
								<el-button size="mini" @click="simCodeVisible=false">关闭</el-button>
							</div>
						</div>
					</el-tab-pane>
					<el-tab-pane label="海康SIM卡流量" name="hksim" v-if="showHksimFlag">
						<div class="simCodeBox">
							<div>
								<span class="simCodeTitle">ICCID：</span>
								<div>{{hksim.iccid}}</div>
							</div>
							<div>
								<span class="simCodeTitle">状态：</span>
								<div>{{hksim.account_status | simStatus}}</div>
							</div>
							<div>
								<span class="simCodeTitle">套餐：</span>
								<div>
									<el-progress :show-text="false" :percentage="100"></el-progress>
								</div>
								<span>{{hksim.data_plan}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">已用流量：</span>
								<div>
									<template v-if="!isNaN(hkdata_usage_Per)">
										<el-progress :show-text="false" :percentage="hkdata_usage_Per"></el-progress>
									</template>
								</div>
								<span>{{hksim.data_usage}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">剩余流量：</span>
								<div>
									<template v-if="!isNaN(hkdata_balance_per)">
										<el-progress :show-text="false" :percentage="hkdata_balance_per"></el-progress>
									</template>
								</div>
								<span>{{hksim.data_balance}}MB</span>
							</div>
							<div>
								<span class="simCodeTitle">到期时间：</span>
								<div>{{hksim.expiry_date*1000 | formatTime}}</div>
							</div>
							<div>
								<span class="simCodeTitle">更换ICCID：</span>
								<div>
									<el-input type="number" v-model="hksiminp" placeholder="请输入ICCID"></el-input>
								</div>
							</div>
							<div class="operateBtn">
								<el-button type="primary" size="mini" @click="changeHkSim">确定</el-button>
								<el-button size="mini" @click="simCodeVisible=false">取消</el-button>
							</div>
						</div>
					</el-tab-pane>
				</el-tabs>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import DateSearch from '@/components/DateSearch'
export default {
	data() {
		return {
			// 请求sim卡获取到需要回显的数据
			simLoading:true, //sim卡加载loading
			showHksimFlag:true, //是否显示hksim卡标识
			simCodeVisible: false,
			simFlag:true, //是否重复加载hksim卡
			sim: {
				iccid: '',
				account_status: 0, //卡状态 0-7 未知 测试期 沉默期 使用中 停机 停机保号 预销号 销号
				data_plan: 0, //套餐大小
				data_usage: 0, //当月用量
				data_balance: 0, //剩余流量
				expiry_date: 0 //到期日期
			},
			hksimFlag:true, //是否重复加载hksim卡
			hksim: {
				iccid: '',
				account_status: 0, //卡状态 0-7 未知 测试期 沉默期 使用中 停机 停机保号 预销号 销号
				data_plan: 0, //套餐大小
				data_usage: 0, //当月用量
				data_balance: 0, //剩余流量
				expiry_date: 0 //到期日期
			},
			hksiminp:'',
			timeRange: '', //时间范围picker
			btnSelected: null, //时间按钮高亮
			dataList: [], //所有数据
			options: {},
			// 状态信息
			equipStatus: {},
			// 统计图表信息
			equipChartData: [],
			//总数据条数
			total: 0,
			// 动态表头
			tableHeadTxt: [
				['环境温度(°C)', 'at'],
				['环境湿度(%)', 'ah'],
				['加热仓温度(°C)', 'hrt'],
				['雨控状态', 'rps'],
				['温控状态', 'tps'],
				['光控状态', 'lps'],
				['灯管状态', 'blbs'],
				['信号强度', 'csq'],
				['上报时间', 'addtime']
			],
			// 表格数据
			tableData: [],
			timeRange: '',
			queryInfo: {
				begin: '',
				end: '',
				e_id: this.$route.params.e_id,
				d_id: this.$route.params.d_id,
				page: 1
			},
			//图表实时否有数据
			isEchartData: true,
			//表格和图表按钮样式切换参数
			display: '0', //0代表表格、1代表图表
			// 表格和图表显示切换控制
			showControl: true,
			//echarts图表参数
			echartOptions: [],
			// 动态表头
			tableHead: [],
			// 表格数据
			hisData: [],
			simCodeDialogVisible: false,
			f_id: '',
			// sim卡切换状态
			activeName: 'sim'
		}
	},
	filters: {
		simStatus(val) {
			switch (val) {
				case 0:
					return '未知'
				case 1:
					return '测试期'
				case 2:
					return '沉默期'
				case 3:
					return '使用中'
				case 4:
					return '停机'
				case 5:
					return '停机保号'
				case 6:
					return '预销号'
				case 7:
					return '销号'
			}
		}
	},
	computed: {
		data_usage_Per: function () {
			let aa = Number(this.sim.data_usage / this.sim.data_plan) * 100
			return aa
		},
		data_balance_per: function () {
			let aa = Number(this.sim.data_balance / this.sim.data_plan) * 100
			return aa
		},
		hkdata_usage_Per: function () {
			let aa = Number(this.hksim.data_usage / this.hksim.data_plan) * 100
			return aa
		},
		hkdata_balance_per: function () {
			let aa = Number(this.hksim.data_balance / this.hksim.data_plan) * 100
			return aa
		}
	},
	mounted() {
		this.getEquipStatus()
	},
	methods: {
		//获取折线图数据
		getChartLine() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=forecast.worm_lamp.device_polyline_data',
				data: this.qs.stringify({
					device_type_id: 3,
					// device_id: this.queryInfo.e_id,
					d_id: this.queryInfo.e_id,
					start_time: this.queryInfo.begin,
					end_time: this.queryInfo.end
				})
			}).then((res) => {
				if (res.data.message == '') {
					var ChartData = [
						{
							name: '温度（°C）',
							dat: []
						},
						{
							name: '湿度（%）',
							dat: []
						},
						{
							name: '加热仓温度（°C）',
							dat: []
						}
					]
					var data = res.data.data
					this.options = {}
					if (data.length > 0) {
						for (let item of data) {
							ChartData[0].dat.unshift([
								item.addtime * 1000 + 8 * 3600000,
								Number(item.temperature)
							])
							ChartData[1].dat.unshift([
								item.addtime * 1000 + 8 * 3600000,
								Number(item.humidity)
							])
							ChartData[2].dat.unshift([
								item.addtime * 1000 + 8 * 3600000,
								Number(item.others)
							])
						}
						this.options = {
							chart: {
								zoomType: 'x'
							},
							title: {
								text: '环境温湿度',
								align: 'left'
							},
							subtitle: {
								text: ''
							},
							xAxis: {
								crosshair: true, //十字基准线
								type: 'datetime',
								dateTimeLabelFormats: {
									//根据时间间距X轴自动显示哪种格式
									millisecond: '%H:%M:%S.%L',
									second: '%H:%M:%S',
									minute: '%H:%M',
									hour: '%H:%M',
									day: '%m-%d',
									week: '%m-%d',
									month: '%Y-%m',
									year: '%Y'
								}
							},
							yAxis: {
								title: {
									text: ''
								}
							},
							legend: {
								// layout: 'vertical',
								align: 'right',
								verticalAlign: 'top'
							},
							plotOptions: {
								series: {
									label: {
										connectorAllowed: false
									},
									pointStart: 2010
								}
							},
							series: [
								{
									name: ChartData[0].name,
									data: ChartData[0].dat
								},
								{
									name: ChartData[1].name,
									data: ChartData[1].dat
								},
								{
									name: ChartData[2].name,
									data: ChartData[2].dat
								}
							],
							colors: ['#00e29d', '#6cbbff', '#ff3f3f'],
							credits: {
								//去掉默认的highcharts.com
								enabled: false
							},
							tooltip: {
								// crosshairs: true,
								shared: true, //折线共享
								headerFormat: '<b>{point.x:%Y-%m-%e %H:%M:%S}</b><br>'
							},
							responsive: {
								rules: [
									{
										condition: {
											maxWidth: 500
										},
										chartOptions: {
											legend: {
												layout: 'horizontal',
												align: 'center',
												verticalAlign: 'bottom'
											}
										}
									}
								]
							}
						}
					}
				}
			})
		},
		// 获取状态信息
		getEquipStatus() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=forecast.worm_lamp.device_status_data',
				data: this.qs.stringify({
					device_id: this.queryInfo.e_id
				})
			}).then((res) => {
				if (res.data.message == '') {
					this.equipStatus = res.data.data;
					if(res.data.data.dver.indexOf('HK') != '-1'){ //判断版本是否包含HK的
						this.showHksimFlag = true;
					}else{
						this.showHksimFlag = false;
					}
				}
			})
		},
		dateChange(data) {
			this.queryInfo.page = 1
			this.queryInfo.begin = data.begin
			this.queryInfo.end = data.end
			this.getChartLine()
			this.getHisDataList()
		},
		//获取表格数据
		getHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=forecast.worm_lamp.device_history_data',
				data: this.qs.stringify({
					device_type_id: 3,
					device_id: this.queryInfo.e_id,
					start_time: this.queryInfo.begin,
					end_time: this.queryInfo.end,
					page: this.queryInfo.page
				})
			}).then((res) => {
				if (res.data.message == '') {
					this.total = res.data.data.counts
					var data = res.data.data.data
					this.tableData = []
					if (data.length > 0) {
						for (var i = 0; i < data.length; i++) {
							var dht = data[i].d_h_t
							dht.addtime = this.formatTime(dht.addtime * 1000)
							dht.rps = dht.rps == 0 ? '正常' : '雨控'
							dht.tps = dht.tps == 0 ? '正常' : '温控'
							dht.lps = dht.lps == 0 ? '正常' : '光控'
							if (dht.lamp != undefined) {
								if (dht.ws == 1) {
									if (dht.lamp == 1) {
										dht.blbs = '工作中'
									} else if (dht.lux == 0) {
										dht.blbs = 'N/A（未检测到传感器）'
									} else {
										dht.blbs = '异常'
									}
								} else {
									dht.blbs = '关闭'
								}
							} else {
								dht.blbs = '--'
							}
							this.tableData.push(dht)
						}
					}
				}
			})
		},
		//改变page
		changePage(val) {
			this.queryInfo.page = val
			this.getHisDataList()
		},
		// SIM卡
		lookSIMCode(flag) {
			this.simLoading = true;
			this.simCodeVisible = true
			if(flag == 'sim'){
				if(!this.simFlag){
					this.simLoading = false;
					return false;
				}
			}
			this.$axios({
				method: 'post',
				url: '/api/api_gateway?method=forecast.send_control.device_sim',
				data: this.qs.stringify({
					d_id: this.queryInfo.d_id,
					type:flag
				})
			}).then((res) => {
				if (res.data.message == '') {
					this.sim.iccid = res.data.data[0].iccid
					this.$axios({
						method: 'POST',
						url: '/api/api_gateway?method=forecast.send_control.sim_query',
						data: this.qs.stringify({
							iccid: this.sim.iccid
						})
					}).then((res) => {
						let data = eval('(' + res.data.data.data + ')')
						if (data.code!=0){
							this.$message({
								type: 'info',
								message: data.msg
							});   
							this.hksim = {
								iccid: '',
								account_status: 0, //卡状态 0-7 未知 测试期 沉默期 使用中 停机 停机保号 预销号 销号
								data_plan: 0, //套餐大小
								data_usage: 0, //当月用量
								data_balance: 0, //剩余流量
								expiry_date: 0 //到期日期
							}
							console.log(this.hksim)
						}
						if (res.data.message == '') {
							console.log(data)
							let cardInfo = data.data
							this.simLoading = false;
							if(flag == 'sim'){
								this.sim = cardInfo
								this.simFlag = false;
							}else{
								if(cardInfo){
									this.hksim = cardInfo
								}else{
									this.hksim = {
										iccid: '',
										account_status: 0, //卡状态 0-7 未知 测试期 沉默期 使用中 停机 停机保号 预销号 销号
										data_plan: 0, //套餐大小
										data_usage: 0, //当月用量
										data_balance: 0, //剩余流量
										expiry_date: 0 //到期日期
									}
								}
							}
						}
					})
				}
			})
		},
		//sim卡状态
		handleClick(tab, event) {
				console.log(event)
				console.log(event.target)
				console.log(event.target.innerText)
			if((event.target.innerText == '海康SIM卡流量') && (this.hksimFlag) ){
				this.hksimFlag = false;
				console.log(event.target.innerText)
				this.lookSIMCode('hksim');
			}
		},
		//绑定更换海康SIM
		changeHkSim(){
			if(!this.hksiminp){}
			this.$axios({
				method: 'post',
				url: '/api/api_gateway?method=forecast.send_control.device_sim',
				data: this.qs.stringify({
					d_id: this.queryInfo.d_id,
					iccid: this.hksiminp,
					type:'change'
				})
			}).then((res) => {
				 this.hksiminp = '';
				if (res.data.data == '1') {
					this.lookSIMCode('hksim')
				}
			})
		},
		//刷新按钮
		refresh() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=forecast.send_control.get_device_config',
				data: this.qs.stringify({
					device_type_id: 3,
					d_id: this.queryInfo.d_id,
					control_type: 'data'
				})
			}).then((res) => {
				if (res.data.data) {
					this.$message.success('刷新成功')
				} else {
					this.$message.err('刷新失败')
				}
			})
		}
	},
	components: {
		DateSearch
	}
}
</script>

<style lang='less' scoped>
.equipInfo {
	display: flex;
	justify-content: space-between;
	margin-bottom: 15px;
	.equipMsg {
		font-size: 14px;
		color: #3d3d3d;
	}
}
.ctrl-check {
	margin-bottom: 20px;
}

.time-check {
	display: flex;
	justify-content: space-between;
	.el-button {
		border-radius: 30px;
	}
	.el-input__inner {
		width: 222px;
	}
}
.charts {
	height: 450px;
}
.equipStatus {
	display: flex;
	justify-content: center;
	margin: 10px 0;
	.equipIcon {
		margin-right: 14%;
	}
	.equipParams {
		min-width: 80px;
		line-height: 27px;
		p {
			color: #a6a6a6;
		}
	}
}

.dataTableSearch {
	display: flex;
	justify-content: space-between;
	margin: 20px 0;
	.el-input__inner {
		width: 222px;
	}
}
.echarts {
	width: 100%;
	height: 300px;
}
.simCodeBox {
	> div {
		line-height: 40px;
		display: flex;
		align-content: center;
		.simCodeTitle {
			width: 100px;
			text-align: right;
			font-size: 14px;
			color: #333;
		}
		> div {
			flex: 1;
			.el-progress {
				margin-top: 17px;
			}
		}
		span {
			width: 85px;
			font-size: 12px;
			padding-left: 3px;
			color: #909090;
		}
		.el-input {
			width: 60%;
		}
	}
	.operateBtn {
		display: block;
		text-align: right;
	}
}
</style>