<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import CountUp from "@/components/count-up/count-up.vue";
import useCharts from "@/hooks/useEcharts";
import type { EChartsOption } from "echarts";
import MonitoringPointsChart from "./monitoring-points-chart.vue";
import TrafficTrendChart from "./traffic-trend-chart.vue";
import WeatherChart from "./weather-chart.vue";
import eqm1Default from "@/assets/img/eqm/eqm1.png";
import eqm1Active from "@/assets/img/eqm/eqm1_active.png";
import eqm2Default from "@/assets/img/eqm/eqm2.png";
import eqm2Active from "@/assets/img/eqm/eqm2_active.png";
import eqm3Default from "@/assets/img/eqm/eqm3.png";
import eqm3Active from "@/assets/img/eqm/eqm3_active.png";
import eqm4Default from "@/assets/img/eqm/eqm4.png";
import eqm4Active from "@/assets/img/eqm/eqm4_active.png";
import { todayTrafficCount, trafficTrend } from "@/api/modules/index";
import { update } from "lodash-es";
// 车流量数据
const trafficData = {
  total: 0,
  car: {
    value: 0,
    percentage: 0,
    name: "小型车",
  },
  truck: {
    value: 0,
    percentage: 0,
    name: "货车",
  },
  bus: {
    value: 0,
    percentage: 0,
    name: "客车",
  },
};

// 监测点车流数据
const monitoringPointsData = reactive({
  points: [
    { name: "连镇", weeklyAvg: 19500, dailyTotal: 16500 },
    { name: "扬王", weeklyAvg: 12000, dailyTotal: 14500 },
    { name: "小庄", weeklyAvg: 10800, dailyTotal: 12300 },
    { name: "寨子", weeklyAvg: 21500, dailyTotal: 26800 },
    { name: "盐山", weeklyAvg: 19700, dailyTotal: 22000 },
  ],
});

// 交通流量趋势数据
const trafficTrendData = reactive({
  hours: ["00:00","01:00","02:00","03:00", "04:00","05:00","06:00","07:00", "08:00",  "09:00", "10:00", "11:00","12:00", 
      "13:00","14:00","15:00","16:00", "17:00","18:00","19:00","20:00","21:00","22:00","23:00", "24:00"],
  realTimeValues: [],
  averageValues: [],
});

// CountUp 配置
const countupOptions = {
  useEasing: true,
  useGrouping: true,
  separator: ",",
  decimal: ".",
  prefix: "",
  suffix: "",
};

// 图表容器引用
const chartRef = ref<HTMLElement | null>(null);

// 图表配置
const chartOptions: EChartsOption = {
  tooltip: {
    trigger: "item",
    formatter: "{b}: {c} ({d}%)",
  },
  legend: {
    show: false,
  },
  series: [
    {
      name: "车流量分布",
      type: "pie",
      radius: ["65%", "80%"],
      center: ["50%", "50%"],
      data: [
        {
          value: trafficData.car.value,
          name: trafficData.car.name,
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#FDBB67" },
                { offset: 1, color: "#FDBB67" },
              ],
            },
          },
        },
        {
          value: trafficData.truck.value,
          name: trafficData.truck.name,
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#59A2FC " },
                { offset: 1, color: "#59A2FC " },
              ],
            },
          },
        },
        {
          value: trafficData.bus.value,
          name: trafficData.bus.name,
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#00FFFF" },
                { offset: 1, color: "#00FFFF" },
              ],
            },
          },
        },
      ],
      emphasis: {
        scale: false,
        scaleSize: 10,
      },
      label: {
        show: false,
      },
    },
    {
      name: "内圈装饰",
      type: "pie",
      radius: ["50%", "52%"],
      center: ["50%", "50%"],
      silent: true,
      data: [{ value: 1 }],
      itemStyle: {
        color: "rgba(0, 255, 255, 0.15)",
      },
      label: {
        show: false,
      },
    },
  ],
  graphic: [
    {
      type: "text",
      left: "center",
      top: "38%",
      style: {
        text: trafficData.total.toLocaleString(),
        fill: "#00ffff",
        fontSize: 64,
        fontFamily: "Arial",
        fontWeight: "bold",
      },
    },
    {
      type: "text",
      left: "center",
      top: "58%",
      style: {
        text: "总量",
        fill: "#ffffff",
        fontSize: 32,
        fontFamily: "Alimama ShuHeiTi",
        fontWeight: "normal",
      },
    },
  ],
};
// 初始化图表
const { initCharts, setOptions } = useCharts(chartRef, chartOptions);
// 获取当前日期并格式化为 YYYY-MM-DD
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
const day = String(today.getDate()).padStart(2, '0');

