<template>
	<div class="app-container">
		<!--工具栏-->
		<div class="head-container">
			<!-- 搜索 -->
			<!-- <el-select v-model="deptparam" clearable placeholder="请选择部门" class="filter-item" style="width: 130px" @change="loaddevice">
				<el-option v-for="item in depts" :key="item.id" :label="item.name" :value="item.id" />
			</el-select> -->
			<el-select v-model="deviceparam" clearable placeholder="请选择设备" class="filter-item" style="width: 260px" @change="loaditem()">
				<el-option v-for="item in devices" :key="item.deviceid" :label="item.name" :value="item.deviceid" />
			</el-select>
			<el-select v-model="itemparam" clearable placeholder="请选择检测项" class="filter-item" style="width: 130px">
				<el-option v-for="item in items" :key="item.code" :label="item.subject" :value="item.code" />
			</el-select>

			<label class="el-form-item-label" style="font-weight: 500;margin-left: 10px;">开始时间</label>
			<el-date-picker v-model="starttime" type="date" placeholder="开始时间"> </el-date-picker>

			<label class="el-form-item-label" style="font-weight: 500;margin-left: 10px;">结束时间</label>
			<el-date-picker v-model="endtime" type="date" placeholder="结束时间"> </el-date-picker>

			<el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="QueryDataStart">搜索</el-button>
			<el-button class="filter-item" size="mini" type="success" icon="el-icon-tickets" @click="exportExcel">导出</el-button>
			<!-- 新增 -->
			<!--<div style="display: inline-block;margin: 0px 2px;">
        <el-button
          v-permission="['ADMIN','SDATA_ALL','SDATA_CREATE']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add">新增</el-button>
      </div>-->
		</div>
		<!--表单组件-->
		<eForm ref="form" :is-add="isAdd" />
		<!--表格渲染-->
		<el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
			<el-table-column prop="deviceid" label="设备名称">
				<template slot-scope="scope">
					<div v-for="item in devicesItem" :key="item.deviceid">
						<div v-if="scope.row.deviceid === item.deviceid">{{ item.name }}</div>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="itemName" label="检测项" />
			<el-table-column prop="data" label="数据值">
				<template slot-scope="scope">
					<span v-if="scope.row.itemName != '风向'">
						{{ scope.row.data }}
					</span>
					{{ scope.row.unit }}
				</template>
			</el-table-column>
			<el-table-column prop="dtime" label="时间">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.dtime) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="rssi" label="信号强度" />
			<el-table-column prop="battery" label="电量" />
			<el-table-column v-if="checkPermission(['ADMIN', 'SDATA_ALL', 'SDATA_EDIT', 'SDATA_DELETE'])" label="操作" width="150px" align="center">
				<template slot-scope="scope">
					<el-button v-permission="['ADMIN', 'SDATA_ALL', 'SDATA_EDIT']" size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)" />
					<el-popover v-permission="['ADMIN', 'SDATA_ALL', 'SDATA_DELETE']" :ref="scope.row.id" placement="top" width="180">
						<p>确定删除本条数据吗？</p>
						<div style="text-align: right; margin: 0">
							<el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
							<el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
						</div>
						<el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
					</el-popover>
				</template>
			</el-table-column>
		</el-table>
		<!--分页组件-->
		<el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChange" @current-change="pageChange" />
		<el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
			<div id="myChart" style="height:400px;width:100% " />
		</el-row>
	</div>
</template>

