<!--要素历史数据-->
<template>
  <div class="innerMargin">
    <el-card class="box-card">

      <div class="equipInfo">
        <div class="equipMsg">
          <span>设备ID：{{ id }}</span>
          <span>设备名称：{{ equipStatus.device_name || "无" }}</span>
          <span>位置：{{ equipStatus.address }}</span>
        </div>
        <div class="dateBox">
          <DateSearch @dateChange="dateChange"></DateSearch>
        </div>
      </div>
      <!-- 自动统计图 -->
      <div>
        <div>
          <el-row :gutter="10">
            <el-col :md="24" :lg="24">
              <el-card class="box-card">
                <div class="charts">
                  <highcharts
                    :options="options"
                    v-if="Object.keys(options).length > 0"
                  ></highcharts>
                  <div class="noDataClass" v-else>暂无数据</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <div class="dataTableSearch">
          <!-- <el-button type="blueInfo" size="mini" @click="deriveData()"
            >导出</el-button
          > -->
        </div>
        <!-- 统计信息 -->
        <el-card class="box-card">
          <el-table :data="eleValTable" stripe 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
            v-if="eleValTable.length > 0"
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="queryInfo.page"
            @current-change="changePage"
          ></el-pagination>
        </el-card>
      </div>

      <!-- 导出对话框 -->
      <el-dialog title="导出信息" :visible.sync="dialogVisible" width="30%">
        <!-- 下拉框和输入框 -->
        <ul class="iptUl">
          <li class="iptList">
            <div class="iptTxt"><span style="color: red">*</span>文件名称：</div>
            <div class="iptBox">
              <el-input placeholder="请输入文件的名称" v-model="value" clearable>
              </el-input>
            </div>
          </li>
          <li class="iptList">
            <div class="iptTxt"><span style="color: red">*</span>下载类型：</div>
            <div class="iptBox">
              <el-select v-model="value1" placeholder="请选择">
                <el-option
                  v-for="item in optionsA"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </li>
          <li class="iptList" v-show="timeShow">
            <div class="iptTxt"><span style="color: red">*</span>时间段：</div>
            <div class="iptBox">
              <el-date-picker
                v-model="value2"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </div>
          </li>
        </ul>
        <!-- 下拉框和输入框 -->

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="blueInfo" @click="addData()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 导出对话框 -->
    </el-card>
  </div>
</template>

<script>
import Vue from "vue";
import DateSearch from "@/components/DateSearch";
import HighCharts from "highcharts";

