<!--  -->
<template>
  <div class="hisbox">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p @click="backtrack" style="cursor: pointer">
          <i class="el-icon-back"></i>
          <span>返回</span>
        </p>
        <p>历史数据</p>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <div class="search_left">
          <div
            :class="tabtable == 1 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="tabtable = 1"
          >
            表格
          </div>
          <div
            :class="tabtable == 2 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="tabtable = 2"
          >
            图表
          </div>
          <div class="timebtn timebtn1" @click="deriveData">导出</div>
          <div class="timebtn timebtn1" @click="refresh">刷新</div>
        </div>
        <div class="search_right">
          <div
            :class="timeindex == 1 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="empty(1), (flag = true)"
          >
            近一天
          </div>
          <div
            :class="timeindex == 2 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="empty(2), (flag = true)"
          >
            近七天
          </div>
          <div
            :class="timeindex == 3 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="empty(3), (flag = true)"
          >
            近一月
          </div>
          <div
            :class="timeindex == 4 ? 'timebtn timebtn1' : 'timebtn timebtn2'"
            @click="empty(4), (flag = true)"
          >
            近三月
          </div>
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            @change="timechange"
          >
          </el-date-picker>
        </div>
      </div>
    </div>
    <div class="baselistbox_table">
      <div v-show="tabtable == 1">
        <el-table :data="hisData" stripe style="width: 100%" height="530">
          <el-table-column
            v-for="(item, index) in tableHead"
            :key="index"
            width="160px"
            :label="item.label"
            :prop="item.property"
          >
            <template slot-scope="scope">{{
              scope.row[scope.column.property]
            }}</template>
          </el-table-column>
          <el-table-column label="" prop=""></el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next,sizes,jumper"
            :total="totalNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="page_size"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-size.sync="page"
            :key="pagekey"
          >
          </el-pagination>
        </div>
      </div>
      <div v-show="tabtable == 2">
        <el-row :gutter="10">
          <el-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            v-for="(item, index) in echartOptions"
            :key="index"
          >
            <el-card class="box-card" style="margin-bottom: 15px">
              <highcharts :options="item"></highcharts>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 导出对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="导出信息"
      :visible.sync="dialogVisible"
      width="580px"
    >
      <!-- <span>这是一段信息</span> -->

      <!-- 下拉框和输入框 -->
      <ul class="iptUl">
        <li class="iptList">
          <div class="iptTxt"><span style="color: red">*</span>文件名称</div>
          <div class="iptBox">
            <el-input
              placeholder="请输入文件的名称"
              size="mini"
              v-model="value"
              clearable
            >
            </el-input>
          </div>
        </li>
        <li class="iptList">
          <div class="iptTxt">下载类型</div>
          <div class="iptBox">
            <el-select v-model="value1" size="mini" placeholder="请选择">
              <el-option
                v-for="item in optionsA"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </li>
      </ul>
      <!-- 下拉框和输入框 -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="addData()" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import Highcharts from "highcharts";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      timeindex: 1,
      start_time: "",
      end_time: "",
      time: "",
      hisData: [],
      tableHead: [],
      totalNum: 10,
      page: 1,
      page_size: 10,
      pagekey: 1,
      dialogVisible: false,
      value: "",
      value1: "",
      optionsA: [
        {
          value: "选项1",
          label: "全部",
        },
        {
          value: "选项2",
          label: "时间段",
        },
      ],
      flag: false,
      tabtable: 1,
      echartOptions: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    backtrack() {
      this.$router.go(-1);
    },
    empty(index) {
      this.timeindex = index;
      this.end_time = Math.floor(+new Date() / 1000);
      var time = new Date();
      if (index == 1) {
        this.start_time = this.end_time - 24 * 60 * 60;
      } else if (index == 2) {
        this.start_time = this.end_time - 7 * 24 * 60 * 60;
      } else if (index == 3) {
        var mouth = time.getMonth();
        this.start_time = Math.floor(time.setMonth(mouth - 1) / 1000);
        // console.log(time2)
      } else if (index == 4) {
        var mouth = time.getMonth();
        this.start_time = Math.floor(time.setMonth(mouth - 3) / 1000);
      }
      console.log(this.start_time);
      this.page = 1;
      this.pagekey = Math.random() * 10 + 1;
      this.getHisDataList();
      this.getEchartsHisDataList();
    },
    timechange(e) {
      console.log(e);
      this.flag = true;
      if (e) {
        this.start_time = Math.floor(+new Date(e[0]) / 1000);
        this.end_time = Math.floor(+new Date(e[1]) / 1000);
        this.page = 1;
        this.pagekey = Math.random() * 10 + 1;
        this.getHisDataList();
        this.getEchartsHisDataList();
      } else {
        this.empty(1);
      }
    },
    // 导出
    deriveData() {
      this.dialogVisible = true;
    },
    //导出数据确定
    addData() {
      var that = this;
      if (that.value == "" || that.value1 == "") {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message({
            message: "请将必填项填写完整",
            type: "warning",
            duration: 1500,
          });
        }
      } else {
        var begin = "";
        var end = "";
        console.log(this.value1);
        if (that.value1 == "选项2") {
          begin = this.start_time;
          end = this.end_time;
        } else {
          begin = "";
          end = "";
        }
        console.log(begin, end);
        window.location.href =
          this.$http +
          "/api/qxz_data_export?device_id=" +
          this.$route.params.id +
          "&filename=" +
          that.value +
          "&begin=" +
          begin +
          "&end=" +
          end +
          "&device_type=3";
      }
    },
    refresh() {
      //历史数据刷新按钮
      // console.log(this.$route.params.id)
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.send_control.get_device_config",
        data: this.qs.stringify({
          device_type_id: 5,
          d_id: this.$route.params.d_id,
          control_type: "data",
        }),
      }).then((res) => {
        // console.log(res)
        if (res.data.message == "") {
          // this.refreshload = true;
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message({
              message: "刷新成功",
              type: "success",
            });
          }
          // this.$message.success("刷新成功");
          setTimeout(() => {
            this.getHisDataList();
            this.getEchartsHisDataList();
            // this.refreshload = false;
          }, 2000);
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message({
              message: "刷新失败",
              type: "success",
            });
          }
        }
      });
    },
    //获取历史数据
    getHisDataList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=weather.weather.qxz_detail",
        data: this.qs.stringify({
          start_time: this.start_time,
          end_time: this.end_time,
          page: this.page,
          page_size: this.page_size,
          device_id: this.$route.params.id,
        }),
      }).then((res) => {
        this.isRainFall = res.data.data.rainFall;
        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]) {
              console.log(conf[i]);
              let arr = conf[i].split("#");
              console.log(arr);
              if (arr[1]) {
                obj.label = `${arr[0]}(${arr[1]})`;
              } else {
                obj.label = `${arr[0]}`;
              }
              obj.property = i;
              arr1.push(obj);
            }
          }
          // console.log(arr1);

          if (arr1.length == 1 && arr1[0].label == "日期") {
            this.hisData = [];
          } else {
            // 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; // 表格数据
            var j = 0;
            var list = [];
            // 循环要素数据有多少定义表头显示多少
            for (let a in data[0].dat) {
              if (data[0].dat[a] !== "") {
                j++;
              }
            }
            for (var i = 0; i < arr1.length; i++) {
              if (j >= i) {
                list.push(arr1[i]);
              }
            }
            this.tableHead = list; // 表格头数据
            this.totalNum = Number(res.data.data.nums);
          }
        } else {
          this.hisData = [];
          if (!this.flag) {
            if (this.timeindex != 4) {
              this.empty(this.timeindex + 1);
            }
          }
        }
      });
    },
    handleSizeChange(e) {
      this.page = 1;
      this.pagekey = Math.random() * 10 + 1;
      this.page_size = e;
      this.getHisDataList();
    },
    handleCurrentChange(e) {
      this.page = e;
      this.getHisDataList();
    },
    //获取图表历史数据
    getEchartsHisDataList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=weather.weather.qxz_data_chart",
        data: this.qs.stringify({
          begin: this.start_time,
          end: this.end_time,
          device_id: this.$route.params.id,
        }),
      })
        .then((res) => {
          console.log(res.data.data);
          this.echartsFn(res.data.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    echartsFn(data) {
      let conf = data.conf;
      let eData = data.data;
      let ChartData = [];
      console.log(conf);
      console.log(eData);
      console.log(eData.length);
      if (conf && eData && eData.length > 0) {
        this.isEchartData = true;
        for (let i in conf) {
          if (conf[i]) {
            //判断是否有值
            ChartData.push({
              name: i,
              tit: conf[i].split("#")[0],
              unit: conf[i].split("#")[1],
              dat: [],
            });
          }
        }
        for (let m of eData) {
          //m是对象
          for (let n in m.dat) {
            //dat是对象 n是key
            for (let j of ChartData) {
              //j是对象
              if (j.name == n && m.dat[n].split("#")[0] != "-99.99") {
                j.dat.push([
                  m.time * 1000 + 8 * 3600000,
                  Number(m.dat[n].split("#")[0]),
                ]);
              }
            }
          }
        }
      } else {
        this.isEchartData = false;
      }
      console.log(ChartData);

      // 判断是否有数据
      if (ChartData.length !== 0) {
        this.isEchartData = true;
        this.echartOptions = ChartData.map((item) => {
          return this.OptionFn(item);
        });
      } else {
        this.isEchartData = false;
      }
    },
    OptionFn(item) {
      return {
        title: {
          text: item.tit,
          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",
          },
        },
        yAxis: {
          title: { text: "" },
        },
        legend: {
          // layout: 'vertical',
          align: "right",
          verticalAlign: "top",
        },
        plotOptions: {
          series: {
            label: {
              connectorAllowed: false,
            },
            pointStart: 2010, //该参数定义了数据点的起点
          },
        },
        series: [
          {
            name: item.name,
            data: item.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>",
          pointFormatter: function () {
            return item.tit + "：" + this.y + item.unit;
          },
        },
        responsive: {
          rules: [
            {
              condition: {
                maxWidth: 500,
              },
              chartOptions: {
                legend: {
                  layout: "horizontal",
                  align: "center",
                  verticalAlign: "bottom",
                },
              },
            },
          ],
        },
      };
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.end_time = Math.floor(+new Date() / 1000);
    this.start_time = this.end_time - 24 * 60 * 60;
    this.getHisDataList();
    this.getEchartsHisDataList();
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.hisbox {
  width: 100%;
  height: 100%;
  .baselistbox_top {
    width: 100%;
    //   height: 130px;
    background-color: #fff;
    border-radius: 10px;
    .baselistbox_top_title {
      width: 100%;
      height: 65px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 25px;
      p:first-child {
        font-size: 14px;
      }
      p:last-child {
        font-size: 18px;
        font-weight: 700;
        margin-left: 20px;
      }
    }
    .baselistbox_top_line {
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
    }
    .baselistbox_top_search {
      width: 100%;
      // height: 68px;
      padding: 20px;
      box-sizing: border-box;
      line-height: 28px;
      display: flex;
      justify-content: space-between;
      .search_left {
        display: flex;
        .timebtn {
          width: 68px;
          height: 26px;
          border: 1px solid #4f71ff;
          text-align: center;
          border-radius: 3px;
          font-size: 14px;
          margin-right: 20px;
          line-height: 26px;
          cursor: pointer;
        }
        .timebtn1 {
          background-color: #4f71ff;
          color: #fff;
        }
        .timebtn2 {
          color: #4f71ff;
        }
      }
      .search_right {
        display: flex;
        .timebtn {
          width: 68px;
          height: 26px;
          border: 1px solid #4f71ff;
          text-align: center;
          border-radius: 3px;
          font-size: 14px;
          margin-right: 20px;
          line-height: 26px;
          cursor: pointer;
        }
        .timebtn1 {
          background-color: #4f71ff;
          color: #fff;
        }
        .timebtn2 {
          color: #4f71ff;
        }
      }
    }
  }
  .baselistbox_table {
    width: 100%;
    // height: calc(100% - 140px);
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;
    border-radius: 10px;
    /deep/.el-table__header {
      th {
        background-color: #f1f1f3;
      }
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      /deep/.el-pager {
        .active {
          background-color: #4f71ff !important;
        }
      }
      /deep/.el-input__inner:hover {
        border-color: #4f71ff;
      }
    }
  }
}
.iptList {
  display: flex;
  margin: 32px 0;
}
.iptTxt {
  text-align: right;
  width: 20%;
  margin: 0 8px 0 0;
  display: inline-block;
  line-height: 28px;
}
.iptBox {
  width: 40%;
}
</style>