<template>
  <div class="gl-page-content-grey">
    <div class="content">
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.用户组项目统计')"
          ref="userProjectChartRef"
          :charts-id="'chart-1'"
          :bar-type="'barChart'"
          @refresh="changeUserGroupProjectFun"
        >
          <template #formSlot>
            <el-form :model="userProjectFromData" label-width="auto">
              <el-form-item label="用户组">
                <el-select
                  class="select-width margin-right-12"
                  v-model="userProjectFromData.userGroupId"
                  @change="
                    () => {
                      userProjectFromData.userId = '';
                      changeUserGroupProjectFun();
                    }
                  "
                >
                  <el-option
                    v-for="item in userGroupOptions"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="用户">
                <userSelectByGroup
                  class="select-width margin-right-12"
                  :groupId="userProjectFromData.userGroupId"
                  v-model="userProjectFromData.userId"
                  @change="changeUserGroupProjectFun"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.用户组任务完成情况统计')"
          ref="userTaskCompleteChartRef"
          :charts-id="'chart-2'"
          :bar-type="'barChart'"
          @refresh="userTaskCompleteProjectChangeFun"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="用户组">
                <el-select
                  class="select-width margin-right-12"
                  v-model="userTaskCompleteFormData.userGroupId"
                  @change="
                    () => {
                      userTaskCompleteFormData.userId = '';
                      userTaskCompleteProjectChangeFun();
                    }
                  "
                >
                  <el-option
                    v-for="item in userGroupOptions"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="用户">
                <userSelectByGroup
                  class="select-width"
                  :groupId="userTaskCompleteFormData.userGroupId"
                  v-model="userTaskCompleteFormData.userId"
                  @change="userTaskCompleteProjectChangeFun"
                />
              </el-form-item>
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="userTaskCompleteFormData.tag1"
                  @change="userTaskCompleteProjectChangeFun"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="userTaskCompleteFormData.tag1"
                  :showCodeList="true"
                  @change="userTaskCompleteProjectChangeFun"
                />
              </el-form-item>
              <el-form-item label="学科">
                <el-select
                  v-model="userTaskCompleteFormData.discipline"
                  clearable
                  class="select-width margin-right-12"
                  @change="userTaskCompleteProjectChangeFun"
                >
                  <el-option
                    v-for="item in DISCIPLINE_TYPE.A"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.用户组难度系数统计')"
          ref="userDifficultyCoefficientChartRef"
          :charts-id="'chart-3'"
          :bar-type="'barChart'"
          @refresh="initUserDifficultyCoefficientStatistics"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="用户组">
                <el-select
                  class="select-width margin-right-12"
                  v-model="userDifficultyCoefficientFormData.userGroupId"
                  @change="
                    () => {
                      userDifficultyCoefficientFormData.userId = '';
                      initUserDifficultyCoefficientStatistics();
                    }
                  "
                >
                  <el-option
                    v-for="item in userGroupOptions"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="用户">
                <userSelectByGroup
                  class="select-width"
                  :groupId="userDifficultyCoefficientFormData.userGroupId"
                  v-model="userDifficultyCoefficientFormData.userId"
                  @change="initUserDifficultyCoefficientStatistics"
                />
              </el-form-item>
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="userDifficultyCoefficientFormData.tag1"
                  @change="initUserDifficultyCoefficientStatistics"
                />
                <!-- <el-select clearable class="select-width margin-right-12" v-model="userDifficultyCoefficientFormData.tag1" @change="initUserDifficultyCoefficientStatistics">
                  <el-option v-for="item in projectOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="userDifficultyCoefficientFormData.tag1"
                  :showCodeList="true"
                  @change="initUserDifficultyCoefficientStatistics"
                />
              </el-form-item>
              <el-form-item label="学科">
                <el-select
                  clearable
                  class="select-width margin-right-12"
                  v-model="userDifficultyCoefficientFormData.discipline"
                  @change="initUserDifficultyCoefficientStatistics"
                >
                  <el-option
                    v-for="item in DISCIPLINE_TYPE.A"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.任务完成统计（机台）')"
          ref="taskCompletionAtWorkstationsChartRef"
          :charts-id="'chart-4'"
          :bar-type="'barChart'"
          @refresh="initTaskCompletionAtWorkstations"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="taskCompletionAtWorkstationsFormData.tag1"
                  @change="initTaskCompletionAtWorkstations"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="taskCompletionAtWorkstationsFormData.tag1"
                  :showCodeList="true"
                  @change="initTaskCompletionAtWorkstations"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.任务完成统计（学科）')"
          ref="taskCompletionAtDisciplineChartRef"
          :charts-id="'chart-5'"
          :bar-type="'barChart'"
          @refresh="initTaskCompletionAtDiscipline"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initTaskCompletionAtDisciplineFormData.tag1"
                  @change="initTaskCompletionAtDiscipline"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initTaskCompletionAtDisciplineFormData.tag1"
                  :showCodeList="true"
                  @change="initTaskCompletionAtDiscipline"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.指标完成统计（机台）')"
          ref="performanceCompletionAtWorkstationsChartRef"
          :charts-id="'chart-6'"
          :bar-type="'barChart'"
          @refresh="initPerformanceCompletionAtWorkstations"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initPerformanceCompletionAtWorkstationsFormData.tag1"
                  @change="initPerformanceCompletionAtWorkstations"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initPerformanceCompletionAtWorkstationsFormData.tag1"
                  :showCodeList="true"
                  @change="initPerformanceCompletionAtWorkstations"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.指标完成统计（学科）')"
          ref="performanceCompletionAtDisciplineChartRef"
          :charts-id="'chart-7'"
          :bar-type="'barChart'"
          @refresh="initPerformanceCompletionAtDiscipline"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initPerformanceCompletionAtDisciplineFormData.tag1"
                  @change="initPerformanceCompletionAtDiscipline"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="initPerformanceCompletionAtDisciplineFormData.tag1"
                  :showCodeList="true"
                  @change="initPerformanceCompletionAtDiscipline"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.工位评审通过统计')"
          ref="reviewPassedChartRef"
          :charts-id="'chart-8'"
          :bar-type="'barChart'"
          @refresh="reviewPassedChangeFun"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="reviewPassedChartFormData.tag1"
                  @change="reviewPassedChangeFun"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="reviewPassedChartFormData.tag1"
                  :showCodeList="true"
                  @change="reviewPassedChangeFun"
                />
              </el-form-item>
              <el-form-item label="学科">
                <el-select
                  v-model="reviewPassedChartFormData.discipline"
                  clearable
                  class="select-width margin-right-12"
                  @change="reviewPassedChangeFun"
                >
                  <el-option
                    v-for="item in DISCIPLINE_TYPE.A"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
      <div class="chart-box">
        <EchartCard
          :title="$t('数据统计.项目任务完成情况统计')"
          ref="projectTaskCompleteChartRef"
          :charts-id="'chart-9'"
          :bar-type="'barChart'"
          @refresh="projectTaskCompleteProjectChangeFun"
        >
          <template #formSlot>
            <el-form label-width="auto">
              <el-form-item label="项目名称">
                <ProjectSelect
                  class="select-width margin-right-12"
                  :multiple="true"
                  v-model="projectTaskCompleteFormData.tag1List"
                  @change="projectTaskCompleteProjectChangeFun"
                />
              </el-form-item>
              <el-form-item label="项目编号">
                <ProjectSelect
                  class="select-width margin-right-12"
                  v-model="projectTaskCompleteFormData.tag1List"
                  :showCodeList="true"
                  :multiple="true"
                  @change="projectTaskCompleteProjectChangeFun"
                />
              </el-form-item>
            </el-form>
          </template>
        </EchartCard>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import EchartCard from '@/components/common/echartCard/index.vue';
