<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right" :class="'el-icon-arrow-right '+ (flag.flag == false ? 'breadcrumb_tab' : '')">
			<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.query.id}}</span>
				<span>设备名称：{{this.$route.query.name || '无'}}</span>
				<span>位置：{{this.$route.query.address || "无"}}</span>
			</div>
			<DateSearch @dateChange="dateChange" ref="setSelected"></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:360px">暂无数据</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/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-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 {
	props: {
		flag: {
			flag: Boolean,
			siteID: Number
		},
	},
	data() {
		return {
			isOne:true,
			isSelect:true,
			isSelectNian:true,
			isSelectYear:true,
			// 请求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'],
				['电池电压(V)', 'vbat'],
				['上报时间', 'addtime']
			],
			// 表格数据
			tableData: [],
			timeRange: '',
			queryInfo: {
				begin: '',
				end: '',
				e_id: this.$route.query.e_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: {
		//获取折线图数据
		initChartLine() {
			this.$axios({
				method: 'POST',
				url: '/cbd_report_detail_chart',
				data: this.qs.stringify({
					req: 'filter',
					begin: this.queryInfo.begin,
					end: this.queryInfo.end,
					id: this.$route.query.id
				})
			}).then((res) => {
				if(res.data.length>0){
					this.isOne = false;
					var at = [],ah = [];
					for(var i = 0;i<res.data.length;i++){
						at.push([this.returnTime(res.data[i].tim),res.data[i].at/10])
						ah.push([this.returnTime(res.data[i].tim),res.data[i].ah/10])
						if(i == res.data.length-1){
							this.options = {
								chart: {
									zoomType: 'x',
									height: 360,
								},
								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: '环境湿度',
										data: ah
									},
									{
										name: '环境温度',
										data: at
									}
								],
								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'
												}
											}
										}
									]
								}
							}
						}
					}
				}else{
					this.options = {};
					if(this.isSelect){
					console.log(res.data.length);
						this.$refs.setSelected.timeBtnClick(2);
						this.isSelect = false
						// this.getChartLine();
						// this.getHisDataList()
					}else if(this.isSelectNian){
					console.log(res.data.length);
						this.$refs.setSelected.timeBtnClick(3);
						this.isSelectNian = false
						// this.getChartLine()
						// this.getHisDataList()
					}else if(this.isSelectYear){
					console.log(res.data.length);
						this.$refs.setSelected.timeBtnClick(4);
						this.isSelectYear = false
						// this.getChartLine()
						// this.getHisDataList()
					}
				}
			})
		},
		//获取折线图数据
		getChartLine() {
			this.$axios({
				method: 'POST',
				url: '/cbd_report_detail_chart',
				data: this.qs.stringify({
					req: 'filter',
					begin: this.queryInfo.begin,
					end: this.queryInfo.end,
					id: this.$route.query.id
				})
			}).then((res) => {
				if(res.data.length>0){
					var at = [],ah = [];
					for(var i = 0;i<res.data.length;i++){
						at.push([this.returnTime(res.data[i].tim),res.data[i].at/10])
						ah.push([this.returnTime(res.data[i].tim),res.data[i].ah/10])
						if(i == res.data.length-1){
							this.options = {
								chart: {
									zoomType: 'x',
									height: 360,
								},
								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: '环境湿度',
										data: ah
									},
									{
										name: '环境温度',
										data: at
									}
								],
								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'
												}
											}
										}
									]
								}
							}
						}
					}
				}else{
					this.options = {};
					
				}
			})
		},
		// 返回时间戳
		returnTime(time) {
			var thisTime = time.replace(/-/g, '/');
			var time = new Date(thisTime);
			var timestamp = time.getTime() + 8 * 3600000;
			return timestamp;
		},
		// 获取状态信息
		getEquipStatus() {
			this.$axios({
				method: 'POST',
				url: '/equipmanage_cbd_detail',
				data: this.qs.stringify({
					id: this.$route.query.id
				})
			}).then((res) => {
					var datStr = res.data[0].cbd_status;
					var dat = eval('('+datStr+')');
					this.equipStatus = {
						dver:dat.dver,
						csq:dat.csq,
						upds:dat.upds,
						hs:dat.hs,
						gs:dat.gs,
						ts:dat.ts,
						device_status:dat.is_online,
					};
			})
		},
		dateChange(data) {
			this.queryInfo.page = 1
			this.queryInfo.begin = new Date(data.begin*1000).toLocaleDateString().replace(/\//g,'-'); 
			this.queryInfo.end = new Date(data.end*1000).toLocaleDateString().replace(/\//g,'-'); 
			if(this.isOne){
				this.initChartLine()
				this.getHisDataList()
			}else{
				this.getChartLine()
				this.getHisDataList()
			}
		},
		//获取表格数据
		getHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/cbd_report_detail',
				data: this.qs.stringify({
					page: this.queryInfo.page,
					req: 'filter',
					id: this.$route.query.id,
					begin: this.queryInfo.begin,
					end: this.queryInfo.end
				})
			}).then((res) => {
				this.tableData = []
				this.total = res.data.nums
				var dat = res.data.dat
					for (var i = 0; i < dat.length; i++) {
						var cbd_data = eval('('+dat[i].cbd_data+')')
						var rps = cbd_data.rps == 0 ? '正常' : '雨控';
						var tps = cbd_data.tps == 0 ? '正常' : '温控';
						var lps = cbd_data.lps == 0 ? '正常' : '光控';
						this.tableData.push({
							at:(cbd_data.at/10).toFixed(2),
							ah:(cbd_data.ah/10).toFixed(2),
							hrt:cbd_data.hrt,
							rps:rps,
							tps:tps,
							lps:lps,
							vbat:cbd_data.vbat,
							addtime:dat[i].upl_time
						})
					}
			})
		},
		//改变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_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_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_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: '/cbd_mqtt',
				data: this.qs.stringify({
					req: 'read',
					topicid: this.$route.query.id,
					kind: 'status'
				})
			}).then((res) => {
				if (res.data == 0) {
					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: 360px;
	highcharts{
		height: 360px;
	}
}
.equipStatus {
	display: flex;
	margin: 10px 0;
	.equipIcon {
		margin: 0 10%;
	}
	.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;
	}
}

.breadcrumb_tab {
	top: 60px !important;
}
</style>