const todayTime = ref(`${year}-${month}-${day}`);
// 确保图表在组件挂载后渲染
onMounted(async () => {
  initCharts();
  try {
    const query = {
      todayTime: todayTime.value
    };
    const res = await todayTrafficCount(query);
    if (res.data) {
      res.data.forEach((item) => {
        if (item.vehicleType == 1) { //小车
          trafficData.car.value = item.vehicleCount;
          trafficData.car.percentage = item.percentage;
        } else if (item.vehicleType == 2) { //货车
          trafficData.truck.value = item.vehicleCount;
          trafficData.truck.percentage = item.percentage;
        } else if (item.vehicleType == 3) { //客车
          trafficData.bus.value = item.vehicleCount;
          trafficData.bus.percentage = item.percentage;
        }
        trafficData.total = item.total;
      })
      // console.log(trafficData, 'trafficData')
    }
    chartOptions.series[0].data = [
      {
        value: trafficData.car.value,
        name: trafficData.car.name,
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#FDBB67" },
              { offset: 1, color: "#FDBB67" },
            ],
          },
        },
      },
      {
        value: trafficData.truck.value,
        name: trafficData.truck.name,
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#59A2FC" },
              { offset: 1, color: "#59A2FC" },
            ],
          },
        },
      },
      {
        value: trafficData.bus.value,
        name: trafficData.bus.name,
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#00FFFF" },
              { offset: 1, color: "#00FFFF" },
            ],
          },
        },
      },
    ];

    // 更新文本内容（如总量）
    chartOptions.graphic[0].style.text = trafficData.total.toLocaleString();

    // 调用 setOptions 方法重新渲染图表
    setOptions(chartOptions);
    trafficTrend({today: '2025-05-30', pileNum: ''}).then((res) => {
      console.log(res, '///////////////////')
      if (res.code == 200) {
        // 清空原有数据
        trafficTrendData.realTimeValues = [];
        trafficTrendData.averageValues = [];

        trafficTrendData.realTimeValues = [...res.data.map(item => item.total)];
        trafficTrendData.averageValues = [...res.data.map(item => item.avg)];
        console.log(trafficTrendData, 'trafficTrendData')
        // // 可选：重新渲染图表
        // trendChartInstance.setOption({
        //   series: [{
        //     data: trafficTrendData.realTimeValues
        //   }, {
        //     data: trafficTrendData.averageValues
        //   }]
        // });
      }
    })
  } catch (error) {
    console.error("请求设备列表失败:", error);
  }
  
});

// 趋势图时间范围选项
const timeRangeOptions = [
  { label: "总体", value: "all" },
  { label: "连镇", value: "lianzhen" },
  { label: "盐山", value: "yanshan" },
  { label: "寨子", value: "zhaizi" },
  { label: "莱芜", value: "laiwu" },
];

const selectedTimeRange = ref("all");

const handleTimeRangeChange = (event: Event) => {
  const target = event.target as HTMLSelectElement;
  selectedTimeRange.value = target.value;
  // 这里可以添加切换时间范围的逻辑
};
const items = ref([
{
    defaultImg: eqm1Default,
    activeImg: eqm1Active,
    isActive: true, // 默认选中
    type: '44',     // 
  },
  {
    defaultImg: eqm2Default,
    activeImg: eqm2Active,
    isActive: true,
    type: '22',     // 视频监控
  },
  {
    defaultImg: eqm3Default,
    activeImg: eqm3Active,
    isActive: true,
    type: '53',     // 广播
  },
  {
    defaultImg: eqm4Default,
    activeImg: eqm4Active,
    isActive: true,
    type: '15',     // 情报板
  },
]);