import UserSelect from '@/components/common/userSelect/index.vue';
import userSelectByGroup from '@/components/common/userSelect/userSelectByGroup.vue';
import { userQueryGroupApi } from '@/api/system/user';
import {
  getUserGroupProjectStatisticsApi,
  getUserGroupTaskCompleteStatisticsApi,
  getAllUserTaskCompleteStatisticsApi,
  queryNodeListApi,
  getWorkstationReviewStatisticsApi,
  getUserGroupDifficultyStatisticsApi,
  getCommonCompleteStatisticsApi,
  getTaskCompleteStatisticsByDisciplineApi,
  getPerformanceCompleteStatisticsByDisciplineApi,
} from '@/api/project/node';
import ProjectSelect from '@/components/common/projectSelect/index.vue';
import { TASK_CALCULATE_STATUS_OBJ, TASK_PROCESS_STATUS_OBJ } from '@/utils/enum/task';
import { getThemeColor } from '@/utils/theme';
import { useDict } from '@/utils/useDict';

const { DISCIPLINE_TYPE, DIFFICULTY_COEFFICIENT } = useDict(
  'DISCIPLINE_TYPE',
  'DIFFICULTY_COEFFICIENT'
);

const userGroupOptions = ref<any>([]);

const disciplineOptions = ref<any>([]);

