<template>
  <commonFilterChart
    :title="$t('数据统计.用户组任务完成情况统计')"
    :charts-id="'chart-2-UserTaskComplete'"
    :bar-type="'barChart'"
    :option="chartOption"
    :filterItems="['userGroup', 'user', 'projectName', 'projectCode', 'discipline']"
    @update="initUserTaskCompleteChart"
  />
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import commonFilterChart from '@/components/common/echartCard/commonFilterChart.vue';
import { getUserGroupTaskCompleteStatisticsApi } 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 getUserGroupTaskCompleteStatistics = async (formData: any) => {
  const xData: any = [];
  let legendData: any = [];
  let seriesData: any = [];
  let colors: any = [];
  const res: any = await getUserGroupTaskCompleteStatisticsApi({
    ...formData,
  });
  if (res.code === 200) {
    legendData =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_ACHIEVE_STATUS.value.O[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
            );
            if (statusKey) {
              // 如果 statusCount 中有这个状态，使用其值，否则使用 0
              seriesItem.data.push(item.statusCount?.[statusKey] || '');
            }
          }
        });
      });
    }
  }
  return {
    xData,
    seriesData,
    legendData,
    colors,
  };
};
// 初始化用户组项目统计
const chartOption = ref();
const initUserTaskCompleteChart = async (formData: any) => {
  const { xData, seriesData, legendData, colors } =
    await getUserGroupTaskCompleteStatistics(formData);
  chartOption.value = {
    color: colors,
    legend: {
      data: legendData,
    },
    grid: {
      bottom: '50',
    },
    xAxis: {
      data: xData,
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
};
</script>
