<template>
  <div style="cursor: default">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>防治系统</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/index/scd' }"
        >杀虫灯</el-breadcrumb-item
      >
      <el-breadcrumb-item>数据详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button type="success" size="small" @click="goBackPage()"
      ><i class="el-icon--left el-icon-d-arrow-left"></i>返回</el-button
    >
    <div class="equipInfo">
      <div class="equipMsg">
        <span>设备ID：{{ id }}</span>
        <span>设备名称：{{ equipStatus.equip_name || "无" }}</span>
        <span>位置：{{ equipStatus.lng }}</span>
      </div>
      <DateSearch @dateChange="dateChange"></DateSearch>
    </div>
    <div class="ctrl-check">
      <el-button type="primary" size="mini" @click="$throttle(refresh,2000)">刷新</el-button>
    </div>
    <!-- 统计图 -->
    <div v-if="viewSwitch">
      <div>
        <el-row :gutter="10">
          <el-col :md="24" :lg="14">
            <el-card class="box-card" id="box-card1">
              <div class="charts">
                <highcharts :options="option1"></highcharts>
              </div>
            </el-card>
          </el-col>
          <el-col :md="24" :lg="10">
            <el-card class="box-card" id="box-card2">
              <div class="pie">
                <highcharts :options="option2"></highcharts>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <div class="dataTableSearch">
          <div>
            <el-button type="primary" size="mini" @click="deriveData()"
              >导出</el-button
            >
          </div>
        </div>
      </div>
      <el-card class="box-card">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column
            v-for="(item, index) in tableHeadTxt"
            :key="index"
            :prop="item[1]"
            :label="item[0]"
            :width="setWidth(item)"
          >
            <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>
      </el-card>

      <!-- 导出对话框 -->
      <el-dialog title="导出信息" :visible.sync="dialogVisible" width="30%">
        <!-- <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"
                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="primary" @click="addData()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 导出对话框 -->
    </div>
  </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";
