<!-- 气象站设备历史数据 -->
<template>
  <div class="equipInfo">
    <DateSearch @dateChange="dateChange" @toggleSwitcState="toggleSwitcState"></DateSearch>
    <div v-if="switcState">
      <highcharts v-if="ChartData.length"
        :options="options"
      ></highcharts>
      <div class="noDataClass" v-else>暂无数据</div>
    </div>
    <div v-if="!switcState">
      <el-table :data="hisData" max-height="405" class="customTable" :header-row-class-name="tableth"  style="width: 100%">
				<el-table-column
					v-for="(item, index) in tableHead"
					:key="index"
					:width="item.property == 'date' ? '160px' : ''"
					:label="item.label"
					:prop="item.property"
				>
					<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>
    </div>
    
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import HighCharts from "highcharts";
import DateSearch from "@/components/highStand/timeSearch";
import qxz_dict from './qxz_dict.json'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    DateSearch
  },
  props: ["equipId", "equipType","d_id"],
  data() {
    //这里存放数据
    return {
      qxz_dict,
      queryInfo:{
        begin:"",
        end:"",
        page:1,
      },
      switcState:true,
      options:{},
      ChartData:[],
      // 表格数据
      total:0,
      // 动态表头
			tableHead: [],
      hisData:[],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 设置hightcharts配置
    refreshData() {
      HighCharts.setOptions({
        // 所有语言文字相关配置都设置在 lang 里
        lang: {
          resetZoom: "刷新",
          resetZoomTitle: "重置缩放比例",
        },
      });
    },
    dateChange(data) {
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.queryInfo.page = 1;
      this.getEchartsHisDataList();
      this.getHisDataList();
    },
    optionFn(ChartData) {
      return {
        chart: {
          zoomType: "x",
          backgroundColor: 'rgba(0,0,0,0)'
        },
        title: {
          text: "",
          align: "left",
        },
        lang: {
          noData: "暂无数据",
        },
        noData: {
          style: {
            fontWeight: "bold",
            fontSize: "15px",
            color: "#303030",
          },
        },
        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",
          },
          lineColor:'#fff',
          labels: {
            style: {
              color: '#fff',
            }
	        },
        },
        yAxis: {
          title: {
            text: "",
          },
          lineColor:'#fff',
          labels: {
            style: {
              color: '#fff',
            }
	        },
        },
        legend: {
          // layout: 'vertical',
          align: "right",
          verticalAlign: "top",
          itemStyle:{
            color:'#fff',
          }
        },
        plotOptions: {
          series: {
            label: {
              connectorAllowed: false,
            },
            pointStart: 2010,
          },
        },
        series: ChartData,
        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",
                },
              },
            },
          ],
        },
        previous:0
      };
    },
    //获取图表历史数据
		getEchartsHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=weather.weather.qxz_data_chart',
				data: this.qs.stringify({
					begin: this.queryInfo.begin,
					end: this.queryInfo.end,
					device_id: this.equipId
				})
			})
				.then((res) => {
					this.echartsFn(res.data.data)
				})
				.catch((err) => {
					console.log(err)
				})
		},
		echartsFn(data) {
			let conf = data.conf
			let eData = data.data
      this.ChartData = []
			if (conf && eData && eData.length > 0) {
				for (let i in conf) {
					if (conf[i]) {
						//判断是否有值
						this.ChartData.push({
							key: i,
							name: conf[i].split('#')[0],
							unit: conf[i].split('#')[1],
							data: []
						})
					}
				}
				for (let m of eData) {
					//m是对象
					for (let n in m.dat) {
						//dat是对象 n是key
						for (let j of this.ChartData) {
							//j是对象
							if (j.key == n && m.dat[n].split('#')[0] != '-99.99') {
								j.data.push([
									m.time * 1000 + 8 * 3600000,
									Number(m.dat[n].split('#')[0])
								])
							}
						}
					}
				}
			} else {
				this.ChartData = []
      }
      this.$nextTick(()=>{
        this.options = this.optionFn(this.ChartData);
      })

		},
    getHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=weather.weather.qxz_detail',
				data: this.qs.stringify({
					start_time: this.queryInfo.begin,
					end_time: this.queryInfo.end,
					page: this.queryInfo.page,
					device_id: this.equipId
				})
			}).then((res) => {
				this.total = Number(res.data.data.nums)
				if (res.data.data.nums > 0) {
					let arr1 = [{ label: '日期', property: 'date' }]
					let arr2 = []
					let conf = res.data.data.conf
					let data = res.data.data.data
					for (let i in conf) {
						let obj = {}
						if (conf[i]) {
							let arr = conf[i].split('#')
							obj.label = `${arr[0]}(${arr[1]})`
							obj.property = i
							arr1.push(obj)
						}
					}
					this.tableHead = arr1
					for (let item of data) {
						let obj = {}
						obj.date = this.formatTime(item.time * 1000)
						for (let i1 in item.dat) {
							if (item.dat[i1]) {
								obj[i1] =
									item.dat[i1].split('#')[0] == '-99.99'
										? 'N/A'
										: item.dat[i1].split('#')[0]
							}
						}
						arr2.push(obj)
					}
					this.hisData = arr2
				} else {
					this.hisData = []
				}
			})
    },
    toggleSwitcState(data){
      this.switcState = data
    },
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.getHisDataList();
    },
    tableth(){
      return 'headerth'
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.refreshData(); //设置hightcharts配置
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
// 暂无数据
.noDataClass {
  text-align: center;
  font-size: 20px;
  line-height: 250px;
  color: rgb(122, 115, 115);
}
// table样式
/deep/.customTable.el-table tr,/deep/.customTable.el-table .headerth th.is-leaf{
    background-color: #1b222f;
    border-bottom: 1px solid #434343;
    color: #eee;
} 
/deep/.customTable.el-table--enable-row-hover .el-table__body tr:hover > td{
  background-color:#042741
}
/deep/.customTable.el-table th.is-leaf,/deep/.customTable.el-table td{
  border-bottom: 1px solid #515151;
}
/deep/.customTable.el-table--scrollable-x .el-table__body-wrapper{
    background-color: #1b222f;
    color: #eee;
}
/deep/.customTable.el-table .is-scrolling-none{
    background-color: #1b222f;
    color: #eee;
}
/deep/.customTable.el-table::before{
	background-color: #7d7d7d;
}
</style>