<template>
  <div class="full-w-h snapshotDataContainer">
    <div style="margin-bottom: 10px; margin-top: 10px" class="custom-form">
      <label class="custom-form-label">时段选择： </label>
      <el-date-picker
        :clearable="false"
        @change="dateChange"
        v-model="dateTimeRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <label class="custom-form-label">车道： </label>
      <el-select
        class="custom-select"
        style="margin-right: 10px"
        multiple
        collapse-tags
        @change="lineChangeGetData()"
        v-model="value1"
        placeholder="请选择"
      >
        <el-option
          v-for="item in options1"
          :key="item.laneId"
          :label="item.aliasName"
          :value="item.laneId"
        >
        </el-option>
      </el-select>
      <div class="custom-form-label">（备注：车道可多选）</div>
      <el-button
        :loading="exportLoading"
        @click="exportLaneExcel()"
        size="mini"
        type="primary"
        class="rightExport"
        >导出</el-button
      >
    </div>
    <div
      v-loading="loading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.4)"
      style="margin-bottom: 10px"
      class="custom-table"
    >
      <div class="custom-elTable">
        <el-table
          ref="table"
          height="100%"
          header-row-class-name="custom-table-header"
          header-cell-class-name="custom-table-header-cell"
          @row-click="rowClick"
          :data="listDataCopy"
          :row-class-name="getRowClassName"
          style="width: 100%"
        >
          <el-table-column
            :width="index === 0 ? '150' : 'auto'"
            :key="index"
            v-for="(it, index) of laneTableColumn"
            align="center"
            :label="it.label"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ occupancyValue(scope.row[it.prop], it.prop) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="custom-nextPre">
        <div>500 条/页</div>
        <div>当前第 {{ currentPage + 1 }} 页</div>
        <div @click="lineChangeGetData('pre')">
          <i class="el-icon-arrow-left" /> 上一页
        </div>
        <div @click="lineChangeGetData('next')">
          下一页 <i class="el-icon-arrow-right" />
        </div>
      </div>
    </div>
    <div class="chartContainer">
      <v-chart
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.4)"
        :option="option"
        autoresize
      ></v-chart>
      <el-select
        class="indexOptionSelector"
        multiple
        collapse-tags
        @change="filterIndexChange"
        v-model="indexOptionValue"
        placeholder="请选择"
      >
        <el-option
          v-for="item of computedLaneTableColumn"
          :key="item.prop"
          :label="item.label"
          :value="item.prop"
        >
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import { noDataTitle } from "@/utils/chartStyle";
import { getFontSize } from "@/config/holo/fontSize";
import {
  exportLane,
  getLaneSnapshotIndex,
  initLaneSort,
  exportSnapshot,
} from "@/dao/optApi";
import { occupancyValue } from "../../../utils";

