import { computed, onMounted, ref } from "vue";
import * as echarts from "echarts";
import {
  CollaborationMonthlyStatisticsResponse,
  getCollaborationMonthlyStatisticsApi
} from "@/api/collaboration/record";
import { getUserListApi, UserDTO } from "@/api/system/user";
import { useUserStoreHook } from "@/store/modules/user";

export function useCollaborationStatisticsHook() {
  const userStore = useUserStoreHook();
  const isAdmin = computed(() => userStore.roles?.includes("admin"));
  const currentYear = new Date().getFullYear();
  const selectedYear = ref(currentYear);
  const selectedCreatorId = ref<number>();
  const creatorOptions = ref<UserDTO[]>([]);
  const yearOptions = Array.from(
    { length: currentYear - 2012 },
    (_, index) => currentYear - index
  );
  const chartRef = ref<HTMLElement>();
  let chart: echarts.ECharts | undefined;

  async function getStatistics() {
    const { data } = await getCollaborationMonthlyStatisticsApi({
      year: selectedYear.value,
      creatorId: selectedCreatorId.value
    });
    renderChart(data);
  }

  async function getCreatorOptions() {
    if (!isAdmin.value) return;
    const { data } = await getUserListApi({ pageNum: 1, pageSize: 1000 });
    creatorOptions.value = data.rows;
  }

  function getUserDisplayName(user: UserDTO) {
    return user.nickname || user.username || "";
  }

  function renderChart(data: CollaborationMonthlyStatisticsResponse[]) {
    chart?.dispose();
    chart = echarts.init(chartRef.value);
    chart.setOption({
      tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
      legend: {
        data: ["拍单费用", "支出费用", "已结稿费", "已结总费用"],
        top: "2%",
        right: "0"
      },
      grid: { left: "0%", right: "0%", bottom: "0%", containLabel: true },
      xAxis: { type: "category", data: data.map(item => `${item.month}月`) },
      yAxis: { type: "value" },
      series: [
        buildSeries(
          "拍单费用",
          data.map(item => item.purchasePrice),
          "#ffbe00"
        ),
        buildSeries(
          "支出费用",
          data.map(item => item.expenditureAmount),
          "#f56c6c"
        ),
        buildSeries(
          "已结稿费",
          data.map(item => item.settledRemuneration),
          "#409eff"
        ),
        buildSeries(
          "已结总费用",
          data.map(item => item.settledTotal),
          "#67c23a"
        )
      ]
    });
  }

  function buildSeries(name: string, data: number[], color: string) {
    return {
      name,
      data,
      type: "bar",
      color
    };
  }

  function resizeChart() {
    chart?.resize({ width: "auto" });
  }

  onMounted(() => {
    getCreatorOptions();
    getStatistics();
    window.addEventListener("resize", resizeChart);
  });

  return {
    chartRef,
    selectedYear,
    selectedCreatorId,
    yearOptions,
    creatorOptions,
    isAdmin,
    getUserDisplayName,
    getStatistics
  };
}