const toggleSelection = (index: number) => {
  items.value[index].isActive = !items.value[index].isActive;
  // 通知地图组件切换显示/隐藏
  window.dispatchEvent(new CustomEvent('toggle-map-device', {
    detail: { type: items.value[index].type, show: items.value[index].isActive }
  }));
};
</script>

<template>
  <div class="traffic-flow-grid">
    <div class="top">
      <div class="traffic-flow-item">
        <div class="item-title">今日车流量</div>
        <div class="item-content top-left">
          <div class="leftcont" ref="chartRef">
            <!-- 图表将在这里渲染 -->
          </div>
          <div class="rightcont">
            <div class="vehicle-stats">
              <div class="vehicle-item">
                <div class="vehicle-info">
                  <span class="vehicle-name">小型车</span>
                  <span class="percentage">{{ trafficData.car.percentage }}%</span>
                </div>
                <div class="vehicle-value car">
                  <count-up :end-val="trafficData.car.value" :options="countupOptions" />
                </div>
              </div>
              <div class="vehicle-item">
                <div class="vehicle-info">
                  <span class="vehicle-name">货车</span>
                  <span class="percentage">{{ trafficData.truck.percentage }}%</span>
                </div>
                <div class="vehicle-value truck">
                  <count-up :end-val="trafficData.truck.value" :options="countupOptions" />
                </div>
              </div>
              <div class="vehicle-item">
                <div class="vehicle-info">
                  <span class="vehicle-name">客车</span>
                  <span class="percentage">{{ trafficData.bus.percentage }}%</span>
                </div>
                <div class="vehicle-value bus">
                  <count-up :end-val="trafficData.bus.value" :options="countupOptions" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="traffic-flow-item">
        <div class="item-title">气象</div>
        <div class="item-content">
          <WeatherChart />
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="traffic-flow-item">
        <div class="item-title">今日各监测点车流情况</div>
        <div class="item-content">
          <monitoring-points-chart :data="monitoringPointsData.points"></monitoring-points-chart>
        </div>
      </div>
      <div class="traffic-flow-item">
        <div class="item-title">
          交通流量趋势
          <div class="dropdown-container">
            <select v-model="selectedTimeRange" @change="handleTimeRangeChange" class="custom-select">
              <option v-for="option in timeRangeOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </option>
            </select>
          </div>
        </div>
        <div class="item-content">
          <traffic-trend-chart :data="trafficTrendData"></traffic-trend-chart>
        </div>
        <div class="eqmMange">
          <div v-for="(item, index) in items" :key="index" class="eqm-item" :class="{ active: item.isActive }"
            @click="toggleSelection(index)"
            :style="{ backgroundImage: `url(${item.isActive ? item.activeImg : item.defaultImg})` }"></div>
        </div>
      </div>

    </div>
  </div>
</template>