const statusColorList = [
  'rgb(200, 201, 204)',
  getThemeColor('--el-color-primary'),
  getThemeColor('--el-color-danger'),
  getThemeColor('--el-color-success'),
  getThemeColor('--el-color-warning'),
  getThemeColor('--el-color-info'),
];
const performanceColorList = ['rgb(200, 201, 204)', 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 processNodeColorList = [
  'rgb(200, 201, 204)', // 未评审
  getThemeColor('--el-color-primary'), // 评审中
  getThemeColor('--el-color-success'), // 已通过
  getThemeColor('--el-color-danger'), // 已拒绝
];
// 封装方法，根据对象的某个属性对对象数组进行排序 升序
const sortObjectArray = (arr: any, key: any) => {
  return arr.sort((a: any, b: any) => {
    return a[key] - b[key];
  });
};
// const projectStorageSpaceStatisticsFormData = ref<any>({

//   userId: '',
// });
const userProjectChartRef = ref();
const changeUserGroupProjectFun = async () => {
  await initUserProjectStatistics();
};

const getUserGroupProjectStatistics = async () => {
  const xData: any = [];
  const yData: any = [];
  try {
    const res: any = await getUserGroupProjectStatisticsApi({ ...userProjectFromData.value });
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        xData.push(item.userName);
        yData.push(item.projectCount);
      });
    }
  } catch {}

  return {
    xData,
    yData,
  };
};
const initUserProjectStatistics = async () => {
  const { xData, yData } = await getUserGroupProjectStatistics();

  // 模拟接口延时
  if (!userProjectChartRef.value || !userProjectChartRef.value.commonChartRef) return;
  userProjectChartRef.value.commonChartRef.disposeEchartsByKey('chart-1');
  userProjectChartRef.value.commonChartRef.option = {
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      show: false,
      top: '0%',
      left: 'center',
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: [
      {
        type: 'bar',
        name: '项目数量',
        barWidth: '30%',
        data: yData,
        itemStyle: {
          color: getThemeColor('--el-color-primary'),
        },
      },
    ],
  };
  userProjectChartRef.value.commonChartRef.initChart();
};

const userTaskCompleteChartRef = ref();

