<template>
  <commonChart
    :title="$t('数据统计.项目任务完成情况统计')"
    :charts-id="'chart-projectTaskComplete'"
    :bar-type="'barChart'"
    :option="chartOption"
    :filterItems="['projectName', 'projectCode']"
    :projectMultiple="true"
    @update="initProjectTaskCompleteChart"
  />
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import commonChart from '@/components/common/echartCard/commonChart.vue';
import { TASK_PROCESS_STATUS_OBJ } from '@/utils/enum/task';
import { getAllUserTaskCompleteStatisticsApi } from '@/api/project/node';

const props = defineProps({
  statusColorList: {
    type: Array,
    default: () => [],
  },
});
// 初始化用户组项目统计
const chartOption = ref();
const getProjectGroupTaskCompleteStatistics = async (formData: any) => {
  const xData: any = [];
  let legendData: any = [];
  let seriesData: any = [];
  const res: any = await getAllUserTaskCompleteStatisticsApi({
    tag1List: formData.tag1 ? formData.tag1.split(',') : [],
  });
  if (res.code === 200) {
    legendData =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_PROCESS_STATUS_OBJ[item];
      }) || [];

    seriesData = legendData?.map((item: any) => {
      return {
        name: item,
        type: 'bar',
        stack: 'total',
        data: [],
        label: {
          show: true,
          formatter: (params: any) => {
            return params.value;
          },
        },
      };
    });
    if (res.data?.result) {
      res.data.result.forEach((item: any) => {
        if (item.userName) {
          xData.push(item.userName);
        }
        // 遍历所有状态
        legendData.forEach((statusName: string) => {
          // 找到对应的 seriesItem
          const seriesItem = seriesData.find((item: any) => item.name === statusName);
          if (seriesItem) {
            // 获取状态对应的 key
            const statusKey = Object.keys(TASK_PROCESS_STATUS_OBJ).find(
              (key) => TASK_PROCESS_STATUS_OBJ[key] === statusName
            );
            if (statusKey) {
              // 如果 statusCount 中有这个状态，使用其值，否则使用 0
              seriesItem.data.push(item.statusCount?.[statusKey] || '');
            }
          }
        });
      });
    }
  }
  return {
    xData,
    seriesData,
    legendData,
  };
};
const initProjectTaskCompleteChart = async (formData: any) => {
  const { xData, seriesData, legendData } = await getProjectGroupTaskCompleteStatistics(formData);

  chartOption.value = {
    color: props.statusColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      show: true,
      top: '0%',
      left: 'center',
      data: legendData,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
};
</script>
