<template>
  <commonFilterChart
    :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 commonFilterChart from '@/components/common/echartCard/commonFilterChart.vue';
import { getAllUserTaskCompleteStatisticsApi } from '@/api/project/node';
import { useDict } from '@/utils/useDict';

const { TASK_ACHIEVE_STATUS } = useDict('TASK_ACHIEVE_STATUS');
const props = defineProps({
  statusColorList: {
    type: Array,
    default: () => [],
  },
});
// 初始化用户组项目统计
const chartOption = ref();
const getProjectGroupTaskCompleteStatistics = async (formData: any) => {
  const xData: any = [];
  let legendData: any = [];
  let seriesData: any = [];
  let colors: 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_ACHIEVE_STATUS.value.O[item] || item;
      }) || [];
    colors = res.data?.allExeStatus.map((item: any) => {
      return props.statusColorList[Number(item) - 1];
    });
    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_ACHIEVE_STATUS.value.O).find(
                (key) => TASK_ACHIEVE_STATUS.value.O[key] === statusName
              ) || statusName;
            if (statusKey) {
              // 如果 statusCount 中有这个状态，使用其值，否则使用 0
              seriesItem.data.push(item.statusCount?.[statusKey] || '');
            }
          }
        });
      });
    }
  }
  return {
    xData,
    seriesData,
    legendData,
    colors,
  };
};
const initProjectTaskCompleteChart = async (formData: any) => {
  const { xData, seriesData, legendData, colors } =
    await getProjectGroupTaskCompleteStatistics(formData);

  chartOption.value = {
    color: colors,
    legend: {
      data: legendData,
    },
    grid: {
      bottom: '50',
    },
    xAxis: {
      data: xData,
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
};
</script>