const userTaskCompleteFormData = ref<any>({
  userGroupId: '',
  userId: '',
  tag1: '',
  discipline: '',
});
const userTaskCompleteProjectChangeFun = async () => {
  await initUserTaskComplete();
};
const getUserGroupTaskCompleteStatistics = async () => {
  const xData: any = [];
  let legendData: any = [];
  let seriesData: any = [];
  const res: any = await getUserGroupTaskCompleteStatisticsApi({
    ...userTaskCompleteFormData.value,
  });
  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 initUserTaskComplete = async () => {
  const { xData, seriesData, legendData } = await getUserGroupTaskCompleteStatistics();
  // 模拟接口延时
  if (!userTaskCompleteChartRef.value || !userTaskCompleteChartRef.value.commonChartRef) return;
  userTaskCompleteChartRef.value.commonChartRef.disposeEchartsByKey('chart-2');
  userTaskCompleteChartRef.value.commonChartRef.option = {
    color: 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,
  };
  userTaskCompleteChartRef.value.commonChartRef.initChart();
};

const userDifficultyCoefficientFormData = reactive<any>({
  userGroupId: '',
  userId: '',
  tag1: '',
  discipline: '',
});
const userDifficultyCoefficientChartRef = ref();
const getDifficultyLevel = (difficulty: number) => {
  const str = DIFFICULTY_COEFFICIENT.value.O[difficulty];
  return str ? str : '难度系数';
};
const initUserDifficultyCoefficientStatistics = async () => {
  let xData: any = [];
  // const yData:any = [1, 2, 3, 4];
  let titles: any = [];
  const seriesData: any = [];

  const res: any = await getUserGroupDifficultyStatisticsApi({
    ...userDifficultyCoefficientFormData,
  });

  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] || 0);
      }

      seriesData.push(obj);
    }
  }

  // 模拟接口延时
  if (
    !userDifficultyCoefficientChartRef.value ||
    !userDifficultyCoefficientChartRef.value.commonChartRef
  )
    return;
  userDifficultyCoefficientChartRef.value.commonChartRef.disposeEchartsByKey('chart-3');
  userDifficultyCoefficientChartRef.value.commonChartRef.option = {
    color: difficultyCountColorList,
    title: {
      textStyle: {
        fontSize: 20,
      },
      subtextStyle: {
        color: '#175ce5',
        fontSize: 15,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      top: '0%',
      left: 'center',
      data: titles,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: sortObjectArray(seriesData, 'coefficient'),
  };
  userDifficultyCoefficientChartRef.value.commonChartRef.initChart();
};

const taskCompletionAtWorkstationsChartRef = ref();

const taskCompletionAtWorkstationsFormData = reactive<any>({
  tag1: '',
});

const initTaskCompletionAtWorkstations = async () => {
  let xData: any = ['工位1', '工位2', '工位3', '工位4'];
  // const yData:any = [20, 30, 40, 50, 60, 70, 80, 90];
  // 模拟接口延时
  // const yData:any = [1, 2, 3, 4];
  let titles: any = [];
  const seriesData: any = [];

  const res: any = await getCommonCompleteStatisticsApi({
    queryType: 'task',
    // x轴为工位，工位应该是tag5
    resultTagType: 'tag4',
    tag1: taskCompletionAtWorkstationsFormData.tag1,
    tag2: '',
    tag3: '',
    tag4: '',
    tag5: '',
    tag6: '',
    tag7: '',
    tag8: '',
    tag9: '',
    tag10: '',
  });

  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_PROCESS_STATUS_OBJ[item];
      }) || [];

    const names = res.data?.allExeStatus || [];

    for (let i = 0; i < names.length; i++) {
      const str = names[i];
      const obj: any = {
        name: TASK_PROCESS_STATUS_OBJ[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);
    }
  }
  if (
    !taskCompletionAtWorkstationsChartRef.value ||
    !taskCompletionAtWorkstationsChartRef.value.commonChartRef
  )
    return;
  taskCompletionAtWorkstationsChartRef.value.commonChartRef.disposeEchartsByKey('chart-4');
  taskCompletionAtWorkstationsChartRef.value.commonChartRef.option = {
    color: statusColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      top: '0%',
      left: 'center',
      data: titles,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
  taskCompletionAtWorkstationsChartRef.value.commonChartRef.initChart();
};

const initTaskCompletionAtDisciplineFormData = reactive<any>({
  tag1: '',
});

const taskCompletionAtDisciplineChartRef = ref();
const initTaskCompletionAtDiscipline = async () => {
  let xData: any = [];
  // const yData:any = [20, 30, 40, 50, 60, 70, 80, 90];
  // 模拟接口延时

  // const yData:any = [1, 2, 3, 4];
  let titles: any = [];
  const seriesData: any = [];

  const res: any = await getTaskCompleteStatisticsByDisciplineApi({
    tag1: initTaskCompletionAtDisciplineFormData.tag1,
  });

  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_PROCESS_STATUS_OBJ[item];
      }) || [];

    const names = res.data?.allExeStatus || [];

    for (let i = 0; i < names.length; i++) {
      const str = names[i];
      const obj: any = {
        name: TASK_PROCESS_STATUS_OBJ[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);
    }
  }
  if (
    !taskCompletionAtDisciplineChartRef.value ||
    !taskCompletionAtDisciplineChartRef.value.commonChartRef
  )
    return;
  taskCompletionAtDisciplineChartRef.value.commonChartRef.disposeEchartsByKey('chart-5');
  taskCompletionAtDisciplineChartRef.value.commonChartRef.option = {
    color: statusColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      top: '0%',
      left: 'center',
      data: titles,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
  taskCompletionAtDisciplineChartRef.value.commonChartRef.initChart();
};

const performanceCompletionAtWorkstationsChartRef = ref();

const initPerformanceCompletionAtWorkstationsFormData = reactive<any>({
  tag1: '',
});

