<template>
  <commonFilterChart
    :title="
      resultTagType === 'mechine'
        ? $t('数据统计.任务完成统计（机台）')
        : $t('数据统计.任务完成统计（学科）')
    "
    :charts-id="'taskCompletion-' + resultTagType"
    :bar-type="'barChart'"
    :option="chartOption"
    :filterItems="['projectName', 'projectCode']"
    @update="initTaskCompleteChart"
  />
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import commonFilterChart from '@/components/common/echartCard/commonFilterChart.vue';
import {
  getCommonCompleteStatisticsApi,
  getTaskCompleteStatisticsByDisciplineApi,
} from '@/api/project/node';
import { useDict } from '@/utils/useDict';

const { TASK_ACHIEVE_STATUS } = useDict('TASK_ACHIEVE_STATUS');
const props = defineProps({
  // x轴 机台、学科discipline
  resultTagType: {
    type: String,
    default: '',
  },
  statusColorList: {
    type: Array,
    default: () => [],
  },
});

const chartOption = ref();
const initTaskCompleteChart = async (formData: any) => {
  let xData: any = [];
  let titles: any = [];
  const seriesData: any = [];
  const params =
    props.resultTagType == 'mechine'
      ? {
          queryType: 'task',
          resultTagType: 'tag4', // 机台
          ...formData,
        }
      : {
          ...formData,
        };
  const api =
    props.resultTagType == 'mechine'
      ? getCommonCompleteStatisticsApi
      : getTaskCompleteStatisticsByDisciplineApi;
  const res: any = await api({
    ...params,
  });
  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_ACHIEVE_STATUS.value.O[item] || item;
      }) || [];
    const colors = res.data?.allExeStatus.map((item: any) => {
      return props.statusColorList[Number(item) - 1];
    });
    const names = res.data?.allExeStatus || [];

    for (let i = 0; i < names.length; i++) {
      const str = names[i];
      const obj: any = {
        name: TASK_ACHIEVE_STATUS.value.O[str] || str,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };

      for (let j = 0; j < res.data.result.length; j++) {
        obj.data.push(res.data.result[j]?.statusCount[str] || 0);
      }

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