<script>
import checkPermission from '@/utils/permission'
// import initData1 from '@/mixins/initData'
import { del } from '@/api/sData'
import { deptByUseridNoPage } from '@/api/dept'
import { loaddevice } from '@/api/sDevice'
import { getData, exportExcel } from '@/api/sData'
import { parseTime, timeParse } from '@/utils/index'
import { queryAllByUseridNoPage } from '@/api/sDevice'
import { sItem } from '@/api/home'
import eForm from './form'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
export default {
	components: { eForm },
	// mixins: [initData1],
	data() {
		return {
			delLoading: false,
			depts: '',
			devices: '',
			items: [],
			sub: {},
			queryData: '',
			deptparam: '',
			deviceparam: '',
			itemparam: '',
			loading: false,
			data: [],
			page: 1,
			size: 10,
			total: 0,
			url: '',
			params: {},
			query: {},
			time: 170,
			isAdd: false,
			queryTypeOptions: [{ key: 'deviceid', display_name: '设备id' }, { key: 'item', display_name: '检测项' }],
			chart: null,
			sidebarElm: null,
			chartData: {
				showData: [],
			},
			dtime: [],

			starttime: '', //开始时间
			endtime: '', //结束时间
			devicesItem: '', //监测值名称
			sItemUnit: {}, //监测单位
		}
	},
	created() {
		this.$nextTick(() => {
			this.loaddeptByUserid()
		})
	},

	mounted() {
		let day = 15 * 1 * 86400 * 1000
		let dateCur = Date.parse(new Date())
		this.starttime = timeParse(dateCur - day) // 开始时间
		this.endtime = timeParse() // 结束时间

		queryAllByUseridNoPage().then(response => {
			this.devicesItem = response
		})

		sItem({
			page: 0,
			size: 1000,
			sort: 'id,desc',
		}).then(res => {
			var arr = res.content || [];
			for(var item of arr){
				this.sItemUnit[item.code] = item;
			}
		})
	},

	methods: {
		parseTime,
		checkPermission,

		// 获取部门ID
		loaddeptByUserid() {
			deptByUseridNoPage().then(response => {
				this.depts = response
				this.deptparam = this.depts[0].id
				this.loaddevice()
			})
		},

		// 获取设备列表
		loaddevice() {
			loaddevice(this.deptparam).then(response => {
				this.devices = response
				this.deviceparam = response[0].deviceid
				this.loaditem()
			})
		},

		// 设备列表下面的子选项
		loaditem() {
			this.items = []
			for (var i = 0; i < this.devices.length; i++) {
				if (this.deviceparam === this.devices[i].deviceid) {
					var code = this.devices[i].code.split(',')
					var subject = this.devices[i].subject.split(',')
					for (var j = 0; j < code.length; j++) {
						this.sub = {}
						this.sub.code = code[j]
						this.sub.subject = subject[j]
						this.items[j] = this.sub
					}
				}
			}
			this.itemparam = this.items[0].code

			const query = this.$route.query
			if (query.item) {
				this.deviceparam = query.deviceid
				this.itemparam = query.item
			}

			this.QueryDataStart()
		},

		// 点击搜索
		QueryDataStart() {
			this.page = 1
			this.QueryData()
		},

		QueryData() {
			const sort = 'dtime,desc'
			// if (this.deviceparam === '' || this.itemparam === '' || this.starttime === '' || this.endtime === null) {
			// 	this.$notify({
			// 		title: '请选择查询信息！',
			// 		type: 'warning',
			// 		duration: 2500,
			// 	})
			// 	return
			// }

			// 时间跨度不能超过14天！
			// var s = new Date(this.endtime.replace(/-/g, '/')) - new Date(this.starttime.replace(/-/g, '/'))
			// var day = s / 1000 / 60 / 60 / 24
			// if (day > 14) {
			// 	this.$notify({
			// 		title: '时间跨度不能超过14天！',
			// 		type: 'warning',
			// 		duration: 2500,
			// 	})
			// 	return
			// }

			this.loading = true
			this.params = { page: this.page, size: this.size, sort: sort }
			getData(this.deviceparam, this.itemparam, this.starttime, this.endtime, this.params).then(response => {
				var dataList = response.data || [];
				for(var item of dataList){
					var attr = this.sItemUnit[item.item];
					item.itemName = attr.subject;
					if(item.item === "FX"){
						var val = ~~item.data, subName = '';
						switch(val){
							case 0: subName='北风'; break;
							case 1: subName='东北风'; break;
							case 2: subName='东风'; break;
							case 3: subName='东南风'; break;
							case 4: subName='南风'; break;
							case 5: subName='西南风'; break;
							case 6: subName='西风'; break;
							case 7: subName='西北风'; break;
							default : subName='北风';
						};
						item.unit = subName;
					}else{
						item.unit = attr.unit;
					};
				};
				this.data = dataList;

				this.total = response.total
				this.dataNopage = response.dataNopage
				this.loading = false
				if (this.data.length === 0) {
					if (this.chart != null) {
						this.chart.clear()
					}
					this.$notify({
						title: '没有数据！',
						type: 'warning',
						duration: 2500,
					})
					return
				}
				this.chartData.showData = response.dataNopage.map(function(data) {
					return data.data
				})
				this.dtime = response.dataNopage.map(function(data) {
					return data.dtime
				})
				this.initChart()
			})
		},

		exportExcel() {
			if (this.deviceparam === '' || this.itemparam === '' || this.starttime === '' || this.endtime === null) {
				this.$notify({
					title: '请选择查询信息！',
					type: 'warning',
					duration: 2500,
				})
				return
			}
			this.loading = true
			exportExcel(this.deviceparam, this.itemparam, this.starttime, this.endtime).then(response => {
				this.loading = false
				this.downloadFile(response)
			})
		},
		downloadFile(data) {
			// 文件导出
			if (!data) {
				return
			}
			const url = window.URL.createObjectURL(new Blob([data]))
			const link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			link.setAttribute('download', 'data.xlsx')
			document.body.appendChild(link)
			link.click()
		},
		add_10(num) {
			if (num < 10) {
				num = '0' + num
			}
			return num
		},
		// beforeInit() {
		//   this.url = 'api/sData'
		//   const sort = 'id,desc'
		//   this.params = { page: this.page, size: this.size, sort: sort }
		//   const query = this.query
		//   const type = query.type
		//   const value = query.value
		//   if (type && value) { this.params[type] = value }
		//   return true
		// },
		pageChange(e) {
			this.page = e
			this.QueryData()
		},
		sizeChange(e) {
			this.page = 0
			this.size = e
			this.QueryData()
		},
		subDelete(id) {
			this.delLoading = true
			del(id)
				.then(res => {
					this.delLoading = false
					this.$refs[id].doClose()
					this.dleChangePage()
					this.$notify({
						title: '删除成功',
						type: 'success',
						duration: 2500,
					})
				})
				.catch(err => {
					this.delLoading = false
					this.$refs[id].doClose()
				})
		},
		add() {
			this.isAdd = true
			this.$refs.form.dialog = true
		},
		edit(data) {
			this.isAdd = false
			const _this = this.$refs.form
			_this.form = {
				id: data.id,
				deviceid: data.deviceid,
				item: data.item,
				dtime: data.dtime,
				data: data.data,
				rssi: data.rssi,
				battery: data.battery,
				nt: data.nt,
			}
			_this.dialog = true
		},
		setOptions({ showData } = {}) {
			this.chart.setOption({
				xAxis: {
					data: this.dtime,
					boundaryGap: false,
					axisTick: {
						show: false,
					},
				},
				grid: {
					left: 10,
					right: 10,
					bottom: 20,
					top: 30,
					containLabel: true,
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'cross',
					},
					padding: [5, 10],
				},
				yAxis: {
					axisTick: {
						show: false,
					},
				},
				legend: {
					data: ['pv'],
				},
				series: [
					{
						name: '',
						itemStyle: {
							normal: {
								color: '#3888fa',
								lineStyle: {
									color: '#3888fa',
									width: 2,
								},
							},
						},
						smooth: true,
						type: 'line',
						data: showData,
						animationDuration: 2800,
						animationEasing: 'cubicInOut',
					} /*,
        {
          name: 'ip',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#3888fa',
              lineStyle: {
                color: '#3888fa',
                width: 2
              },
              areaStyle: {
                color: '#f3f8ff'
              }
            }
          },
          data: ipData,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }*/,
				],
			})
		},
		initChart() {
			this.chart = echarts.init(document.getElementById('myChart'), 'macarons')
			this.setOptions(this.chartData)
		},
	},
}
</script>

<style scoped></style>