const initPerformanceCompletionAtWorkstations = async () => {
  let xData: any = ['工位1', '工位2', '工位3', '工位4'];
  // const yData:any = [20, 30, 40, 50, 60, 70, 80, 90];
  // 模拟接口延时
  let titles: any = [];
  const seriesData: any = [];

  const res: any = await getCommonCompleteStatisticsApi({
    queryType: 'performance',
    // x轴为工位，工位应该是tag5
    resultTagType: 'tag4',
    tag1: initPerformanceCompletionAtWorkstationsFormData.tag1,
    tag2: '',
    tag3: '',
    tag4: '',
    tag5: '',
    tag6: '',
    tag7: '',
    tag8: '',
    tag9: '',
    tag10: '',
  });

  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_CALCULATE_STATUS_OBJ[item] || item;
      }) || [];
    const names = res.data?.allExeStatus || [];

    for (let i = 0; i < names.length; i++) {
      const str = names[i];
      const obj: any = {
        name: TASK_CALCULATE_STATUS_OBJ[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);
    }
  }
  if (
    !performanceCompletionAtWorkstationsChartRef.value ||
    !performanceCompletionAtWorkstationsChartRef.value.commonChartRef
  )
    return;
  performanceCompletionAtWorkstationsChartRef.value.commonChartRef.disposeEchartsByKey('chart-6');
  performanceCompletionAtWorkstationsChartRef.value.commonChartRef.option = {
    // color: ['#37a93d', '#de4231', '#808080'],
    color: performanceColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      show: true,
      top: '0%',
      left: 'center',
      data: titles,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
  performanceCompletionAtWorkstationsChartRef.value.commonChartRef.initChart();
};

const performanceCompletionAtDisciplineChartRef = ref();
const initPerformanceCompletionAtDisciplineFormData = reactive<any>({
  tag1: '',
});

const initPerformanceCompletionAtDiscipline = async () => {
  // const xData:any = ['学科1', '学科2', '学科3', '学科4'];
  // const yData:any = [20, 30, 40, 50, 60, 70, 80, 90];
  // 模拟接口延时

  let xData: any = [];
  // const yData:any = [20, 30, 40, 50, 60, 70, 80, 90];
  // 模拟接口延时
  let titles: any = [];
  const seriesData: any = [];

  const res: any = await getPerformanceCompleteStatisticsByDisciplineApi({
    tag1: initPerformanceCompletionAtDisciplineFormData.tag1,
  });

  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles =
      res.data?.allExeStatus?.map((item: any) => {
        return TASK_CALCULATE_STATUS_OBJ[item] || item;
      }) || [];
    const names = res.data?.allExeStatus || [];

    for (let i = 0; i < names.length; i++) {
      const str = names[i];
      const obj: any = {
        name: TASK_CALCULATE_STATUS_OBJ[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);
    }
  }
  if (
    !performanceCompletionAtDisciplineChartRef.value ||
    !performanceCompletionAtDisciplineChartRef.value.commonChartRef
  )
    return;
  performanceCompletionAtDisciplineChartRef.value.commonChartRef.disposeEchartsByKey('chart-7');
  performanceCompletionAtDisciplineChartRef.value.commonChartRef.option = {
    // color: ['#37a93d', '#de4231', '#808080'],
    color: performanceColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      show: true,
      top: '0%',
      left: 'center',
      data: titles,
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    dataZoom: xData.length > 4 ? [] : null,
    series: seriesData,
  };
  performanceCompletionAtDisciplineChartRef.value.commonChartRef.initChart();
};

const reviewPassedChartRef = ref();

const reviewPassedChartFormData = reactive<any>({
  tag1: '',
  discipline: '',
});

