import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import { getCollaborationMonthlyStatisticsApi } from "@/api/collaboration/record";

export function useCollaborationStatisticsHook() {
  const currentYear = new Date().getFullYear();
  const selectedYear = ref(currentYear);
  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(
      selectedYear.value
    );
    renderChart(data);
  }

  function renderChart(data) {
    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(() => {
    getStatistics();
    window.addEventListener("resize", resizeChart);
  });

  return {
    chartRef,
    selectedYear,
    yearOptions,
    getStatistics
  };
}
