<!-- 设备历史数据 -->
<template>
  <div class="equipInfo">
    <DateSearch @exportData="exportData" @dateChange="dateChange" @toggleSwitcState="toggleSwitcState"></DateSearch>
    <div class="charts" v-if="switcState">
      <highcharts
        class="highcharts"
        :options="options"
        v-if="Object.keys(options).length > 0"
      ></highcharts>
      <div class="noDataClass" v-else>暂无数据</div>
    </div>
    <div v-if="!switcState">
      <el-table :data="tableData" max-height="300" class="customTable" :header-row-class-name="tableth" style="width: 150%">
        <el-table-column
          v-for="(item, index) in tableHeadTxt[equipType]"
          :key="index"
          :prop="item"
          :label="equipState_dict[item].name+equipState_dict[item].unit"
          :width="item=='addtime'?'170px':''"
        >
          <template slot-scope="scope">
            <template v-if="equipState_dict[scope.column.property].value">
              {{ equipState_dict[scope.column.property].value[scope.row.d_h_t[scope.column.property]] }}
            </template>
            <template v-else>
              <template v-if="scope.column.property=='addtime'">
                  {{ scope.row.d_h_t[scope.column.property]*1000|formatTime }}
              </template>
              <template v-else>
                {{ scope.row.d_h_t[scope.column.property] }}
              </template>
            </template>
          </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 equipState_dict from './equipState_dict.json'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    DateSearch
  },
  props: ["equipId", "equipType","d_id"],
  data() {
    //这里存放数据
    return {
      equipState_dict,
      queryInfo:{
        begin:"",
        end:"",
        page:1,
      },
      switcState:true,
      options:{},
      ChartData:[],
      // 表格数据
      total:0,
      tableData:[],
      // 动态表头
      tableHeadTxt: {
        "2":["ds", "ws", "tbs", "rps", "tps", "dps", "tt", "ct", "at", "ah", "cv", "bv","addtime"],
        "3":["at","ah","hrt","rps","tps","lps","lamp","csq","current","vbat","addtime"],
        "4":["proj","ds","ws","at","ah","cv","bv","cs","bs","infr_ct","csq","dver","addtime"],
        "7":["ds","ws", "at", "ah", "set_temp", "pre_temp", "batStatus", "rps", "usb_sta", "csq", "dver", "addtime"],
        // "7":["on_off", "at", "ah", "set_temp", "pre_temp", "batStatus", "rps", "usb_sta", "v_bat", "alti", "csq", "dver", "addtime"],
      }
    };
  },
  //监听属性 类似于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.getChartLine('chart','table');
    },
    exportData(data){
      window.location.href =
			this.$deriveData +
			"/api/cbd_export?device_id=" +
			this.d_id +
			"&filename=1" +
			"&start_time=" +
			data.begin +
			"&end_time=" +
			data.end +
      "&device_type="+
      this.equipType;
    },
    toggleSwitcState(data){
      this.switcState = data
    },
    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,
        // 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",
                },
              },
            },
          ],
        },
        previous:0
      };
    },
    getChartLine(chart,table){
      switch(this.equipType){
        case 2:
          console.log(123213123);
          
          if(chart){
            this.ChartData = [
              {
                name: "温度（°C）",
                data: [],
              },
              {
                name: "湿度（%）",
                data: [],
              },
              {
                name: "击虫次数",
                data: [],
              },
              {
                name: "充电电压",
                data: [],
              },
              {
                name: "电池电压",
                data: [],
              },
            ]
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_polyline_data",
              data: this.qs.stringify({
                device_type_id: 2,
                d_id: this.d_id,
                start_time: this.queryInfo.begin,
                end_time: this.queryInfo.end,
              }),
            }).then((res) => {
              if (res.data.data.length !== 0) {
                var data = res.data.data;
                for (let item of data) {
                  this.ChartData[0].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.temperature),
                  ]);
                  this.ChartData[1].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.humidity),
                  ]);
                  this.ChartData[2].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others.ct),
                  ]);
                  this.ChartData[3].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others.cv/1000),
                  ]);
                    this.ChartData[4].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others.bv/1000),
                  ]);
                }
                this.$nextTick(()=>{
                  console.log(this.ChartData)
                  this.options = this.optionFn(this.ChartData);

                })
              }else{
                this.options = {};
              }
            });
          }
          if(table){
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_history_data",
              data: this.qs.stringify({
                device_type_id: 2,
                device_id: this.equipId,
                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 = [];
                this.tableData = data
              }
            });
          }
          break;
        case 3:
          if(chart){
            this.ChartData = [
              {
                name: "温度（°C）",
                data: [],
              },
              {
                name: "湿度（%）",
                data: [],
              },
              {
                name: "识别害虫数量（只）",
                data: [],
              },
            ]
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_polyline_data",
              data: this.qs.stringify({
                device_type_id: 3,
                d_id: this.d_id,
                start_time: this.queryInfo.begin,
                end_time: this.queryInfo.end,
              }),
            }).then((res) => {
              if (res.data.data.length) {
                var data = res.data.data;
                for (let item of data) {
                  this.ChartData[0].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.temperature),
                  ]);
                  this.ChartData[1].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.humidity),
                  ]);
                  this.ChartData[2].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others),
                  ]);
                }
                this.options = this.optionFn(this.ChartData);
                // this.loadingInstance.close();
              }else{
                this.options = {}
              }
            });
          }
          if(table){
            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.equipId,
                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 = [];
                this.tableData = data
              }
            });
          }
          break;
        case 4:
          if(chart){
            this.ChartData = [
              {
                name: "温度（°C）",
                data: [],
              },
              {
                name: "湿度（%）",
                data: [],
              },
              {
                name: "诱虫次数（头）",
                data: [],
              },
              // {
              //   name: "高压计数值",
              //   data: [],
              // },
              // {
              //   name: "cpu温度（°C）",
              //   data: [],
              // },
            ]
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_polyline_data",
              data: this.qs.stringify({
                device_type_id: 4,
                d_id: this.d_id,
                start_time: this.queryInfo.begin,
                end_time: this.queryInfo.end,
              }),
            }).then((res) => {
              if (res.data.data.length > 0) {
                var data = res.data.data;
                for (let item of data) {
                  this.ChartData[0].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.temperature),
                  ]);
                  this.ChartData[1].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.humidity),
                  ]);
                  this.ChartData[2].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others.infr_ct),
                  ]);
                }
                this.options = this.optionFn(this.ChartData);
              }else{
                this.options = {};
              }
            });
          }
          if(table){
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_history_data",
              data: this.qs.stringify({
                device_type_id: 4,
                device_id: this.equipId,
                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 = [];
                this.tableData = data
              }
            });
          }
          break;
        case 7:
          if(chart){
            this.ChartData = [
              {
                name: "温度（°C）",
                data: [],
              },
              {
                name: "湿度（RH）",
                data: [],
              },
              {
                name: "保温仓温度（°C）",
                data: [],
              },
            ]
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_polyline_data",
              data: this.qs.stringify({
                device_type_id: 7,
                d_id: this.d_id,
                start_time: this.queryInfo.begin,
                end_time: this.queryInfo.end,
              }),
            }).then((res) => {
              if (res.data.data.length !== 0) {
                var data = res.data.data;
                for (let item of data) {
                  this.ChartData[0].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.temperature),
                  ]);
                  this.ChartData[1].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.humidity),
                  ]);
                  this.ChartData[2].data.unshift([
                    item.addtime * 1000 + 8 * 3600000,
                    Number(item.others),
                  ]);
                }
                this.options = this.optionFn(this.ChartData);
              }else{
                this.options = {};
              }
            });
          }
          if(table){
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.device_history_data",
              data: this.qs.stringify({
                device_type_id: 7,
                device_id: this.equipId,
                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 = [];
                this.tableData = data
              }
            });
          }
          break;
        default:
          break;
      }
    },
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.getChartLine('','table');
    },
    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);
}
.highcharts{
  height: 350px;
}
// 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;
}
// 分页
/deep/.el-pagination{
  margin-bottom: 0;
}
</style>