import { defineComponent, ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Select } from "ant-design-vue";
import * as echarts from "echarts";
import dayjs from "@/utils/dayjs";

import { getSortedRoadDataByHour } from "./fetchData";
import { RoadInfoByHour, EnumRoadConfig } from "../../../store/roadUnit/types";
import { roadOccChartOption, roadSpeedChartOption } from "./chartOptions";

import { useStore } from "@/hook/useStore";
import useRoadUnitStore from "@/store/roadUnit";

import style from "@/assets/style/RoadUnit/roadInfo.module.less";
import backIcon from "@/assets/img/roadUnit/back.svg";

const { Option } = Select;

export default defineComponent({
  components: {
    Select,
    Option,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    /**
     * 选择的日期
     * 选中的道路名称
     * 区域通行车辆、车次、车速分日表
     */
    const { time, road: roadName, areaInfoByDate } = useStore(useRoadUnitStore);

    /**
     * 道路列表
     */
    const roadList = computed(() =>
      areaInfoByDate.value.map((road) => {
        return road.road_name;
      })
    );

    /**
     * 选中的道路信息
     */
    const checkedRoadDataByDate = computed(
      () =>
        areaInfoByDate.value.find((road) => {
          return road.road_name === roadName.value;
        }) || { pass_veh_num: 0, pass_veh_occ: 0, segments: [], road_name: "", mean_velocity: 0 }
    );

    /**
     * 道路车辆、车次、车速分时表
     * 用来渲染地图中选中的某条道路可视化路线
     * 用来渲染roadInfo页面车次、车速chart
     */
    const roadDataByHour = ref<RoadInfoByHour[]>();
    const getRoadDataByHour = async () => {
      const startTime = dayjs(time.value, "YYYY-MM-DD").format("YYYY-MM-DD HH:mm:ss");
      const endTime = dayjs(time.value, "YYYY-MM-DD").add(1, "day").format("YYYY-MM-DD HH:mm:ss");
      roadDataByHour.value = await getSortedRoadDataByHour(roadName.value, startTime, endTime);
      renderCharts();
    };
    onMounted(() => {
      getRoadDataByHour();
    });
    watch([roadName, time], () => {
      getRoadDataByHour();
    });

    /**
     * 渲染车次、车速chart
     */
    const occChart = ref<HTMLDivElement>();
    const speedChart = ref<HTMLDivElement>();
    let speedChartIns: echarts.ECharts | undefined;
    let occChartIns: echarts.ECharts | undefined;
    const renderCharts = () => {
      const times = [] as any[],
        occPass = [] as any[],
        speedPass = [] as any[];
      let occMax = 0,
        speedMax = 0;
      roadDataByHour.value?.forEach((item) => {
        occPass.push(item.pass_veh_occ);
        speedPass.push(item.mean_velocity);
        times.push(dayjs(item.count_time, "YYYY-MM-DD HH:mm:ss").format("HH"));
        occMax = occMax > item.pass_veh_occ ? occMax : item.pass_veh_occ;
        speedMax = speedMax > item.mean_velocity ? speedMax : item.mean_velocity;
      });
      roadSpeedChartOption.xAxis.data = roadOccChartOption.xAxis.data = times;
      roadOccChartOption.series[0].data = occPass;
      roadSpeedChartOption.series[0].data = speedPass;
      roadOccChartOption.yAxis.interval = occMax / 4 < 10 ? 10 : Math.floor(occMax / 4 / 10) * 10;
      roadSpeedChartOption.yAxis.interval = speedMax / 4 < 10 ? 10 : Math.floor(speedMax / 4 / 10) * 10;

      if (occChart.value) {
        occChartIns || (occChartIns = echarts.init(occChart.value));
        occChartIns.setOption(roadOccChartOption);
      }
      if (speedChart.value) {
        speedChartIns || (speedChartIns = echarts.init(speedChart.value));
        speedChartIns.setOption(roadSpeedChartOption);
      }
    };

    /**
     * 道路切换
     */
    const onRoadChange = (e: any) => {
      router.replace({
        path: route.path,
        query: {
          ...route.query,
          road: e,
        },
      });
    };

    /**
     * 跳转区域页面
     */
    const goBack = () => {
      const { mode, area, time } = route.query;
      router.replace({
        path: route.path,
        query: { mode, area, time },
      });
    };

    /**
     * 跳转道路配置页面
     */
    const goHandleConfig = () => {
      router.replace({
        path: route.path,
        query: {
          ...route.query,
          roadConfig: EnumRoadConfig.开,
        },
      });
    };

    return () => (
      <div class={style.road}>
        <div class={style.backButton} onClick={() => goBack()}>
          <img src={backIcon} />
          <span>返回</span>
        </div>
        <div class={style.roadSelect}>
          <Select value={roadName.value} onChange={(e) => onRoadChange(e)}>
            {roadList.value.map((item, index) => (
              <Option key={index} value={item}>
                {item}
              </Option>
            ))}
          </Select>
          <span class={style.roadConfig} onClick={() => goHandleConfig()}>
            道路特征设置
          </span>
        </div>
        <div class={style.statistics}>
          <div>
            <span class={style.title}>通行车辆数</span>
            <div>
              <span class={style.count}>{checkedRoadDataByDate.value.pass_veh_num}</span>
              <span class={style.unit}>辆</span>
            </div>
          </div>
          <div>
            <span class={style.title}>通行车次</span>
            <div>
              <span class={style.count}>{checkedRoadDataByDate.value.pass_veh_occ}</span>
              <span class={style.unit}>车次</span>
            </div>
          </div>
        </div>
        <div class={style.chart} ref={occChart}></div>
        <div class={style.speed}>
          <div>
            <span class={style.title}>平均速度</span>
            <div>
              <span class={style.count}>{checkedRoadDataByDate.value.mean_velocity}</span>
              <span class={style.unit}>km/h</span>
            </div>
          </div>
        </div>
        <div class={style.chart} ref={speedChart}></div>
      </div>
    );
  },
});
