<template>
  <div style="cursor: default">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title" style="cursor: pointer">
        <p @click="goBackPage()" 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="equipInfo">
          <div class="detail">
            <span>设备ID：{{ id }}</span>
            <span>设备名称：{{ $route.query.name }}</span>
            <span>位置：{{ $route.query.address }}</span>
            <span>已培养时间(h)：{{ staytime }}</span>
          </div>
          <DateSearch
            ref="timeCirculation"
            @dateChange="dateChange"
            @timeScreen="timeScreen"
          ></DateSearch>
        </div>
        <div class="ctrl-check">
          <el-button
            type="primary"
            size="mini"
            @click="$throttle(refresh, 2000)"
            >刷新</el-button
          >
        </div>
      </div>
    </div>
    <el-row :gutter="20" v-loading="refreshload" style="margin-top: 10px">
      <el-col :md="24" :lg="12">
        <el-card class="box-card" id="box-card1">
          <highcharts :options="option1"></highcharts>
        </el-card>
      </el-col>
      <el-col :md="24" :lg="12">
        <el-card class="box-card" id="box-card2">
          <highcharts :options="option2"></highcharts>
        </el-card>
      </el-col>
    </el-row>
    <div class="dataTableSearch">
      <el-button type="primary" size="mini" @click="deriveData()"
        >导出</el-button
      >
    </div>
    <el-card class="box-card" v-loading="refreshload">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column
          v-for="(item, index) in tableHeadTxt2"
          :key="index"
          :prop="item[1]"
          :label="item[0]"
          :show-overflow-tooltip="true"
          :width="setWidth(item)"
        >
          <template slot-scope="scope">{{
            scope.row[scope.column.property]
          }}</template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,sizes,jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          v-if="tableData.length"
          :current-page="queryInfo.page"
          @size-change="handleSizeChange"
          @current-change="changePage"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 导出对话框 -->
    <el-dialog 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="请输入文件的名称"
              v-model="value"
              size="mini"
              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" 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>
import DateSearch from "@/components/DateSearch";
import HighCharts from "highcharts";
import HighchartsNoData from "highcharts/modules/no-data-to-display";
HighchartsNoData(HighCharts);
import { Loading } from "element-ui";
import Circulation from "../../../static/js/equipState_dict.json";

