<template>
  <div class="full-w-h cycleDataContainer">
    <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
        @change="getData"
        style="margin-right: 10px"
        v-model="locationType1"
        placeholder="请选择"
      >
        <el-option
          v-for="item in locationOptions1"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        style="margin-right: 10px"
        multiple
        collapse-tags
        @change="filterTable1"
        v-model="value1"
        placeholder="请选择"
      >
        <el-option
          v-for="item in options1"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <div>
        （备注：{{ locationType1 === "laneSort" ? "车道" : "转向" }}可多选）
      </div>
      <el-button
      :loading = 'exportLoading'
        @click="exportLaneExcel()"
        size="mini"
        type="primary"
        class="rightExport"
        >导出</el-button
      >
    </div>
    <div style="margin-bottom: 10px" class="custom-table">
      <el-table
        ref="table"
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.4)"
        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%"
        height="100%"
      >
        <el-table-column
          v-for="(it, index) of laneTableColumn"
          :key="index"
          :fixed="index === 0"
          align="center"
          :width="index === 0 ? '150' : 'auto'"
          :prop="it.prop"
          :label="it.label"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ occupancyValue(scope.row[it.prop]) }}
          </template>
        </el-table-column>
      </el-table>
    </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 {
  getLanePeriodTurnData,
  getLaneTrafficIndex,
  exportLane,
  exportTurn
} from "@/dao/optApi";
import { occupancyValue } from "../../../utils";