export default {
  data() {
    return {
      id:this.$store.state.ele_history_id,
      // 动态表头
      tableHead: [],
      // 数据
			eleValChart: [],
      eleValTable: [],
      eleNameTable:[],
      eleIndexTable:[],
      eleNameChart:[],
      eleIndexChart:[],
      total: null,
      queryInfo: {
        begin: "",
        end: "",
        page: 1,
        pageall: 1,
        pest_name: "",
        manualpage: 1,
      },

      d_id:'',
      allPest: [],
      options: {},
      options2: {},
      options3: {},
      options4: {},
      equip_name: "",
      worms: [],
      // 状态信息
      equipStatus: {},

      // 自动统计动态表头
      tableHeadTxt: [
        ["害虫名称", "name"],
        ["害虫数量", "sum"],
        // ["统计时间", "upl_time"]
      ],
      tableHeadTxtAll: [
        ["害虫名称", "name"],
        ["害虫数量", "sum"],
        ["统计时间", "upl_time"],
        // ['操作', 'operationData'],
      ],
      // 表格数据
      tableData: [],
      tableDataB: [],
      tableDataAll: [],
      tableDataAllB: [],
      index: 0,
      tableDataA: [],
      timeRange: "",
      totalall: null,
      viewSwitch: 1,
      viewSwitch2: "",
      viewSwitch23: "",
      // 手动统计表头
      tableHeadTxtA: [
        ["害虫名称", "pest_name"],
        ["害虫数量", "pest_num"],
        ["作物种类", "crop_name"],
        ["虫害阶段", "pest_case"],
        ["统计时间", "add_time"],
        // ["统计时间", "upl_time"]
      ],
      dropDown: [], //手动统计害虫名称下拉数据
      chartsLineShow: true, //判断折线图是否为空
      chartsPieShow: true, //判断统计图是否为空
      pestTit: "详细信息",
      flag: 1,
      dataSwitchType: 1, //0代表统计信息，1代表详细信息
      //导出弹框
      dialogVisible: false,
      optionsA: [
        {
          value: "选项1",
          label: "全部",
        },
        {
          value: "选项2",
          label: "时间段",
        },
      ],
      value: "", //文件名称
      value1: "", //下载类型
      value2: "", //时间段
      timeShow: false, //选择时间
      imgListData: "", //表格图片
      recognitionImage: [], //图片数组
      AxiosImageList: [],
      imageListtData: false,
      //害虫资料
      dialogFormVisible: false,
      popUpData: {}, //虫害数据
      isClick: true, //点赞开关
      //图片框
      discernVisible: false,
      discernVisibleA: false, //自动统计-统计信息
      enlargement: false, //识别弹框放大
      enlargementImg: true, //图片样式控制
      loading: false, //加载
      recognitionData: {}, //害虫数据对象
      htmlData: "",
      iconShow: false, //icon
      iconIf: true,
      iconShowA: false,

      // 测试测试
      readOnly: true, //是否只读
      currentImage: "", //图片标注的图片
      imagepopShow: true, //是否为手动标注
      uuid: "0da9130",
    };
  },
  watch: {
    viewSwitch(val) {
      // console.log(val)
      this.btnSelected = "2";
    },
    value1(val) {
      if (val == "选项2") {
        this.timeShow = true;
      }
      if (val == "选项1") {
        this.timeShow = false;
      }
    },
    dialogVisible(val) {
      if (val == false) {
        this.value = "";
        this.value1 = "";
        this.value2 = "";
        this.timeShow = false;
      }
    },
    discernVisible(val) {
      if (val == false) {
        var swiper = new Swiper(".swiper-container", {
          initialSlide: 0,
          observer: true, //修改swiper自己或子元素时，自动初始化swiper
          observeParents: true, //修改swiper的父元素时，自动初始化swiper
          prevButton: ".swiper-button-prev",
          nextButton: ".swiper-button-next",
        });
        swiper.destroy(true, true);
      }
    },
    discernVisibleA(val) {
      if (val == false) {
        // this.tagName = "";
        this.setdataNum = {};
        this.$refs["aiPanel-editor"].getMarker().clearData();
      }
    },
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 设置hightcharts配置
    refreshData() {
      HighCharts.setOptions({
        // 所有语言文字相关配置都设置在 lang 里
        lang: {
          resetZoom: "刷新",
          resetZoomTitle: "重置缩放比例",
        },
      });
    },

    //子向父传值
    dateChange(data) {
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.getTableList();
      this.getChartList();
    },
    //获取表格数据
    getTableList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=weather.weather.sf_data",
        data: this.qs.stringify({
          device_id: this.id,
          page:this.queryInfo.page
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.total = res.data.data.nums;
          var eleNumArr = res.data.data.conf.eleNum.split('/');
          var eleNameArr = res.data.data.conf.eleName.split('/');
          this.tableHead=[{ label: '日期', property: 'time' }]
          this.eleNameTable = []; //要素名称
          this.eleIndexTable = []; //要素下标，便于查找要素值
          eleNumArr.forEach((item,index) => {
            if(item!=100){
              this.eleNameTable.push(eleNameArr[index]);
              this.eleIndexTable.push(index)
              this.tableHead.push({
                label: eleNameArr[index],
                property: 'e'+index
              })
            }
          });

          // 循环要素值
          this.eleValTable = [];
          var dat = res.data.data.dat;
          for(var i = 0;i<dat.length;i++){
            var device_status = eval('('+dat[i].device_status+')');
            var tableJson={
              time:this.formatTime(dat[i].uptime * 1000)
            }
            this.eleIndexTable.forEach((item,index) => {
              var ekey = 'e'+(item+1);
              if(device_status[ekey]!=32767){
                tableJson['e'+item]=device_status[ekey]
              }else{
                tableJson['e'+item]='N/A'
              }
              if(index==this.eleIndexTable.length-1){
                this.eleValTable.push(tableJson)
              }
            })
          }
        }
      });
    },
    getChartList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=weather.weather.sf_data_chart",
        data: this.qs.stringify({
          device_id: this.id,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          var eleNumArr = res.data.data.conf.eleNum.split('/');
          var eleNameArr = res.data.data.conf.eleName.split('/');
          this.eleNameChart = []; //要素名称
          this.eleIndexChart = []; //要素下标，便于查找要素值
          eleNumArr.forEach((item,index) => {
            if(item!=100){
              this.eleNameChart.push(eleNameArr[index]);
              this.eleIndexChart.push(index)
            }
          });

          // 循环要素值
          this.eleValChart = [];
          var dat = res.data.data.dat;
          for(var i = 0;i<dat.length;i++){
            var device_status = eval('('+dat[i].device_status+')');
            var time = dat[i].uptime * 1000+8*60*60*1000;
            this.eleIndexChart.forEach((item,index) => {
              var ekey = 'e'+(item+1);
              if(!this.eleValChart[index]){
                this.eleValChart[index]=[]
              }
              if(device_status[ekey]!=32767){
                this.eleValChart[index].push(
                  [time,device_status[ekey]]
                )
              }
            })
            if(i==dat.length-1){
              this.renderChart()
            }
          }
        }
      });
    },
    renderChart(){
      var dat = [];
      for(var i = 0;i<this.eleValChart.length;i++){
        dat.push({
          type: 'spline',
          name: this.eleNameChart[i],
          data: this.eleValChart[i],
        })
      }
      this.options = {
        chart: {
          zoomType: "x",
        },
        title: {
          text: "历史数据",
          align: "left",
        },
        subtitle: {
          text: "",
        },
        xAxis: {
          crosshair: true, //十字基准线
          type: "datetime",
          dateTimeLabelFormats: {
            //根据时间间距X轴自动显示哪种格式
            millisecond: "%H:%M:%S",
            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: "center",
          verticalAlign: "top",
        },
        plotOptions: {
          series: {
            label: {
              connectorAllowed: false,
            },
            pointStart: 2010,
          },
        },
        series: 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",
                },
              },
            },
          ],
        },
      };
    },
    
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.getTableList();
    },
  },
  components: {
    DateSearch,
  },
};
</script>

<style lang='less' scoped>
.box-card {
  position: relative;
}
.equipInfo {
  .equipMsg {
    font-size: 14px;
    color: #3d3d3d;
    span {
      margin-left: 5px;
    }
  }
  .dateBox {
    display: flex;
    .viewSwitch {
      margin-left: 10px;
    }
  }
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 10px;
}

.charts{
  height: 423px;
}


</style>