<template>
  <div class="gl-page-content-grey-full">
    <div class="content">
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.任务完成统计机台')"
          :charts-id="'chart-4'"
          :bar-type="'barChart'"
          :nodata="taskCompletionAtWorkstations?.xAxis.data.length === 0"
          :option="taskCompletionAtWorkstations"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.任务完成统计学科')"
          :charts-id="'chart-5'"
          :bar-type="'barChart'"
          :nodata="taskCompletionAtDisciplineOption?.xAxis.data.length === 0"
          :option="taskCompletionAtDisciplineOption"
        >
        </EchartCard>
      </div>
      <!-- 新增 任务达成统计  工位/学科 -->
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.任务达成统计机台')"
          :charts-id="'chart-Quality-1'"
          :bar-type="'barChart'"
          :nodata="taskAchieveAtWorkstations?.xAxis.data.length === 0"
          :option="taskAchieveAtWorkstations"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.任务达成统计学科')"
          :charts-id="'chart-Quality-2'"
          :bar-type="'barChart'"
          :nodata="taskAchieveAtDisciplineOption?.xAxis.data.length === 0"
          :option="taskAchieveAtDisciplineOption"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.指标完成统计机台')"
          :charts-id="'chart-6'"
          :bar-type="'barChart'"
          :nodata="performanceCompletionAtWorkstationsOption?.xAxis.data.length === 0"
          :option="performanceCompletionAtWorkstationsOption"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.指标完成统计学科')"
          :charts-id="'chart-7'"
          :bar-type="'barChart'"
          :nodata="performanceCompletionAtDisciplineOption?.xAxis.data.length === 0"
          :option="performanceCompletionAtDisciplineOption"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.成员任务进度统计')"
          :charts-id="'chart-2'"
          :bar-type="'barChart'"
          :nodata="userTaskCompleteOption?.xAxis.data.length === 0"
          :option="userTaskCompleteOption"
        >
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('统计分析.难度系数统计')"
          :charts-id="'chart-3'"
          :bar-type="'barChart'"
          :nodata="userDifficultyCoefficientOption?.xAxis.data.length === 0"
          :option="userDifficultyCoefficientOption"
        >
        </EchartCard>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue';
import EchartCard from '@/components/common/echartCard/index.vue';
import {
  getTaskCompleteStatisticsApi,
  getTaskAchieveStatisticsApi,
  getPerformanceCompleteStatisticsApi,
  getUserDifficultyStatisticsApi,
  getUserTaskCompleteStatisticsApi,
} from '@/api/project/task';
import { useDict } from '@/utils/useDict';
import { TASK_CALCULATE_STATUS_OPTIONS } from '@/utils/enum/task';
import { getThemeColor } from '@/utils/theme';

const { TASK_EXE_STATUS, DIFFICULTY_COEFFICIENT } = useDict(
  'TASK_EXE_STATUS',
  'DIFFICULTY_COEFFICIENT'
);
const taskCalculateStatusLegendData = TASK_CALCULATE_STATUS_OPTIONS.map((item) => ({
  name: item.label,
}));
const taskExeStatusLegendData = TASK_EXE_STATUS.value.A.map((item: any) => {
  return {
    name: item.label,
  };
});

interface Props {
  projectUuid: string;
}

const props = withDefaults(defineProps<Props>(), {
  projectUuid: '',
});

const currentProjectUuid = ref('');
watchEffect(() => {
  if (props.projectUuid) {
    currentProjectUuid.value = props.projectUuid;
  }
});

// 进度状态颜色列表：已驳回、未开始、进行中、已完成、已暂停、已关闭、已延期
const statusColorList = [
  getThemeColor('--el-color-danger'),
  'rgb(200, 201, 204)',
  getThemeColor('--el-color-primary'),
  getThemeColor('--el-color-success'),
  getThemeColor('--el-color-warning'),
  'rgb(222, 223, 224)',
  'rgb(250, 182, 182)',
  'rgb(179, 225, 157)', // 已闭环
];

// 完成情况颜色列表：未分析、不合格、合格
const completionStatusColorList = [
  getThemeColor('--el-color-info'),
  getThemeColor('--el-color-danger'),
  getThemeColor('--el-color-success'),
];
const difficultyCountColorList = [
  '#67c23a',
  'rgb(179, 225, 157)',
  'rgb(248, 227, 197)',
  'rgb(243, 209, 158)',
  'rgb(248, 152, 152)',
  '#f56c6c',
];
// 封装方法，根据对象的某个属性对对象数组进行排序 升序
const sortObjectArray = (arr: any, key: any) => {
  return arr.sort((a: any, b: any) => {
    return a[key] - b[key];
  });
};