export default {
  data() {
    return {
      id: this.$route.params.e_id,
      lineTime: "",
      dataTime: "",
      worms: [
        {
          value: 1,
          label: "蛾子",
        },
        {
          value: 2,
          label: "蚊子",
        },
      ],
      // 状态信息
      equipStatus: {},
      // 统计图表信息
      equipChartData: [],
      //总数据条数
      total: 0,
      // 动态表头
      tableHeadTxt: [
        ["设备开关", "ds"],
        ["工作状态", "ws"],
        ["灯管状态", "tbs"],
        ["雨控状态", "rps"],
        ["温控状态", "tps"],
        ["倾倒状态", "dps"],
        ["定时(h)", "tt"],
        ["电击次数", "ct"],
        ["温度(°C)", "at"],
        ["湿度(%)", "ah"],
        ["充电电压(v)", "cv"],
        ["电池电压(v)", "bv"],
        ["上报时间", "addtime"],
      ],
      // 表格数据
      tableData: [],
      timeRange: "",
      queryInfo: {
        begin: "",
        end: "",
        e_id: this.$route.params.e_id,
        d_id: this.$route.params.d_id,
        page: 1,
      },
      viewSwitch: 1,
      viewSwitch2: 1,
      //图表实时否有数据
      isEchartData: true,
      //表格和图表按钮样式切换参数
      display: "0", //0代表表格、1代表图表
      displayView: true,
      // 表格和图表显示切换控制
      showControl: true,
      //echarts图表参数
      echartOptions: [],
      // 动态表头
      tableHead: [],
      // 表格数据
      hisData: [],
      //导出弹框
      dialogVisible: false,
      optionsA: [
        {
          value: "选项1",
          label: "全部",
        },
        {
          value: "选项2",
          label: "时间段",
        },
      ],
      value: "", //文件名称
      value1: "", //下载类型
      value2: "", //时间段
      timeShow: false, //选择时间
      loadingInstance1: {},
      loadingInstance2: {},
      ChartData: [
        {
          name: "温度（°C）",
          dat: [],
        },
        {
          name: "湿度（%）",
          dat: [],
        },
        {
          name: "击虫次数",
          dat: [],
        },
        {
          name:"充电电压",
          dat:[]
        },
         {
          name:"电池电压",
          dat:[]
        }
      ],
    };
  },
  mounted() {
    this.refreshData();
    this.loadingInstance1 = Loading.service({
      fullscreen: false,
      target: document.getElementById("box-card1"),
    });
    this.loadingInstance2 = Loading.service({
      fullscreen: false,
      target: document.getElementById("box-card2"),
    });
  },
  computed: {
    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,
          },
          {
            name: this.ChartData[3].name,
            data: this.ChartData[3].dat,
          },
          {
            name: this.ChartData[4].name,
            data: this.ChartData[4].dat,
          },
        ],
        colors: ["#f97000", "#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: 2,
          d_id: this.queryInfo.d_id,
          start_time: this.queryInfo.begin,
          end_time: this.queryInfo.end,
        }),
      }).then((res) => {
        if (res.data.message == "" && res.data.data.length !== 0) {
          var data = res.data.data;
            for (let item of data) {
              this.ChartData[0].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.temperature),
              ]);
              this.ChartData[1].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.humidity),
              ]);
              this.ChartData[2].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.others.ct),
              ]);
               this.ChartData[3].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.others.cv/1000),
              ]);
                this.ChartData[4].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.others.bv/1000),
              ]);
          }
        }
        this.loadingInstance1.close();
        this.loadingInstance2.close();
      });
    },
    //获取表格数据
    getHisDataList() {
      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.queryInfo.e_id,
          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 = [];
          if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
              var dht = data[i].d_h_t;
              dht.addtime = this.formatTime(dht.addtime * 1000);
              dht.ds = dht.ds == 0 ? "关" : "开";
              dht.rps = dht.rps == 0 ? "正常" : "雨控";
              dht.tps = dht.tps == 0 ? "正常" : "保护";
              dht.tbs = dht.tbs == 0 ? "正常" : "保护";
              dht.dps = dht.dps == 0 ? "正常" : "保护";
              dht.cv = dht.cv / 1000;
              dht.bv = dht.bv / 1000;
              switch (dht.ws) {
                case 0:
                  dht.ws = "待机";
                  break;
                case 1:
                  dht.ws = "工作";
                  break;
                case 2:
                  dht.ws = "充电";
                  break;
              }
              this.tableData.push(dht);
            }
          }
        }
      });
    },
    dateChange(data) {
      this.queryInfo.page = 1;
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.getHisDataList();
      this.getChartDataList();
    },
    //改变page
    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: 2,
          d_id: this.queryInfo.d_id,
          control_type: "data",
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.$message.success("刷新成功");
        } else {
          this.$message.err("刷新失败");
        }
      });
    },
    //返回上一页
    goBackPage() {
      this.$router.go(-1);
    },

    // 导出数据
    deriveData() {
      this.dialogVisible = true;
    },
    //导出数据确定
    addData() {
      var that = this;
      if (that.value == "" && that.value1 == "" && that.value2 == "") {
        this.$message({
          message: "请将必填项填写完整",
          type: "warning",
          duration: 1500,
        });
      } else if (
        that.value !== "" &&
        that.value1 == "选项2" &&
        that.value2 == ""
      ) {
        this.$message({
          message: "请填写导出时间段",
          type: "warning",
          duration: 1500,
        });
      } else if (
        that.value !== "" &&
        (that.value1 == "选项1" ||
          (that.value1 == "选项2" && that.value2 !== ""))
      ) {
        var begin = "";
        var end = "";
        if (that.value2) {
          begin = parseInt(new Date(that.value2[0]).getTime() / 1000);
          end = parseInt(new Date(that.value2[1]).getTime() / 1000);
        } else {
          begin = "";
          end = "";
        }
        window.location.href =
          this.$deriveData +
          "/api/cbd_export?device_id=" +
          that.$route.params.d_id +
          "&filename=" +
          that.value +
          "&start_time=" +
          begin +
          "&end_time=" +
          end +
          "&device_type=2";
      }
    },
  },
  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>
.box-card {
  position: relative;
}
.equipInfo {
  .equipMsg {
    font-size: 14px;
    color: #3d3d3d;
    span {
      margin-left: 5px;
    }
  }
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 8px;
}

.time-check {
  display: flex;
  justify-content: space-between;
  .el-input__inner {
    margin-left: 10px;
    width: 222px;
  }
  .viewSwitch {
    margin-left: 10px;
  }
}

.chartsSelect {
  text-align: right;
  position: absolute;
  z-index: 999;
  left: 0;
  right: 21px;
}
.charts,
.pie {
  height: 423px;
}
.equipStatus {
  display: flex;
  justify-content: center;
  margin: 10px 0;
  .equipIcon {
    margin-right: 14%;
  }
  .equipParams {
    min-width: 80px;
    line-height: 27px;
    p {
      color: #a6a6a6;
    }
  }
}

.dataTableSearch {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  .el-input__inner {
    width: 222px;
  }
}

.echarts {
  width: 100%;
  height: 300px;
}
.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%;
}
</style>