<template>
  <div id="showChart" class="public-custom-dialog show-chart">
    <div class="show-data-header">
      <div class="header-time">
        <div class="time-select">
          <el-select
            v-model="timeValue"
            placeholder="请选择"
            size="small"
            @change="selectChange"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div class="time-picker">
          <el-date-picker
            v-if="timeValue === '4'"
            v-model="pickerValue1"
            end-placeholder="结束日期"
            range-separator="至"
            size="small"
            start-placeholder="开始日期"
            type="datetimerange"
            @change="pickerChange"
          ></el-date-picker>
        </div>
      </div>
      <div class="eader-radio">
        <el-radio-group v-model="showType" size="small">
          <el-radio-button
            :disabled="showlistDisable"
            label="表格"
          ></el-radio-button>
          <el-radio-button
            :disabled="showchartDisable"
            label="图表"
          ></el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="show-data-body">
      <div
        v-show="showType === '图表'"
        id="chart"
        style="width:100%;height:400px;"
      ></div>
      <div v-show="showType === '表格'" class="list-container">
        <el-table
          :data="tableData"
          class="device-topic-list"
          style="width: 100%"
        >
          <el-table-column
            align="center"
            label="时间"
            prop="time"
            width="250"
          ></el-table-column>
          <el-table-column align="center" label="原始值" prop="value">
            <template slot-scope="scope">
              <div
                v-if="dialogData.funDataType === 'IMAGE'"
                class
                style="text-align: center;"
              >
                <el-image
                  :preview-src-list="[getIotFileUrl(scope.row.value)]"
                  :src="getIotFileUrl(scope.row.value)"
                  :title="dialogData.fileName"
                  style="width: 40px; height: 30px; margin: 5px;cursor: default;"
                ></el-image>
              </div>
              <div v-else>
                <span>{{ returnStr(scope.row.value) }}</span>
                <span
                  style=" cursor: default; position: relative; right: -10px; color: #3a8ee6;"
                  @click="copyOnClick(scope.row.value)"
                  >复制</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          v-show="tableData.length > 0"
          :disabled="loadMoredisable"
          class="load-more"
          size="small"
          style="margin-top: 10px; margin-left: 44%;"
          @click="loadMoreData"
          v-text="loadMoreText"
        ></el-button>
      </div>
    </div>
    <div class="show-data-footer">
      <el-pagination
        :current-page="page.page"
        :page-size="page.pageSize"
        :page-sizes="[100, 500, 1000]"
        :small="true"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getDataUploadListAt } from "@/api/iot/device";
