<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" @change="loadFlag()">
				<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-form-item>-->
			<!--<el-button class="filter-item" size="mini" type="success" icon="el-icon-tickets" @click="exportExcel">导出</el-button>-->
			<!--</el-form-item>-->
			<!-- 新增 -->
			<!--<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-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
			<div id="myChart" style="height:400px;width:100% " />
		</el-row>
		<el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
			<el-table-column prop="deviceid" label="设备id" />
			<el-table-column prop="dtime" label="时间" />
			<el-table-column prop="data" 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"/>-->
	</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 { getIllData, exportExcel } from '@/api/sData'
import { parseTime, timeParse } from '@/utils/index'
import eForm from './form'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
export default {
	components: { eForm },
	// mixins: [initData1],
	data() {
		return {
			delLoading: false,
			Currenttime: '',
			depts: '',
			devices: '',
			items: [],
			sub: {},
			queryData: '',
			deptparam: '',
			deviceparam: '',
			itemparam: '',
			loading: false,
			data: [],
			page: 1,
			size: 10,
			total: 0,
			url: '',
			params: {},
			query: {},
			time: 170,
			isAdd: false,
			clickFlag: false,
			queryTypeOptions: [{ key: 'deviceid', display_name: '设备id' }, { key: 'item', display_name: '检测项' }],
			chart: null,
			sidebarElm: null,
			chartData: {
				showData: [],
			},
			dtime: [],

      starttime: '', //开始时间
			endtime: '', //结束时间
		}
	},
	created() {
		this.$nextTick(() => {
			// this.init()
			this.getTime()
			this.loaddeptByUserid()
		})
	},

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

	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++) {
						// if (code[i].indexOf('ILL') !== -1) {// 包含光照ILL
						this.sub = {}
						this.sub.code = code[j]
						this.sub.subject = subject[j]
						this.items[j] = this.sub
						// }
					}
				}
			}
			for (let item of this.items) {
				if (item.subject == '光照') {
					this.itemparam = item.code
				}
			}
			this.QueryDataStart()
		},


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

		getTime() {
			var myDate = new Date()
			var time = this.add_10(myDate.getHours()) + ':' + this.add_10(myDate.getMinutes()) + ':' + this.add_10(myDate.getSeconds())
			this.Currenttime = time
		},

		QueryData() {
			const sort = 'dtime,esc'
			if (this.deviceparam === '' || this.itemparam === '' || this.starttime === '' || this.endtime === null) {
				this.$notify({
					title: '请选择查询信息！',
					type: 'warning',
					duration: 2500,
				})
				return
			}
		
			this.loading = true
			this.params = { page: this.page, size: this.size, sort: sort }
			getIllData(this.deviceparam, this.itemparam, this.starttime, this.endtime, this.params)
				.then(response => {
					this.data = response.illmap
					// 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.clickFlag = true
					this.chartData.showData = response.illdata
					this.dtime = response.days
					this.initChart()
				})
				.catch(err => {
					this.loading = false
					console.log(err.response.data.message)
				})
		},

		exportExcel() {
			if (!this.clickFlag) {
				this.$notify({
					title: '请先点击查询确认有数据！',
					type: 'warning',
					duration: 2500,
				})
				return
			}
			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()
		},

		loadFlag() {
			this.clickFlag = false
		},
		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.init()
					this.$notify({
						title: '删除成功',
						type: 'success',
						duration: 2500,
					})
				})
				.catch(err => {
					this.delLoading = false
					this.$refs[id].doClose()
					console.log(err.response.data.message)
				})
		},
		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',
					},
				],
			})
		},
		initChart() {
			this.chart = echarts.init(document.getElementById('myChart'), 'macarons')
			this.setOptions(this.chartData)
		},
	},
}
</script>

<style scoped></style>