const reviewPassedChangeFun = () => {
  initReviewPassed();
};
// 评审中、已通过，已拒绝 对应 1、2、3
const initReviewPassed = async () => {
  let xData: any = [];
  let titles: any = [];
  const seriesData: any = [];
  const res: any = await getWorkstationReviewStatisticsApi({
    resultTagType: 'tag5',
    ...reviewPassedChartFormData,
  });
  if (res && res.code === 200) {
    xData =
      res.data?.result?.map((item: any) => {
        return item.name;
      }) || [];

    titles = res.data.allApprovalStatus;
    const statusMap: any = {
      0: '未评审',
      1: '评审中',
      2: '已通过',
      3: '已拒绝',
    };

    for (let i = 0; i < titles.length; i++) {
      const obj: any = {
        // name: titles[i],
        name: statusMap[titles[i]],
        nameValue: titles[i],
        type: 'bar',

        emphasis: {
          focus: 'series',
        },
        data: [],
      };

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

      seriesData.push(obj);
    }
  }
  if (!reviewPassedChartRef.value || !reviewPassedChartRef.value.commonChartRef) return;
  reviewPassedChartRef.value.commonChartRef.disposeEchartsByKey('chart-8');
  reviewPassedChartRef.value.commonChartRef.option = {
    // color: ['#808080', '#b6d634', '#37a93d', '#de4231'],
    color: processNodeColorList,
    title: {
      textStyle: {
        fontSize: 20,
      },
      subtextStyle: {
        color: '#175ce5',
        fontSize: 15,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      // trigger: 'item',
      // formatter: function (params:any) {
      //   return `${params.name} : ${params.value} 个 `;
      // },
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      show: true,
      top: '0%',
      left: 'center',
      data: ['未评审', '评审中', '已通过', '已拒绝'],
    },
    grid: {
      top: '10%',
      bottom: '50',
      left: '5%',
      right: '5%',
    },
    xAxis: [
      {
        type: 'category',
        data: xData,
        // axisLabel: {
        //   interval: 'auto',
        // },
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    dataZoom: xData.length > 4 ? [] : null,
    series: sortObjectArray(seriesData, 'nameValue'),
  };
  reviewPassedChartRef.value.commonChartRef.initChart();
};

const userProjectFromData = ref<any>({
  userGroupId: '',
  userId: '',
});
const getGroupList = async () => {
  const res: any = await userQueryGroupApi({
    current: 1,
    size: 1000,
  });
  if (res && res.code === 200) {
    userGroupOptions.value = [];
    res.data.data.forEach((item: any) => {
      userGroupOptions.value.push({
        label: item.groupName,
        value: item.id,
      });
    });
    if (userGroupOptions.value?.length) {
      userProjectFromData.value.userGroupId = userGroupOptions.value[0].value;
      userTaskCompleteFormData.value.userGroupId = userGroupOptions.value[0].value;
      userDifficultyCoefficientFormData.userGroupId = userGroupOptions.value[0].value;
    }
  }
};

const getDisciplineOptionsFun = async () => {
  queryNodeListApi({ current: 1, size: 999, nodeType: 'discipline', pid: null }).then(
    (res: any) => {
      if (res.code === 200) {
        disciplineOptions.value =
          res.data?.data?.map((item: any) => {
            return {
              label: item.nodeName,
              value: item.id,
            };
          }) || [];
      }
    }
  );
};

// ------------------项目任务完成情况统计------------------
const projectTaskCompleteChartRef = ref();
const projectTaskCompleteFormData = ref<any>({
  tag1List: '',
});
const projectTaskCompleteProjectChangeFun = () => {
  initProjectTaskComplete();
};
const getProjectGroupTaskCompleteStatistics = async () => {
  const xData: any = [];
  let legendData: any = [];
  let seriesData: any = [];
  const res: any = await getAllUserTaskCompleteStatisticsApi({
    tag1List: projectTaskCompleteFormData.value.tag1List
      ? projectTaskCompleteFormData.value.tag1List.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 initProjectTaskComplete = async () => {
  // 项目uuids
  // const params = {};
  const { xData, seriesData, legendData } = await getProjectGroupTaskCompleteStatistics();
  if (!projectTaskCompleteChartRef.value || !projectTaskCompleteChartRef.value.commonChartRef)
    return;
  projectTaskCompleteChartRef.value.commonChartRef.disposeEchartsByKey('chart-9');
  const option = {
    color: 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,
  };
  projectTaskCompleteChartRef.value.commonChartRef.option = option;
  projectTaskCompleteChartRef.value.commonChartRef.initChart();
};

onMounted(async () => {
  await getGroupList();
  await getDisciplineOptionsFun();
  await initUserProjectStatistics();
  await initUserTaskComplete();
  await initUserDifficultyCoefficientStatistics();
  await initTaskCompletionAtWorkstations();
  await initTaskCompletionAtDiscipline();
  await initPerformanceCompletionAtWorkstations();
  await initPerformanceCompletionAtDiscipline();
  await initReviewPassed();
  await initProjectTaskComplete();
});
</script>
<style lang="scss" scoped>
.gl-page-content-grey {
  .content {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .chart-box {
      width: calc(50% - 8px);
      height: 400px;
      position: relative;
      margin-bottom: 16px;
      .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>