import { getIotFileUrl } from "@/utils/hciot";
import moment from "moment";
export default {
  name: "RunStateTable",
  props: ["deviceKey", "deviceId", "dialogShow", "pro_type", "prodId"],
  data() {
    return {
      timeValue: "1",
      pickerValue1: "",
      tableData: [],
      loadMoreText: "已经全部加载",
      loadMoredisable: true,
      showType: "图表",
      showchartDisable: false,
      showlistDisable: false,
      showDialog: true,
      chart: null,
      row: {},
      page: {
        page: 1,
        pageSize: 100,
        total: 0
      },
      timeOptions: [
        {
          label: "1小时",
          value: "1"
        },
        {
          label: "24小时",
          value: "2"
        },
        {
          label: "7天",
          value: "3"
        },
        {
          label: "自定义",
          value: "4"
        }
      ]
    };
  },
  created() {
    this.timeValue = "1";
  },
  mounted() {
    /*this.$nextTick(function() {
      this.initDialog()
    })*/
  },
  watch: {
    /*dialogData(obj) {
      this.initDialog()
    }*/
  },
  methods: {
    getIotFileUrl,
    copyOnClick(val) {
      let self = this;
      this.$copyText(val).then(
        function() {
          self.$message({
            message: "复制成功",
            type: "success"
          });
        },
        function() {
          self.$message.error("复制失败");
        }
      );
    },
    returnStr(val) {
      if (val.length > 47) {
        return val.substring(0, 47) + "... ";
      } else {
        return val;
      }
    },
    drawLine() {
      let param = {};
      let time = {};
      switch (this.timeValue) {
        case "1":
          time.startTime = Date.parse(
            new Date(new Date().getTime() - 1 * 60 * 60 * 1000)
          );
          time.endTime = Date.parse(new Date());
          break;
        case "2":
          time.startTime = Date.parse(
            new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
          );
          time.endTime = Date.parse(new Date());
          break;
        case "3":
          time.startTime = Date.parse(
            new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000)
          );
          time.endTime = Date.parse(new Date());
          break;
        default:
          time.startTime = Date.parse(this.pickerValue1[0]);
          time.endTime = Date.parse(this.pickerValue1[1]);
      }
      let listWhere = [];
      listWhere.push(
        {
          field: "time",
          operator: "gt",
          val: time.startTime,
          valType: "time"
        },
        {
          field: "time",
          operator: "lt",
          val: time.endTime,
          valType: "time"
        }
      );
      param.deviceKey = this.deviceKey;
      param.deviceId = this.deviceId;
      param.prodPk = this.prodId;
      param.fields = this.dialogData.funKey;
      param.orderType = 2;
      param.current = this.page.page;
      param.size = this.page.pageSize;
      param.listWhere = listWhere;
      getDataUploadListAt(param).then(res => {
        let timeData = res.data.records;
        this.page.total = res.data.total;
        this.setShowChart(timeData);
      });
    },
    formatTime(date) {
      // 检查时间戳长度
      if (date && date.toString().length === 10) {
        // 10 位时间戳
        return moment(date * 1000).format("YYYY-MM-DD HH:mm:ss");
      } else if (date && date.toString().length === 13) {
        // 13 位时间戳
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
      } else {
        return date;
      }
    },
    setShowChart(timeData) {
      for (let item of timeData) {
        let value = item.value;
        if (this.dialogData.dataFormatType === "ENUM") {
          let key = parseInt(item.value);
          value = this.dialogData.dataFormatObj[key] || item.value;
        } else if (this.dialogData.dataFormatType === "TIME") {
          value = this.formatTime(item.value);
        }
        let dataItem = {
          time: this.parseTime(new Date(item.time)),
          value: value
        };
        this.tableData.push(dataItem);
      }
      let chartData = [...this.tableData];
      // chartData.reverse()
      let valueData = [];
      let xData = [];
      for (let point of chartData) {
        xData.push(point.time);
        valueData.push(point.value);
      }
      if (!this.chart) {
        var o = document.getElementById("showChart");
        var w = o.clientWidth || o.offsetWidth;
        document.getElementById("chart").style.width = w + "px";
        this.chart = echarts.init(document.getElementById("chart"));
      }
      this.chart.setOption({
        tooltip: {
          trigger: "axis"
        },
        xAxis: {
          type: "category",
          data: xData
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            data: valueData,
            type: "line"
          }
        ]
      });
    },
    loadMoreData() {},
    getMoreTimeData(param) {
      if (!this.showDialog) {
        return;
      }
      this.page.page += 1;
      param.page = this.page.page;
      getDataUploadListAt(param).then(res => {
        let timeData = res.data.data.records;
        this.page.total = res.data.data.total;
        this.setShowChart(timeData);
        if (this.page.total > this.page.pageSize * this.page.page) {
          this.getMoreTimeData(param);
        }
      });
    },
    initDialog(dialogData) {
      if (dialogData) {
        this.dialogData = dialogData;
      } else {
        return;
      }
      if (!this.dialogData.funDataType || !document.querySelector("#chart")) {
        return;
      }
      this.timeValue = "1";
      this.showDialog = true;
      this.tableData = [];
      this.page = {
        page: 1,
        pageSize: 100,
        total: 0
      };
      if (
        this.dialogData.funDataType === "TEXT" ||
        this.dialogData.funDataType === "DATE" ||
        this.dialogData.funDataType === "IMAGE" ||
        this.dialogData.dataFormatType === "ENUM" ||
        this.dialogData.dataFormatType === "TIME"
      ) {
        this.showchartDisable = true;
        this.showType = "表格";
      } else {
        this.showchartDisable = false;
        this.showType = "图表";
      }
      this.drawLine();
    },
    handleShowDialog() {},
    close() {
      this.timeValue = "1";
      this.showDialog = false;
    },
    selectChange(val) {
      if (val !== "4") {
        this.showDialog = true;
        this.tableData = [];
        this.page = {
          page: 1,
          pageSize: 100,
          total: 0
        };
        this.drawLine();
      }
    },
    pickerChange() {
      this.showDialog = true;
      this.tableData = [];
      this.page = {
        page: 1,
        pageSize: 100,
        total: 0
      };
      this.drawLine();
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.tableData = [];
      this.drawLine();
    },
    handleCurrentChange(val) {
      this.page.page = val;
      this.tableData = [];
      this.drawLine();
    }
  }
};
</script>

<style lang="scss" scoped>
.list-container {
  overflow: auto;
  height: 50vh;
  padding-bottom: 10px;
}
.show-data-footer {
  text-align: center;
  padding-top: 10px;
}
.show-data-header {
  margin-bottom: 15px;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 34px;
  line-height: 32px;
  .header-time {
    display: flex;
    align-items: center;
    .time-select {
      width: 100px;
      margin-right: 8px;
    }
    .time-picker {
      width: 350px;
    }
  }
}
</style>
<style lang="scss">
.public-custom-dialog.show-chart {
  .el-dialog__body {
    padding: 15px 20px;
  }
  .el-dialog__footer {
    padding-top: 0;
  }
}
</style>