export default {
  name: "cycleData",
  props: ["crossData"],
  data() {
    return {
      exportLoading:false,
      loading: true,
      laneTableColumn: [],
      locationType1: "laneSort",
      locationOptions1: [
        { value: "laneSort", label: "车道级" },
        { value: "turn", label: "转向级" },
      ],
      value1: [],
      options1: [],
      indexOptionValue: [],
      tabs: [{ 1: "周期数据" }, { 2: "快照数据" }, { 3: "事件数据" }],
      listDataCopy: [],
      dateTimeRange: [],
      xData: [],
      yDatas: [],
      tableData: [],
      option: {},
      laneTableColumn1: [
        { label: "时间", prop: "time" },
        { label: "方向", prop: "dirName" },
        { label: "车道号", prop: "laneSort" },
        { label: "总流量", prop: "allFlow" },
        { label: "行人流量", prop: "pedFlow" },
        { label: "非机动车流量", prop: "nonMotorFlow" },
        { label: "小车流量", prop: "trafficFlowC" },
        { label: "中车流量", prop: "trafficFlowB" },
        { label: "大车流量", prop: "trafficFlowA" },
        { label: "平均速度", prop: "speed" },
        { label: "平均时间占有率", prop: "timeOccupancy" },
        { label: "平均车头时距", prop: "vehheadTime" },
        { label: "平均车身间距", prop: "vehheadDist" },
        { label: "85位速度", prop: "v85" },
        { label: "车辆总和", prop: "allVehiceleFlow" },
        { label: "平均空间占有率(%)", prop: "vehicleNumsRatioMean" },
        { label: "最大排队长度", prop: "queueLength" },
        { label: "平均停车次数", prop: "stopTimes" },
        { label: "平均延误", prop: "delayTime" },
      ],
      laneTableColumn2: [
        { label: "时间", prop: "windowStartTime" },
        { label: "方向", prop: "fRidDirTranslate" },
        { label: "总流量", prop: "allFlow" },
        { label: "平均速度", prop: "avgSpeed" },
        { label: "左转流量", prop: "flow1" },
        { label: "左转车辆平均速度", prop: "speed1" },
        { label: "直行流量", prop: "flow2" },
        { label: "直行车辆平均速度", prop: "speed2" },
        { label: "右转流量", prop: "flow3" },
        { label: "右转车辆平均速度", prop: "speed3" },
      ],
      includeIndex1: [
        "allFlow",
        "allVehiceleFlow",
        "delayTime",
        "nonMotorFlow",
        "pedFlow",
        "queueLength",
        "speed",
        "stopTimes",
        "timeOccupancy",
        "trafficFlowA",
        "trafficFlowB",
        "trafficFlowC",
        "v85",
        "vehheadDist",
        "vehheadTime",
        "vehicleNumsRatioMean",
      ],
      includeIndex2: [
        "flow1",
        "flow2",
        "flow3",
        "speed1",
        "speed2",
        "speed3",
        "allFlow",
        "avgSpeed",
      ],
    };
  },
  computed: {
    computedLaneTableColumn() {
      if (this.locationType1 === "laneSort") {
        return this.laneTableColumn1.filter((item) => {
          return this.includeIndex1.includes(item.prop);
        });
      } else {
        return this.laneTableColumn2.filter((item) => {
          return this.includeIndex2.includes(item.prop);
        });
      }
    },
  },
  mounted() {
    if (time_config.dataQuery_cycleTime) {
      this.dateTimeRange = [
        new Date(time_config.dataQuery_cycleTime[0]),
        new Date(time_config.dataQuery_cycleTime[1]),
      ];
    } else {
      this.dateTimeRange = [
        new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24)),
        new Date(),
      ];
    }
    // if (this.crossData.crossId) {
    if (this.crossData.id) {
      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() {
      // 车道级excel导出下载
      if (this.locationType1 === "laneSort") {
        this.exportLoading = true
        exportLane({
          // crossId: this.crossData.crossId,
          crossId: this.crossData.id,
          end: this.dateTimeRange[1].toLocaleString().replaceAll("/", "-"),
          start: this.dateTimeRange[0].toLocaleString().replaceAll("/", "-"),
        }).then((response) => {
          this.exportLoading = false
          this.downloadFileExcel(response)
        });
      }
      // 转向级
      else{
        this.exportLoading = true
        exportTurn({
          // crossId: this.crossData.crossId,
          crossId: this.crossData.id,
          end: this.dateTimeRange[1].toLocaleString().replaceAll("/", "-"),
          start: this.dateTimeRange[0].toLocaleString().replaceAll("/", "-"),
        }).then((response) => {
          this.exportLoading = false
          this.downloadFileExcel(response)
        });
      }
    },
    filterIndexChange() {
      if (this.locationType1 === "laneSort") {
        this.renderFilterData1();
      } else {
        this.renderFilterData2();
      }
    },
    occupancyValue,
    initSelectAndFilterTable1() {
      this.value1 = [];
      console.log("before sort...", this.tableData);
      this.options1 = this.tableData
        .sort((a, b) => {
          return Number(a.dir) - Number(b.dir);
        })
        .reduce((a, b) => {
          if (!a.includes(b.laneSort)) {
            a.push(b.laneSort);
          }
          return a;
        }, []);
      if (this.options1.length) {
        this.value1.push(...this.options1);
      }
      this.filterTable1();
    },
    initSelectAndFilterTable2() {
      this.value1 = [];
      this.options1 = this.tableData.reduce((a, b) => {
        if (!a.includes(b.fRidDirTranslate)) {
          a.push(b.fRidDirTranslate);
        }
        return a;
      }, []);
      if (this.options1.length) {
        // this.value1.push(this.options1[0])
        this.value1.push(...this.options1);
      }
      this.filterTable1();
    },
    filterTable1() {
      if (this.locationType1 === "laneSort") {
        this.listDataCopy = this.tableData.filter((item) => {
          return this.value1.includes(item.laneSort);
        });
        // this.listDataCopy = this.tableData
        this.renderFilterData1();
      } else {
        this.listDataCopy = this.tableData.filter((item) => {
          return this.value1.includes(item.fRidDirTranslate);
        });
        // this.listDataCopy = this.tableData
        this.renderFilterData2();
      }
    },
    // 根据筛选后的数据渲染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.includeIndex1.includes(key) &&
            this.indexOptionValue.includes(key)
          ) {
            let wholeKey = `${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],
        });
      }
      // ---
      let title = {
        show: false,
      };
      if (!this.xData.length) {
        title = noDataTitle;
      }
      let series = [];
      let selected = {};
      for (let [i, item] of this.yDatas.entries()) {
        let valueArr = item.name.split("-");
        let value = valueArr[valueArr.length - 1];
        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,
          label: {
            show: false,
          },
          emphasis: {
            focus: "series",
          },
          data: item.list.reverse(),
        });
      }
      this.option = {
        title,
        dataZoom: {
          type: "inside",
        },
        tooltip: {
          backgroundColor: "rgba(0,0,0,0.6)",
          borderWidth: 0,
          textStyle: {
            fontSize: getFontSize(12),
            color: "white",
          },
          enterable: true,
          trigger: "axis",
          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;padding: 2px 8px 2px 2px;">' +
                str +
                "</div>"
              );
            }
          },
          axisPointer: {
            type: "shadow",
          },
          confine: true,
        },
        legend: {
          inactiveColor: "rgba(255,255,255,0.7)",
          left: 0,
          padding: [7, 200, 0, 0],
          // selected,
          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.xData.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,
      };
      // ---
    },

    // 转向数据渲染echarts
    renderFilterData2() {
      this.xData = this.listDataCopy.reduce((a, b) => {
        if (!a.includes(b.windowEndTime)) {
          a.push(b.windowEndTime);
        }
        return a;
      }, []);
      this.yDatas = [];
      let yObj = this.listDataCopy.reduce((a, b) => {
        for (let key in b) {
          if (
            this.includeIndex2.includes(key) &&
            this.indexOptionValue.includes(key)
          ) {
            let wholeKey = `${b.fRidDirTranslate}-${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],
        });
      }
      console.log("yDatas", this.yDatas);
      // ---
      let title = {
        show: false,
      };
      if (!this.xData.length) {
        title = noDataTitle;
      }
      let series = [];
      let selected = {};
      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("-")[1];
        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(),
        });
      }
      this.option = {
        title,
        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;padding: 2px 8px 2px 2px;">' +
                str +
                "</div>"
              );
            }
          },
          enterable: true,
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          confine: true,
        },
        legend: {
          inactiveColor: "rgba(255,255,255,0.7)",
          padding: [7, 200, 0, 0],
          left: 0,
          // selected,
          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.xData.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,
      };
      // ---
    },
    getData() {
      this.loading = true;
      this.indexOptionValue = ["allFlow"];
      let params = {
        // crossId: this.crossData.crossId,
        crossId: this.crossData.id,
        end: this.dateTimeRange[1].toLocaleString().replaceAll("/", "-"),
        start: this.dateTimeRange[0].toLocaleString().replaceAll("/", "-"),
        granularity: "1h",
      };
      // 车道级数据
      if (this.locationType1 === "laneSort") {
        this.laneTableColumn = this.laneTableColumn1;
        getLaneTrafficIndex(params).then((res) => {
          console.log("res1", res);
          this.loading = false;
          this.tableData = res.content;
          this.tableData.map((item) => {
            item.dirName = this.$store.state.dicts.Direction.find((dict) => {
              return dict.code == item.dir;
            })?.name;
          });
          this.listDataCopy = JSON.parse(JSON.stringify(this.tableData));
          this.initSelectAndFilterTable1();
          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
        });
      }
      // 转向级数据
      else {
        this.laneTableColumn = this.laneTableColumn2;
        getLanePeriodTurnData(params).then((res) => {
          console.log("转向级", res);
          this.loading = false;
          this.tableData = res.content.reduce((a, b) => {
            b.windowEndTime = b.windowEndTime.slice(0, 19);
            let haveFlag = false;
            for (let i = 0; i < a.length; i++) {
              if (
                // a[i].crossId === b.crossId &&
                a[i].id === b.id &&
                a[i].fRidDir === b.fRidDir &&
                a[i].windowEndTime === b.windowEndTime
              ) {
                haveFlag = true;
                a[i][`flow${b.turnDirNo}`] = b.flow;
                a[i][`speed${b.turnDirNo}`] = b.speed;
              }
            }
            if (!haveFlag) {
              let externalObj = {};
              externalObj[`flow${b.turnDirNo}`] = b.flow;
              externalObj[`speed${b.turnDirNo}`] = b.speed;
              let finalSinglaObj = Object.assign({}, b, externalObj);
              delete finalSinglaObj.speed;
              a.push(finalSinglaObj);
            }
            return a;
          }, []);
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].allFlow =
              (this.tableData[i].flow1 || 0) +
              (this.tableData[i].flow2 || 0) +
              (this.tableData[i].flow3 || 0);
            let speedNum = 0;
            for (let key in this.tableData[i]) {
              if (key.includes("speed")) {
                speedNum += 1;
              }
            }
            this.tableData[i].fRidDirTranslate =
              this.$store.state.dicts.Direction.find((item) => {
                return item.code == this.tableData[i].fRidDir;
              }).name;
            this.tableData[i].avgSpeed = (
              ((this.tableData[i].speed1 || 0) +
                (this.tableData[i].speed2 || 0) +
                (this.tableData[i].speed3 || 0)) /
              speedNum
            ).toFixed(2);
          }
          console.log("this.tableData 转向", this.tableData);
          this.listDataCopy = JSON.parse(JSON.stringify(this.tableData));
          this.initSelectAndFilterTable2();
          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
        });
      }
    },
    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>
//table fixed 列样式
::v-deep .el-table__fixed::before {
  height: 0;
}

::v-deep .el-table__fixed {
  box-shadow: 0 0 0.52083vw rgba(255, 255, 255, 0.12);
}

::v-deep .el-table {
  overflow: unset;
}

//table fixed 列样式 end
::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;
    border: none;
    top: 50%;
    font-size: 14px;
    cursor: pointer;
    letter-spacing: 1px;
    background-color: rgba(41, 67, 114);
    display: flex;
    align-items: center;
    justify-content: center;
    transform: translateY(-50%);
  }

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

.custom-table {
  height: 450px;
  display: flex;
  align-items: center;
}

.cycleDataContainer {
  display: flex;
  flex-direction: column;
  padding: 0 10px;
}
.custom-export-button {
    position: absolute;
    right: 0;
    border-radius: 0;
    background-color: #294372;
    color: white;
    letter-spacing: 1px;
    border: none;
    width: 78px;
    font-size: 14px;
    height: 28px;
  }
  .custom-export-button:hover {
    background-color: #355287;
  }
</style>