export default {
  name: "snapshotData",
  props: ["crossData"],
  data() {
    return {
      exportLoading: false,
      currentPage: 0,
      indexOptionValue: [],
      loading: true,
      laneTableColumn: [
        { label: "时间", prop: "time" },
        { label: "方向", prop: "dirName" },
        { label: "车道号", prop: "laneSort" },
        { label: "排队长度", prop: "queueLength" },
        { label: "队首距离", prop: "teamHeadDistance" },
        { label: "队尾距离", prop: "teamTailDistance" },
        { label: "排队车辆数", prop: "queueNums" },
        { label: "车道内车辆数", prop: "carNums" },
        { label: "平均空间占有率", prop: "vehicleLengthRatio" },
        { label: "平均速度", prop: "speed" },
        { label: "车辆分布情况", prop: "stdSpaceHeadway" },
        { label: "头车速度", prop: "headSpeed" },
        { label: "末车速度", prop: "mailSpeed" },
        { label: "头车位置", prop: "firstCarPosition" },
        { label: "末车位置", prop: "endCarPosition" },
      ],
      includeIndex: [
        "queueLength",
        "teamHeadDistance",
        "teamTailDistance",
        "queueNums",
        "carNums",
        "vehicleLengthRatio",
        "speed",
        "stdSpaceHeadway",
        "headSpeed",
        "mailSpeed",
        "firstCarPosition",
        "endCarPosition",
      ],
      value1: [],
      options1: [],
      listDataCopy: [],
      dateTimeRange: [],
      xData: [],
      yDatas: [],
      tableData: [],
      finalXData: [],
    };
  },
  computed: {
    computedLaneTableColumn() {
      return this.laneTableColumn.filter((item) => {
        return this.includeIndex.includes(item.prop);
      });
    },
    option() {
      let title = {
        show: false,
      };
      if (!this.finalXData.length) {
        title = noDataTitle;
      }
      let series = [];
      let selected = {};
      console.log("1111111111", this.finalXData, this.yDatas);
      for (let [i, item] of this.yDatas.entries()) {
        // let nameReal = this.$store.state.dicts.Direction.find((item) => {
        //   return item.code == key;
        // }).name
        let value = item.name.split("-")[2];
        let realIndex = this.laneTableColumn.find((columnIndex) => {
          return columnIndex.prop === value;
        })?.label;
        let nameReal = item.name.replace(value, realIndex);
        if (value !== "allFlow") {
          selected[nameReal] = false;
        }
        series.push({
          name: nameReal,
          type: "line",
          symbol: "none",
          smooth: true,
          // areaStyle: {
          //   color: new echarts.graphic.LinearGradient(
          //       0,
          //       1,
          //       0,
          //       0,
          //       [
          //         {
          //           offset: 0,
          //           color: "rgba(62, 170, 247, 0)", // 100% 处的颜色
          //         },
          //         {
          //           offset: 1,
          //           color: this.colors[i], // 0% 处的颜色
          //         },
          //       ],
          //       false
          //   ),
          // },
          label: {
            show: false,
          },
          emphasis: {
            focus: "series",
          },
          data: item.list.reverse(),
        });
      }
      return {
        title,
        dataZoom: {
          type: "inside",
        },
        tooltip: {
          backgroundColor: "rgba(0,0,0,0.6)",
          borderWidth: 0,
          textStyle: {
            fontSize: getFontSize(12),
            color: "white",
          },
          formatter: function (params) {
            if (params && params.length) {
              let str = `<p>${params[0]?.name}</p>`;
              for (let i = 0; i < params.length; i++) {
                str += `<p>${params[i].seriesName}&nbsp;&nbsp;:&nbsp;&nbsp;${params[i].value}</p>`;
              }
              return (
                '<div style="max-height:200px;overflow-y:auto;background-color:rgba(0,0,0,0.6);color:white ">' +
                str +
                "</div>"
              );
            }
          },
          enterable: true,
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          confine: true,
        },
        legend: {
          inactiveColor: "rgba(255,255,255,0.7)",
          // selected,
          left: 0,
          padding: [7, 200, 0, 0],
          itemGap: getFontSize(16),
          itemWidth: getFontSize(12),
          itemHeight: getFontSize(12),
          textStyle: {
            color: "rgba(255,255,255,0.9)",
            fontSize: getFontSize(12),
            lineHeight: 16,
          },
          pageTextStyle: {
            color: "rgba(255,255,255,0.9)",
            fontSize: getFontSize(12),
          },
          pageIconColor: "white",
          pageIconSize: getFontSize(12),
          pageIconInactiveColor: "rgba(255,255,255,0.7)",
          type: "scroll",
        },
        grid: {
          left: 38,
          right: 60,
          bottom: 0,
          top: "22%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.finalXData.reverse(),
          axisLabel: {
            fontSize: getFontSize(12),
            color: "rgba(126, 139, 166, 1)",
          },
          axisPointer: {
            type: "line",
          },
        },
        yAxis: {
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "rgba(255, 255, 255, 0.2)",
            },
          },
          type: "value",
          axisLabel: {
            fontSize: getFontSize(12),
            color: "rgba(126, 139, 166, 1)",
          },
        },
        series: series,
      };
    },
  },
  mounted() {
    if (time_config.dataQuery_snapshotTime) {
      this.dateTimeRange = [
        new Date(time_config.dataQuery_snapshotTime[0]),
        new Date(time_config.dataQuery_snapshotTime[1]),
      ];
    } else {
      this.dateTimeRange = [
        new Date(new Date().setTime(new Date().getTime() - 1000 * 60 * 60)),
        new Date(),
      ];
    }
    this.getData();
  },
  methods: {
    dateChange(){
      if(new Date(this.dateTimeRange[1]).getTime() - new Date(this.dateTimeRange[0]).getTime() > 30*24*60*60*1000){
        this.$message('选择时段需小于30天')
        return
      }
      this.getData()
    },
    downloadFileExcel(response) {
      let blob = new Blob([response.data], { type: "application/x-xls" });
      let a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      let fileName = response.headers["content-disposition"].split("=")[1];
      fileName = decodeURI(fileName);
      a.download = fileName; //文件名称
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    exportLaneExcel() {
      this.exportLoading = true;
      // excel导出下载
      exportSnapshot({
        // crossId: this.crossData.crossId,
        crossId: this.crossData.id,
        end: this.dateTimeRange[1].toLocaleString().replaceAll("/", "-"),
        start: this.dateTimeRange[0].toLocaleString().replaceAll("/", "-"),
        laneId: this.value1.join(","),
      }).then((response) => {
        this.exportLoading = false;
        this.downloadFileExcel(response);
      });
    },
    lineChangeGetData(isNextPage) {
      this.loading = true;
      if (this.value1.length) {
        this.indexOptionValue = ["queueLength"];
        let params = {
          // crossId: this.crossData.crossId,
          crossId: this.crossData.id,
          end: this.dateTimeRange[1].toLocaleString().replaceAll("/", "-"),
          start: this.dateTimeRange[0].toLocaleString().replaceAll("/", "-"),
          laneId: this.value1.join(","),
        };
        let optionFlag = "";
        if (isNextPage) {
          if (isNextPage === "pre") {
            params = { ...params, pageNum: this.currentPage - 1 };
            optionFlag = "pre";
          } else {
            params = { ...params, pageNum: this.currentPage + 1 };
            optionFlag = "next";
          }
        } else {
          params = { ...params, pageNum: 0 };
        }
        // 车道级数据
        getLaneSnapshotIndex(params).then((res) => {
          console.log("res1快照", res);
          this.loading = false;
          if (res.content && res.content.length) {
            if (optionFlag === "pre") {
              this.currentPage -= 1;
            }
            if (optionFlag === "next") {
              this.currentPage += 1;
            }
            this.tableData = res.content.map((row) => {
              row.teamHeadDistance =
                row.teamHeadDistance < 0 ? "--" : row.teamHeadDistance;
              row.teamTailDistance =
                row.teamTailDistance < 0 ? "--" : row.teamTailDistance;
              row.dirName = this.$store.state.dicts.Direction.find((dict) => {
                return dict.code == row.dir;
              })?.name;
              return row;
            });
            this.listDataCopy = JSON.parse(JSON.stringify(this.tableData));
            this.initSelectAndFilterTable1();
            this.$nextTick(() => {
              this.$refs.table.doLayout();
            });
          } else {
            let msg = "";
            if (optionFlag === "pre") {
              msg = "已经是第一页";
            }
            if (optionFlag === "next") {
              msg = "已经是最后一页";
            }
            if (msg) {
              this.$message(msg);
            } else {
              this.tableData = res.content;
              this.listDataCopy = JSON.parse(JSON.stringify(this.tableData));
              this.initSelectAndFilterTable1();
              this.$nextTick(() => {
                this.$refs.table.doLayout();
              });
            }
          }
        });
      } else {
        this.loading = false;
        this.tableData = [];
        this.listDataCopy = [];
        this.initSelectAndFilterTable1();
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      }
    },
    // getLaneName(aliasName){
    //   let [] aliasName.split('-')
    // },
    filterIndexChange() {
      this.renderFilterData1();
    },
    occupancyValue,
    initSelectAndFilterTable1() {
      // this.value1 = []
      // this.options1 = this.tableData.reduce((a, b) => {
      //   if (!a.includes(b.laneSort)) {
      //     a.push(b.laneSort)
      //   }
      //   return a
      // }, [])
      // if (this.options1.length) {
      //   this.value1.push(this.options1[0])
      // }
      this.filterTable1();
    },
    filterTable1() {
      this.listDataCopy = this.tableData.filter((item) => {
        return this.value1.includes(item.laneId);
      });
      this.renderFilterData1();
    },
    // 根据筛选后的数据渲染echarts
    renderFilterData1() {
      this.xData = this.listDataCopy.reduce((a, b) => {
        // if (!a.includes(b.time)) {
        a.push(b.time);
        // }
        return a;
      }, []);

      this.yDatas = [];
      let yObj = this.listDataCopy.reduce((a, b) => {
        for (let key in b) {
          if (
            this.includeIndex.includes(key) &&
            this.indexOptionValue.includes(key)
          ) {
            let wholeKey = `${b.dirName}-${b.laneSort}-${key}`;
            if (a[wholeKey]) {
              a[wholeKey].push(b[key]);
            } else {
              a[wholeKey] = [b[key]];
            }
          }
        }
        return a;
      }, {});
      for (let key in yObj) {
        this.yDatas.push({
          name: key,
          list: yObj[key],
        });
      }
      // 将x轴时间 等比例缩放为数据点数组长度
      let xStart = this.xData[0];
      let xEnd = this.xData[this.xData.length - 1];
      let rangeAllTime = new Date(xEnd).getTime() - new Date(xStart).getTime();
      let stepNum = this.xData.length / this.yDatas.length;
      let onStepTime = rangeAllTime / stepNum;
      console.log("range", rangeAllTime, stepNum, onStepTime);
      this.finalXData = [];
      for (let i = 0; i < stepNum; i++) {
        this.finalXData.push(
          new Date(new Date(xStart).getTime() + onStepTime * i).toLocaleString()
        );
      }
    },
    getData() {
      this.value1 = [];
      // if (this.crossData.crossId) {
      if (this.crossData.id) {
        // todo 获取当前路口所有车道 根据车道 getData
        // initLaneSort({ crossId: this.crossData.crossId }).then((res) => {
        initLaneSort({ crossId: this.crossData.id }).then((res) => {
          this.options1 = res.content;
          for (let item of this.options1) {
            this.value1.push(item.laneId);
          }
          this.lineChangeGetData();
        });
      }
    },
    rowClick(e) {
      console.log("row", e);
    },
    getRowClassName(e) {
      if (e.rowIndex % 2 !== 0) {
        return "row-odd";
      } else {
        return "row-even";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.custom-select {
  width: 280px;
}

.custom-form-label {
  font-size: 14px;
}

::v-deep .el-input__inner {
  border: 1px solid rgba(90, 144, 238, 0.34);
  color: white;
}

::v-deep .el-range-separator {
  color: white;
}

label {
  margin-left: 10px;
}

label:first-child {
  margin-left: 0;
}

.chartContainer {
  flex: 1;
  position: relative;

  .indexOptionSelector {
    position: absolute;
    width: 180px;
    right: 0;
    top: 0;
  }
}

.custom-form {
  height: 40px;
  display: flex;
  align-items: center;
  position: relative;

  .rightExport {
    width: 78px;
    height: 28px;
    position: absolute;
    right: 0;
    top: 50%;
    font-size: 14px;
    letter-spacing: 1px;
    cursor: pointer;
    background-color: rgba(41, 67, 114);
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    transform: translateY(-50%);
  }

  .rightExport:hover {
    background-color: #355287;
  }
}

.custom-table {
  height: 450px;
  width: 100%;

  .custom-elTable {
    height: 400px;
  }

  .custom-nextPre {
    height: 50px;
    display: flex;
    width: 100%;
    justify-content: end;
    align-items: center;
    font-size: 14px;

    div {
      margin-left: 15px;
      cursor: pointer;
    }

    div:hover {
      color: #5cb6ff;
    }
  }
}

.snapshotDataContainer {
  display: flex;
  flex-direction: column;
  padding: 0 10px;
}
</style>