// 成员任务进度统计
const userTaskCompleteOption = ref();
const getUserTaskCompleteStatistics = async () => {
  const xData: any = [];
  const seriesData: any = [];
  const res: any = await getUserTaskCompleteStatisticsApi({
    tag1: currentProjectUuid.value,
  });
  if (res.code === 200) {
    res.data.result.forEach((item: any) => {
      xData.push(item.userName);
    });
    for (let i = 0; i < TASK_EXE_STATUS.value.A.length; i++) {
      const item = TASK_EXE_STATUS.value.A[i];
      const obj: any = {
        name: item.label,
        stack: 'total',
        emphasis: {
          focus: 'series',
        },
        data: [],
        label: {
          show: true,
          formatter: function (params: { value: any }) {
            // 当值为0时返回空字符串
            return params.value === 0 ? '' : params.value;
          },
        },
      };
      for (let j = 0; j < res.data.result.length; j++) {
        obj.data.push(res.data.result[j]?.statusCount[item.value] || 0);
      }
      seriesData.push(obj);
    }
  }
  return {
    xData,
    seriesData,
  };
};
const queryUserTaskCompletion = async () => {
  const { xData, seriesData } = await getUserTaskCompleteStatistics();
  const option = {
    color: statusColorList,
    legend: {
      data: taskExeStatusLegendData,
    },
    grid: {
      bottom: '50',
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 5,
    series: seriesData,
  };
  userTaskCompleteOption.value = { ...option };
};

// 难度系数统计
const getDifficultyLevel = (difficulty: number) => {
  const str = DIFFICULTY_COEFFICIENT.value.O[difficulty];
  return str ? str : '难度系数';
};
const userDifficultyCoefficientOption = ref();
const queryUserDifficultStatistics = async () => {
  let xData: any = [];
  let titles: any = [];
  const seriesData: any = [];
  const res: any = await getUserDifficultyStatisticsApi({
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.userName;
    });
    titles = res.data.alldifficultyValue;
    for (let i = 0; i < titles.length; i++) {
      const str = titles[i].toFixed(1);
      const obj: any = {
        name: getDifficultyLevel(Number(str)) + str,
        coefficient: Number(str),
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };
      for (let j = 0; j < res.data.result.length; j++) {
        obj.data.push(res.data.result[j]?.difficultyCount[str]);
      }
      seriesData.push(obj);
    }
  }
  const option = {
    color: difficultyCountColorList,
    legend: {
      data: titles,
    },
    grid: {
      bottom: '50',
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 5,
    series: sortObjectArray(seriesData, 'coefficient'),
  };
  userDifficultyCoefficientOption.value = { ...option };
};

// #region 任务完成统计机台
const taskCompletionAtWorkstations = ref();
const queryTaskCompletionByWorkspace = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getTaskCompleteStatisticsApi({
    resultTagType: 'tag4',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_EXE_STATUS.value.A.length; i++) {
      const item = TASK_EXE_STATUS.value.A[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };

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

      seriesData.push(obj);
    }
  }
  const option = {
    color: statusColorList,
    legend: {
      data: taskExeStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  taskCompletionAtWorkstations.value = { ...option };
  console.log('taskCompletionAtWorkstations.value', taskCompletionAtWorkstations.value);
};
// #endregion

// #region 任务完成统计学科
const taskCompletionAtDisciplineOption = ref();
const queryTaskCompletionByDiscipline = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getTaskCompleteStatisticsApi({
    resultTagType: 'tag6',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_EXE_STATUS.value.A.length; i++) {
      const item = TASK_EXE_STATUS.value.A[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };

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

      seriesData.push(obj);
    }
  }
  const option = {
    color: statusColorList,
    legend: {
      data: taskExeStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  taskCompletionAtDisciplineOption.value = { ...option };
};
// #endregion

// #region 新增 任务达成统计 —— 工位
const taskAchieveAtWorkstations = ref();
const queryTaskQualityByWorkspace = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getTaskAchieveStatisticsApi({
    resultTagType: 'tag4',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_CALCULATE_STATUS_OPTIONS.length; i++) {
      const item = TASK_CALCULATE_STATUS_OPTIONS[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };

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

      seriesData.push(obj);
    }
  }
  const option = {
    color: completionStatusColorList,
    legend: {
      data: taskCalculateStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  taskAchieveAtWorkstations.value = { ...option };
};

// 指标完成统计机台
const performanceCompletionAtWorkstationsOption = ref();
const queryPerfCompletionByWorkspace = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getPerformanceCompleteStatisticsApi({
    resultTagType: 'tag4',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_CALCULATE_STATUS_OPTIONS.length; i++) {
      const item = TASK_CALCULATE_STATUS_OPTIONS[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };
      for (let j = 0; j < res.data.result.length; j++) {
        obj.data.push(res.data.result[j]?.statusCount[item.value] || 0);
      }
      seriesData.push(obj);
    }
  }
  const option = {
    color: completionStatusColorList,
    legend: {
      data: taskCalculateStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  performanceCompletionAtWorkstationsOption.value = { ...option };
};

// #region 任务达成统计 —— 学科
const taskAchieveAtDisciplineOption = ref();
const queryTaskQualityByDiscipline = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getTaskAchieveStatisticsApi({
    resultTagType: 'tag6',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_CALCULATE_STATUS_OPTIONS.length; i++) {
      const item = TASK_CALCULATE_STATUS_OPTIONS[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };

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

      seriesData.push(obj);
    }
  }
  const option = {
    color: completionStatusColorList,
    legend: {
      data: taskCalculateStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  taskAchieveAtDisciplineOption.value = { ...option };
};

// 指标完成统计学科
const performanceCompletionAtDisciplineOption = ref();
const queryPerfCompletionByDiscipline = async () => {
  let xData: any = [];
  const seriesData: any = [];
  const res: any = await getPerformanceCompleteStatisticsApi({
    resultTagType: 'tag6',
    tag1: currentProjectUuid.value,
  });
  if (res && res.code === 200) {
    xData = res.data.result.map((item: any) => {
      return item.name;
    });
    for (let i = 0; i < TASK_CALCULATE_STATUS_OPTIONS.length; i++) {
      const item = TASK_CALCULATE_STATUS_OPTIONS[i];
      const obj: any = {
        name: item.label,
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [],
      };
      for (let j = 0; j < res.data.result.length; j++) {
        obj.data.push(res.data.result[j]?.statusCount[item.value] || 0);
      }
      seriesData.push(obj);
    }
  }
  const option = {
    color: completionStatusColorList,
    legend: {
      data: taskCalculateStatusLegendData,
    },
    xAxis: {
      data: xData,
    },
    yAxis: {
      minInterval: 1,
    },
    dataZoom: xData.length > 4,
    series: seriesData,
  };
  performanceCompletionAtDisciplineOption.value = { ...option };
};

const initData = async () => {
  // 按工位仿真任务达成统计：传项目id，工位id，查各个工位下任务的状态  完成、进行中、驳回等
  await queryTaskCompletionByWorkspace();
  // 按学科仿真任务达成统计：传项目id，学科id，查各个学科下任务的状态  完成、进行中、驳回等
  await queryTaskCompletionByDiscipline();
  // 按学科仿真指标达成统计：传项目id，学科id，查各个学科下任务的指标的达成状态  合格、不合格、未分析
  await queryPerfCompletionByWorkspace();
  // 按工位仿真指标达成统计：传项目id，学科id，查各个学科下任务的指标的达成状态  合格、不合格、未分析
  await queryPerfCompletionByDiscipline();
  // 成员任务进度统计：传项目id，查各个人完成和未完成的任务数量
  await queryUserTaskCompletion();
  // 难度系数统计：难度系数有1、2、3、4、5，统计1有几个，2有几个。。。
  await queryUserDifficultStatistics();

  // 新增
  // 按照工位统计任务质量达成情况
  await queryTaskQualityByWorkspace();
  // 按照学科统计任务质量达成情况
  await queryTaskQualityByDiscipline();
};
watchEffect(() => {
  if (props.projectUuid) {
    initData();
  }
});
onMounted(async () => {});
</script>
<style lang="scss" scoped>
.gl-page-content-grey-full {
  overflow: auto;

  .content {
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    overflow: auto;

    .margin-style {
      width: 100% !important;
    }

    .chart-box {
      width: calc(50% - 8px);
      height: 400px;
      position: relative;

      .el-form {
        width: 100%;
        display: flex;
        justify-content: flex-end;

        .el-form-item {
          margin-bottom: 0 !important;
          margin-right: 0 !important;

          .el-select {
            width: 215px;
          }

          .select-width {
            width: 90px !important;
          }

          .margin-right-12 {
            margin-right: 12px;
          }
        }
      }

      .chart-item {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