<style scoped lang="scss">
.traffic-flow-grid {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;

  .top {
    flex: 1;
    width: 100%;
    display: flex;

    .traffic-flow-item {
      flex: 1;

      .item-title {
        width: 1080px;
        height: 104px;
        background-image: url("../../assets/img/leftoright/title.png");
        margin-left: 48px;
        margin-top: 48px;
        font-family: Alimama ShuHeiTi, Alimama ShuHeiTi;
        font-weight: 700;
        font-size: 52px;
        color: #ffffff;
        line-height: 104px;
        padding-left: 56px;
        letter-spacing: 2px;
        text-shadow: 0px 4px 0px #095a8c;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }

      .item-content {
        width: 1080px;
        height: 948px;
        margin-left: 48px;
        margin-top: 32px;
        background-image: url("../../assets/img/leftoright/content.png");
        padding: 40px;
      }
    }

    .top-left {
      display: flex;

      .leftcont {
        width: 744px;
        height: 744px;
        margin-top: 102px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .rightcont {
        flex: 1;
        height: 744px;
        /* margin-top: 102px; */
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        padding: 40px 20px;
        background-color: transparent;

        .vehicle-stats {
          width: 100%;
          margin-top: 120px;

          .vehicle-item {
            margin-bottom: 48px;

            .vehicle-info {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12px;
              border-bottom: 1px solid rgba(186, 213, 255, 0.5);
              padding-bottom: 16px;

              .vehicle-name {
                font-size: 32px;
                color: #ffffff;
                font-family: "Alimama ShuHeiTi";
              }

              .percentage {
                font-size: 32px;
                color: #ffffff;
                font-weight: normal;
              }
            }

            .vehicle-value {
              font-size: 46px;
              font-weight: bold;
              margin-bottom: 12px;
              font-family: "Arial";
              padding: 0 12px;
              border-radius: 12px;

              &.car {
                border-radius: 8px 8px 8px 8px;
                background: rgba(253, 187, 103, 0.1);
                color: #FDBB67;
              }

              &.truck {
                color: #59A2FC;
                background-color: rgba(0, 200, 255, 0.1);
              }

              &.bus {
                color: #00FFFF;
                background-color: rgba(0, 255, 255, 0.1);
              }
            }

            .progress-bar {
              height: 24px;
              width: 100%;
              background-color: rgba(255, 255, 255, 0.1);
              border-radius: 12px;
              overflow: hidden;
              position: relative;

              .progress-inner {
                height: 100%;
                position: relative;
                border-radius: 12px;
                transition: width 1s ease-in-out;

                &.car {
                  background: linear-gradient(90deg, #00ffff 0%, #00e3ff 100%);
                }

                &.truck {
                  background: linear-gradient(90deg, #ffb980 0%, #ffaa70 100%);
                }

                &.bus {
                  background: linear-gradient(90deg, #4ecee6 0%, #4eb5e6 100%);
                }
              }
            }
          }
        }
      }
    }
  }

  .bottom {
    flex: 1;
    width: 100%;
    display: flex;

    .traffic-flow-item {
      flex: 1;
      position: relative;

      .item-title {
        width: 1080px;
        height: 104px;
        background-image: url("../../assets/img/leftoright/title.png");
        margin-left: 48px;
        margin-top: 48px;
        font-family: Alimama ShuHeiTi, Alimama ShuHeiTi;
        font-weight: 700;
        font-size: 52px;
        color: #ffffff;
        line-height: 104px;
        padding-left: 56px;
        letter-spacing: 2px;
        text-shadow: 0px 4px 0px #095a8c;
        text-align: left;
        font-style: normal;
        text-transform: none;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .dropdown-container {
          margin-right: 26px;
          display: flex;
          align-items: center;
          height: 100%;

          .custom-select {
            background: #304c76;
            border: 1px solid #59729a;
            color: #d4dce7;
            padding: 8px 16px;
            font-size: 24px;
            border-radius: 4px;
            outline: none;
            cursor: pointer;
            font-family: Alimama ShuHeiTi;
            display: flex;
            align-items: center;
            width: 184px;
            height: 64px;

            &:hover {
              background: #304b75;
            }

            option {
              background: #081934;
              color: #d4dce7;
              font-size: 24px;

              &:hover,
              &:focus {
                background: #304b75;
                color: #08a1b3;
              }
            }

            /* Webkit browsers specific styles */
            option:checked,
            option:hover {
              background: #304b75 !important;
              color: #08a1b3 !important;
              -webkit-text-fill-color: #08a1b3 !important;
            }
          }
        }
      }

      .item-content {
        width: 1080px;
        height: 948px;
        margin-left: 48px;
        margin-top: 32px;
        background-image: url("../../assets/img/leftoright/content.png");

        .monitoring-chart,
        .trend-chart {
          width: 100%;
          height: 100%;
          padding: 40px;
        }
      }
    }

    .eqmMange {
      position: absolute;
      width: 184px;
      height: 736px;
      margin-bottom: 0;
      background-image: url("../../assets/img/eqm.png");
      right: -260px;
      bottom: 60px;
    }
  }
}

.eqmMange {
  display: flex;
  flex-direction: column;
  // gap: 20px; /* 图片之间间距 */
  width: 184px;
  height: 736px;
  background-image: url("../../assets/img/eqm.png");
  right: -100px;
  bottom: 60px;

  .eqm-item {
    width: 100%;
    height: 25%;
    /* 四个等分高度 */
    background-size: cover;
    background-position: center;
    cursor: pointer;
    transition: transform 0.2s ease-in-out;

    &.active {
      transform: scale(1.05);
      /* 可选效果：放大一点表示激活 */
    }
  }
}
</style>
