<template>
  <div class="full-w-h d-queueLength">
    <div class="filter-buttons">
      <div @click="activeCode=item.code" class="f-button" :class="activeCode===item.code?'active':''"
           v-for="item of reqTypes">{{ item.name }}
      </div>
      <el-select class="f-button"
                 v-model="selectVal" @change="refresh">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <v-chart v-loading="loading"
             element-loading-text="数据加载中..."
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(3, 11, 25, 0.8)" class="d-chart" autoresize :option="option"/>
  </div>
</template>

<script>
import {getCrossTurnData, getCrossTurnData1, getKeyCross} from "@/dao/optApi";
import {getFontSize} from "@/config/holo/fontSize";
import {noDataTitle} from "@/utils/chartStyle";

export default {
  name: 'queueLength',
  props: ['crossData'],
  data() {
    return {loading:true,

      option: {},
      turnMap: {
        3: '右转',
        2: '直行',
        1: '左转',
        'unknow': '未知',
        'u': '掉头',
        'l_s': '直左',
        's_r': '直右',
        'l_s_r': '左直右',
        'l_r': '左右',
        'l_u': '左转掉头',
        's_u': '直行掉头',
        'r_u': '右转掉头',
        'l_s_u': '左直掉头',
        'u_s_r': '直右掉头',
        'l_s_r_r': '左直右掉头',
        'l_r_u': '左右掉头'
      },
      options: [],
      selectVal: '',
      activeCode: 1,
      reqTypes: [
        {name: '进口道级', code: 1},
        {name: '转向级', code: 2},
      ],
    }
  },
  computed: {
    crossId() {
      return this.crossData.id
    },
    crossName() {
      return this.crossData.name
    }
  },
  watch: {
    activeCode(e) {
      this.getData()
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    refresh() {
      if (this.activeCode === 1) {
        this.renderInOut()
      }
      if (this.activeCode === 2) {
        this.renderTurn()
      }
    },
    getData() {
      this.loading = true
      if (this.activeCode === 1) {
        this.options = [{label: '进口', value: 1}]
        this.selectVal = this.options[0].value
        getKeyCross({crossId: this.crossId}).then(res => {
          this.loading = false
          console.log('进口道级', res)
          this.inOutData = res.content
          this.renderInOut()
        })
      }
      if (this.activeCode === 2) {
        let start = `${new Date().toLocaleDateString().replaceAll('/','-')} 00:00:00`
        let end = new Date().toLocaleString().replaceAll('/','-')
        // let start = '2024-04-04 00:00:00'
        // let end = '2024-04-04 00:00:00'
        getCrossTurnData1({crossId: this.crossId, start, end}).then(res => {
          this.loading = false
          console.log('zhuanxaingji', res)
          this.options = res.content.reduce((a, b) => {
            let bInA = false
            for (let aItem of a) {
              if (aItem.value === b.fRidDir) {
                bInA = true
              }
            }
            if (!bInA) {
              a.push({
                value: b.fRidDir,
                label: this.$store.state.dicts.Direction.find((item) => {
                  return item.code == b.fRidDir;
                }).name,
              })
            }
            return a
          }, [])
          this.selectVal = this.options[0]?.value || ''
          this.allTurnData = res.content
          this.renderTurn()
        })
        // getCrossTurnData({crossId: this.crossId}).then(res => {
        //   console.log('转向级', res)
        //   this.options = res.content.reduce((a, b) => {
        //     let bInA = false
        //     for (let aItem of a) {
        //       if (aItem.value === b.dir) {
        //         bInA = true
        //       }
        //     }
        //     if (!bInA) {
        //       a.push({
        //         value: b.dir,
        //         label: this.$store.state.dicts.Direction.find((item) => {
        //           return item.code == b.dir;
        //         }).name,
        //       })
        //     }
        //     return a
        //   }, [])
        //   this.selectVal = this.options[0]?.value || ''
        //   this.allTurnData = res.content
        //   this.renderTurn()
        // })
      }
    },
    // 渲染进口/出口排队图表
    renderInOut() {
      let xData = this.inOutData.map(item => {
        return item.hourMinute
      })
      let allDir = this.inOutData.reduce((a, b) => {
        for (let item of b.detailList) {
          if (item.inOutType === this.selectVal) {
            if (!a[item.dir]) {
              a[item.dir] = false
            }
          }
        }
        return a
      }, {})
      let yDatas = this.inOutData.reduce((a, b) => {
        let allDirCopy = JSON.parse(JSON.stringify(allDir))
        for (let item of b.detailList) {
          if (item.inOutType === this.selectVal) {
            allDirCopy[item.dir] = true
            if (a[item.dir]) {
              a[item.dir].push(item.queueLength)
            } else {
              a[item.dir] = [item.queueLength]
            }
          }
        }
        for (let key in allDirCopy) {
          if (!allDirCopy[key]) {
            if (a[key]) {
              a[key].push(0)
            } else {
              a[key] = [0]
            }
          }
        }
        return a
      }, {})
      let title = {
        show: false
      }
      if (!xData.length) {
        title = noDataTitle
      }
      let colors = [
        "rgba(24, 144, 255, 1)",
        "rgba(0, 189, 208, 1)",
        "rgba(79, 210, 125, 1)",
        "rgba(255, 209, 69, 1)",
      ]
      let option = {
        title,
        dataZoom: {
          type: "inside",
          startValue: xData.length - 6,
          endValue:xData.length-1,
        },
        tooltip: {
          enterable: true,
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderWidth: 0,
          textStyle: {
            fontSize: getFontSize(12),
            color: 'white',
          },
          confine: true,
        },
        legend: {
          inactiveColor: 'rgba(255,255,255,0.7)',
          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: 0,
          right: 0,
          bottom: 0,
          top: "22%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: xData,
          boundaryGap: true,
          axisLabel: {
            fontSize: getFontSize(12),
            color: "rgba(126, 139, 166, 1)",
          },
        },
        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: (() => {
          let series = [];
          for (let key in yDatas) {
            let index = Object.keys(yDatas).indexOf(key)
            let nameReal = this.$store.state.dicts.Direction.find((item) => {
              return item.code == key;
            }).name
            series.push({
              name: nameReal,
              type: "bar",
              barWidth: getFontSize(6),
              label: {
                show: false,
              },
              itemStyle: {
                borderRadius: 4,
                color: new echarts.graphic.LinearGradient(
                    0,
                    1,
                    0,
                    0,
                    [
                      {
                        offset: 0,
                        color: colors[index].replace('1)', '0.2)'), // 100% 处的颜色
                      },
                      {
                        offset: 1,
                        color: colors[index], // 0% 处的颜色
                      },
                    ],
                    false
                ),
              },
              emphasis: {
                focus: "series",
              },
              data: yDatas[key],
            })
          }
          console.log("series", series);
          return series;
        })(),
      };
      this.option = option
    },
    // 渲染转向级别排队图表
    renderTurn() {
      let filterData = this.allTurnData.filter(item => {
        return item.fRidDir === this.selectVal
      }).reverse()
      let xData = filterData.reduce((a,b) => {
        let time = new Date(b.windowEndTime).toLocaleTimeString().slice(0,5)
        if(!a.includes(time)){
          a.push(time)
        }
        return a
      },[])
      console.log(filterData, xData)
      let yDatas = filterData.reduce((a, b) => {
          if (a[b.turnDirNo]) {
            a[b.turnDirNo].push(b.queueLength)
          } else {
            a[b.turnDirNo] = [b.queueLength]
          }
        return a
      }, {})
      console.log('x,y', xData, yDatas)
      let colors = [
        "rgba(24, 144, 255, 1)",
        "rgba(0, 189, 208, 1)",
        "rgba(79, 210, 125, 1)",
        "rgba(255, 209, 69, 1)",
      ]
      let title = {
        show:false,
      }
      if(!xData.length){
        title = noDataTitle
      }
      let option = {
        title,
        dataZoom: {
          type: "inside",
          startValue: xData.length - 6,
          endValue:xData.length-1,
        },
        color: colors,
        tooltip: {
          enterable: true,
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderWidth: 0,
          textStyle: {
            fontSize: getFontSize(12),
            color: 'white',
          },
          confine: true,
        },
        legend: {
          inactiveColor: 'rgba(255,255,255,0.7)',
          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: 0,
          right: 0,
          bottom: 0,
          top: "22%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          data: xData,
          axisLabel: {
            fontSize: getFontSize(12),
            color: "rgba(126, 139, 166, 1)",
          },
        },
        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: (() => {
          let series = [];
          for (let key in yDatas) {
            let index = Object.keys(yDatas).indexOf(key)
            let nameReal = this.turnMap[key]
            series.push({
              name: nameReal,
              type: "bar",
              barWidth: getFontSize(6),
              label: {
                show: false,
              },
              itemStyle: {
                borderRadius: 4,
                color: new echarts.graphic.LinearGradient(
                    0,
                    1,
                    0,
                    0,
                    [
                      {
                        offset: 0,
                        color: colors[index].replace('1)', '0.2)'), // 100% 处的颜色
                      },
                      {
                        offset: 1,
                        color: colors[index], // 0% 处的颜色
                      },
                    ],
                    false
                ),
              },
              emphasis: {
                focus: "series",
              },
              data: yDatas[key],
            })
          }
          console.log("series", series);
          return series;
        })(),
      };
      this.option = option
    },
  },

}
</script>

<style lang="less" scoped>
.d-queueLength {
  display: flex;
  flex-direction: column;

  ::v-deep .el-input__inner {
    color: white;
  }

  .filter-buttons {
    height: 25px;
    width: 100%;
    display: flex;
    justify-content: flex-end;


    .f-button {
      margin-left: 10px;
      padding: 0 10px;
      height: 25px;
      line-height: 25px;
      font-size: 12px;
      background-color: #375a99;
      cursor: pointer;
    }

    .active {
      background-color: #5a91ee;
    }

    .f-button:last-child {
      width: 100px;
      padding: 0;

      ::v-deep .el-input__inner {
        height: 25px;
        line-height: 25px;
        font-size: 12px;
        border-radius: 0;
      }

      ::v-deep .el-input__icon {
        line-height: 25px;
      }
    }
  }

  .d-chart {
    width: 100%;
    flex: 1;
  }
}
</style>