export default {
  data() {
    return {
      user_tag: null, //1超级管理员，2经销商，3农林政府单位，4普通用户，5销售用户
      id: this.$route.params.e_id,
      staytime: "", //已培养时间
      btnSelected: "",
      timeRange: "",
      lineTime: "",
      tableHeadTxt2: [
        ["设备开关", "on_off"],
        ["环境温度(°C)", "at"],
        ["环境湿度(%)", "ah"],
        ["保温仓设定温度(°C)", "set_temp"],
        ["保温仓当前温度(°C)", "pre_temp"],
        ["电池状态", "batStatus"],
        ["雨控状态", "rps"],
        // ["摄像头状态", "usb_sta"],
        ["工作状态", "work_sta"],
        // ["电压(V)", "v_bat"],
        // ["电压(V)", "vbat"],
        // ["电流(mA)", "current"],
        // ["信号强度", "csq"],
        ["设备版本", "dver"],
        ["上报时间", "addtime"],
      ],
      queryInfo: {
        begin: "",
        end: "",
        e_id: this.$route.params.e_id,
        d_id: this.$route.params.d_id,
        page: 1,
        page_size: 10,
      },
      // 表格数据
      tableData: [],
      total: 0,
      //导出弹框
      dialogVisible: false,
      optionsA: [
        {
          value: "选项1",
          label: "全部",
        },
        {
          value: "选项2",
          label: "时间段",
        },
        // {
        //   value: "选项2",
        //   label: "时间段",
        // },
      ],
      value: "", //文件名称
      value1: "", //下载类型
      value2: "", //时间段
      timeShow: false, //选择时间
      loadingInstance1: {},
      loadingInstance2: {},
      ChartData: [
        {
          name: "温度（°C）",
          dat: [],
        },
        {
          name: "湿度（RH）",
          dat: [],
        },
        {
          name: "保温仓温度（°C）",
          dat: [],
        },
      ],
      equipStateDict: {}, //
      timeScreenData: null,
      //保存一个标识，用来区分是点击还是自动获取
      sign: null,
      refreshload: false,
    };
  },
  created() {
    this.user_tag = localStorage.getItem("user_tag");
  },
  mounted() {
    // this.getChartDataList();
    // this.getHisDataList();
    this.equipStateDict = Circulation;
    this.refreshData();
    this.loadingInstance1 = Loading.service({
      fullscreen: false,
      target: document.getElementById("box-card1"),
    });
    this.loadingInstance2 = Loading.service({
      fullscreen: false,
      target: document.getElementById("box-card2"),
    });
    console.log(this.ChartData);
  },
  computed: {
    userType: function () {
      //获取用户类型
      return window.sessionStorage.getItem("myuser_type");
    },
    option1() {
      return {
        chart: {
          zoomType: "x",
        },
        title: {
          text: "环境温湿度",
          align: "left",
        },
        lang: {
          noData: "暂无数据",
        },
        noData: {
          style: {
            fontWeight: "bold",
            fontSize: "15px",
            color: "#303030",
          },
        },
        subtitle: {
          text: "",
        },
        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: this.ChartData[0].name,
            data: this.ChartData[0].dat,
          },
          {
            name: this.ChartData[1].name,
            data: this.ChartData[1].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",
                },
              },
            },
          ],
        },
      };
    },
    option2() {
      return {
        chart: {
          zoomType: "x",
        },
        title: {
          text: "保温仓温度",
          align: "left",
        },
        lang: {
          noData: "暂无数据",
        },
        noData: {
          style: {
            fontWeight: "bold",
            fontSize: "15px",
            color: "#303030",
          },
        },
        subtitle: {
          text: "",
        },
        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: this.ChartData[2].name,
            data: this.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",
                },
              },
            },
          ],
        },
      };
    },
  },
  methods: {
    // 设置hightcharts配置
    refreshData() {
      HighCharts.setOptions({
        // 所有语言文字相关配置都设置在 lang 里
        lang: {
          resetZoom: "刷新",
          resetZoomTitle: "重置缩放比例",
        },
      });
    },
    //获取折线数据
    getChartDataList() {
      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.queryInfo.d_id,
          start_time: this.queryInfo.begin,
          end_time: this.queryInfo.end,
        }),
      }).then((res) => {
        console.log(this.sign + "这是变量");
        console.log(this.queryInfo.begin + "这是开始时间");
        if (res.data.data.length == 0 && this.timeScreenData == null) {
          if (this.sign == this.queryInfo.begin || this.sign == null) {
            this.$refs.timeCirculation.say();
            console.log("这是自动的");
          } else {
            console.log("这是点击的");
          }
          this.sign = this.queryInfo.begin; //保存一个标识，用来区分是点击还是自动获取
        }
        this.ChartData[0].dat = [];
        this.ChartData[1].dat = [];
        this.ChartData[2].dat = [];
        if (res.data.message == "" && res.data.data.length !== 0) {
          var data = res.data.data;
          for (let item of data) {
            if (item.new_tem) {
              this.ChartData[0].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.new_tem),
              ]);
            } else {
              item.temperature !== "" &&
                this.ChartData[0].dat.unshift([
                  item.addtime * 1000 + 8 * 3600000,
                  Number(item.temperature),
                ]);
            }
            if (item.new_hum) {
              this.ChartData[1].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.new_hum),
              ]);
            } else {
              item.humidity !== "" &&
                this.ChartData[1].dat.unshift([
                  item.addtime * 1000 + 8 * 3600000,
                  Number(item.humidity),
                ]);
            }
            item.others !== "" &&
              this.ChartData[2].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.others),
              ]);
          }
        }
        this.loadingInstance1.close();
        this.loadingInstance2.close();
      });
    },
    // 当使用日期筛选
    timeScreen(data) {
      this.timeScreenData = data;
    },
    //获取表格数据
    getHisDataList() {
      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.queryInfo.e_id,
          start_time: this.queryInfo.begin,
          end_time: this.queryInfo.end,
          page: this.queryInfo.page,
          page_size: this.queryInfo.page_size,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.total = res.data.data.counts;
          var data = res.data.data.data;
          if (data.length > 0) {
            this.staytime = data[0].d_h_t.staytime; //已培养时间
            this.tableData = [];
            for (var i = 0; i < data.length; i++) {
              var dht = data[i].d_h_t;
              dht.addtime = this.formatTime(dht.addtime * 1000);
              dht.on_off = this.equipStateDict.ds.value[dht.ds]; //设备开关
              dht.batStatus =
                this.equipStateDict.batStatus.value[dht.batStatus]; //电压状态
              dht.rps = this.equipStateDict.rps.value[dht.rps]; //雨控状态
              dht.work_sta = this.equipStateDict.work_sta.value[dht.work_sta]; //摄像头状态
              console.log(this.equipStateDict.work_sta.value[dht.work_sta]);
              if (dht.new_hum) {
                dht.ah = dht.new_hum;
              }
              if (dht.new_tem) {
                dht.at = dht.new_tem;
              }
              // 保温仓设定温度
              if (dht.set_temp == undefined) {
                dht.set_temp = 0;
              }
              // 保温仓当前温度
              if (dht.pre_temp == undefined) {
                dht.pre_temp = 0;
              }
              // 摄像头状态
              if (dht.usb_sta == undefined) {
                dht.usb_sta = "暂无";
              }
              this.tableData.push(dht);
            }
          } else {
            this.tableData = [];
          }
          console.log(this.tableData);
        }
      });
    },
    dateChange(data) {
      this.queryInfo.page = 1;
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.getHisDataList();
      this.getChartDataList();
    },
    handleSizeChange(e) {
      this.queryInfo.page = 1;
      this.queryInfo.page_size = e;
      this.getHisDataList();
    },
    changePage(val) {
      this.queryInfo.page = val;
      this.getHisDataList();
    },
    setWidth(item) {
      if (item[1] == "addtime") {
        return 180 + "px";
      }
    },
    refresh() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.send_control.get_device_config",
        data: this.qs.stringify({
          device_type_id: 7,
          d_id: this.queryInfo.d_id,
          control_type: "data",
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.refreshload = true;
          setTimeout(() => {
            this.getChartDataList();
            this.getHisDataList();
            if (document.getElementsByClassName("el-message").length == 0) {
              this.$message.success("刷新成功");
            }
            this.refreshload = false;
          }, 2000);
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.err("刷新失败");
          }
        }
      });
    },
    //返回上一页
    goBackPage() {
      this.$router.go(-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.queryInfo.begin;
          end = this.queryInfo.end;
        } else if (that.value1 == "选项1") {
          begin = "";
          end = "";
        }
        console.log(begin);
        var username = localStorage.getItem("username");
        console.log(username);
        // console.log(window.location.origin)
        window.location.href =
          // this.$deriveData +
          this.$http+
          // "http://192.168.1.77:8002"+
          "/api/cbd_export?device_id=" +
          this.$route.params.d_id +
          "&filename=" +
          that.value +
          "&start_time=" +
          begin +
          "&end_time=" +
          end +
          "&device_type=7" +
          "&username=" +
          username;
      }
    },
  },
  components: {
    DateSearch,
  },
  watch: {
    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;
      }
    },
  },
};
</script>

<style lang='less' scoped>
.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;
      margin-right: 20px;
    }
    p:last-child {
      font-size: 18px;
      font-weight: 700;
    }
  }
  .baselistbox_top_line {
    width: 100%;
    height: 1px;
    background-color: #f2f2f2;
  }
  .baselistbox_top_search {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    line-height: 28px;
  }
}
.equipInfo {
  display: flex;
  margin-top: 10px;
  margin-bottom: 8px;
  justify-content: space-between;
  .detail {
    font-size: 14px;
    color: #666;
    span {
      margin-right: 20px;
    }
  }
}
.dataTableSearch {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
.el-input__inner {
  width: 222px !important;
}
.ctrl-check {
  margin-bottom: 20px;
}

.iptList {
  display: flex;
  margin: 15px 0 15px 0;
}
.iptTxt {
  text-align: right;
  width: 20%;
  margin: 0 5% 0 0;
  display: inline-block;
}
.iptBox {
  width: 40%;
}
.pagination {
  width: 100%;
  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;
  }
}
// 表格文字居中
/deep/.el-table th > .cell {
  text-align: center;
}

/deep/.el-table .cell {
  text-align: center;
}
/deep/.el-table__header {
  th {
    background-color: #f1f1f3;
  }
}
</style>