<template>
  <div class="comp-summary-charts charts">
    <div class="chart-box">
      <EchartCard
        v-if="currentProjectId"
        :title="$t('工况库.项目任务进度统计')"
        ref="ProjectTaskProgressChartRef"
        :charts-id="'chart-progress'"
        :bar-type="'barChart'"
        :nodata="barChartNodata"
        @refresh="queryProjectTaskProgress"
      >
        <template #formSlot>
          <el-form :model="projectTaskFormData" label-width="auto">
            <el-form-item label="工位：">
              <el-select
                v-model="projectTaskFormData.workspace"
                placeholder="请选择工位"
                clearable
                @change="workspaceChangeFun"
                @clear="workspaceClearFun"
              >
                <el-option
                  v-for="item in workspaceOptions"
                  :key="item.uuid"
                  :label="item.nodeName"
                  :value="item.uuid"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学科：">
              <el-select
                v-model="projectTaskFormData.discipline"
                placeholder="请选择学科"
                clearable
                @change="disciplineChangeFun"
                @clear="disciplineClearFun"
              >
                <el-option
                  v-for="item in disciplineOptions"
                  :key="item.uuid"
                  :label="item.nodeName"
                  :value="item.uuid"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </template>
      </EchartCard>
      <el-empty class="chart-empty" description="选择单个项目后展示任务进度统计数据" />
    </div>
    <div class="chart-box">
      <EchartCard
        v-if="currentProjectId"
        :title="$t('工况库.项目任务达成统计')"
        ref="ProjectTaskAchievementChartRef"
        :charts-id="'chart-achievement'"
        :bar-type="'pieChart'"
        :nodata="pieChartNodata"
        @refresh="queryProjectTaskAchievement"
      >
      </EchartCard>
      <el-empty v-else class="chart-empty" description="选择单个项目后展示任务达成统计数据" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import EchartCard from '@/components/common/echartCard/index.vue';
import {
  getTaskCompleteStatisticsByDisciplineApi,
  getChildrenNodeListApi,
} from '@/api/project/node';
import { getTaskAchieveStatisticsApi } from '@/api/project/task';
import { getThemeColor } from '@/utils/theme';
import {
  TASK_PROCESS_STATUS_OBJ,
  TASK_PROCESS_STATUS,
  TASK_CALCULATE_STATUS_OBJ,
} from '@/utils/enum/task';
import emitter from '@/utils/eventBus';

// 进度状态颜色列表
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 achievementColorList = [
  getThemeColor('--el-color-info'), // 未分析
  getThemeColor('--el-color-success'), // 合格
  getThemeColor('--el-color-danger'), // 不合格
];

const currentProjectId = ref<string>('');

// ***************** 工位学科筛选 *****************
// 工位、学科筛选
const projectTaskFormData = ref<any>({
  workspace: '',
  discipline: '',
});
// 下拉框选项
const workspaceOptions = ref<any>([]);
const disciplineOptions = ref<any>([]);
// 获取当前项目下的工位
const queryWorkspaceList = async () => {
  const params = {
    nodeId: currentProjectId.value,
    nodeType: 'workspace',
  };
  getChildrenNodeListApi(params).then((res) => {
    workspaceOptions.value = res.data;
  });
};
// 获取当前项目下的学科
const queryDisciplineList = async () => {
  const params = {
    nodeId: projectTaskFormData.value.workspace || currentProjectId.value,
    nodeType: 'discipline',
  };
  getChildrenNodeListApi(params).then((res) => {
    disciplineOptions.value = res.data;
  });
};

// 下拉选项变化
const workspaceChangeFun = (val: string) => {
  if (!val) return;
  // 学科列表变化，值清空
  queryDisciplineList();
  projectTaskFormData.value.discipline = '';
  // 图表变化
  queryProjectTaskProgress();
};
const disciplineChangeFun = (val: string) => {
  if (!val) return;
  // 图表变化
  queryProjectTaskProgress();
};

// 下拉清除
const workspaceClearFun = () => {
  // 学科列表清空，值清空
  disciplineOptions.value = [];
  projectTaskFormData.value.discipline = '';
  // 图表变化
  queryProjectTaskProgress();
};
const disciplineClearFun = () => {
  // 图表变化
  queryProjectTaskProgress();
};

// ***************** 进度统计 *****************
const ProjectTaskProgressChartRef = ref();
const barChartNodata = ref(false);
const getCommonOptionFun = async () => {
  let xData: any = [];
  const seriesData: any = [];
  let legendData: any = [];
  if (currentProjectId.value === '') {
    return {
      xData,
      seriesData,
      legendData,
    };
  } else {
    const res: any = await getTaskCompleteStatisticsByDisciplineApi({
      tag1: currentProjectId.value,
      tag5: projectTaskFormData.value.workspace,
      tag6: projectTaskFormData.value.discipline,
    });

    if (res && res.code === 200) {
      barChartNodata.value = res.data.allExeStatus.length === 0;
      xData = res.data.result.map((item: any) => {
        return item.name;
      });

      legendData = 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',
          stack: 'total', // 堆叠效果
          emphasis: {
            focus: 'series',
          },
          label: {
            show: false, // 暂不展示，效果很一般
            position:
              TASK_PROCESS_STATUS_OBJ[str] ===
              TASK_PROCESS_STATUS_OBJ[TASK_PROCESS_STATUS.COMPLETED]
                ? 'right'
                : '',
            formatter: (params: any) => {
              return params.value
                ? TASK_PROCESS_STATUS_OBJ[str] ===
                  TASK_PROCESS_STATUS_OBJ[TASK_PROCESS_STATUS.COMPLETED]
                  ? `———${params.value}`
                  : params.value
                : '';
            },
          },
          data: [],
        };

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

        seriesData.push(obj);
      }
    }
    return {
      xData,
      seriesData,
      legendData,
    };
  }
};
const queryProjectTaskProgress = async () => {
  const { xData, seriesData, legendData } = await getCommonOptionFun();
  if (!ProjectTaskProgressChartRef.value || !ProjectTaskProgressChartRef.value.commonChartRef)
    return;
  ProjectTaskProgressChartRef.value.commonChartRef.disposeEchartsByKey('chart-progress');
  ProjectTaskProgressChartRef.value.commonChartRef.option = {
    color: statusColorList,
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      top: '0%',
      left: 'center',
      data: legendData,
      // itemWidth: 12,
      // itemHeight: 12,
    },
    grid: {
      top: '15%',
      bottom: '20%',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData || [],
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
    },
    dataZoom:
      xData.length > 4
        ? [
            {
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              start: 0,
              end: 100,
              textStyle: {
                color: 'transparent',
              },
              maxValueSpan: 4,
              minValueSpan: 4,
              moveHandleSize: 10,
              height: 10,
              filterMode: 'empty',
              bottom: 0,
            },
          ]
        : null,
    series: seriesData || [],
  };
  ProjectTaskProgressChartRef.value.commonChartRef.initChart();
};

// ***************** 达成统计 *****************
const ProjectTaskAchievementChartRef = ref();
const pieChartNodata = ref(false);
const queryProjectTaskAchievement = async () => {
  const seriesData: { name: any; value: any }[] = [];
  // 如果没有选择项目，则不请求接口
  if (currentProjectId.value) {
    const res: any = await getTaskAchieveStatisticsApi({
      resultTagType: 'tag1',
      tag1: currentProjectId.value,
    });
    pieChartNodata.value = res.data.allAchieveStatus.length === 0;
    // 把res.data.allAchieveStatus数组转换为对象的key，value默认是0
    const achieveStatusObj: any = {};
    res.data.allAchieveStatus.forEach((item: any) => {
      achieveStatusObj[item] = 0;
    });
    // 遍历res.data.result数组，把每个对象的statusCount属性合并到achieveStatusObj中
    res.data.result?.forEach((item: any) => {
      for (const key in item.statusCount) {
        achieveStatusObj[key] += item.statusCount[key];
      }
    });
    // 遍历achieveStatusObj，把每个对象的key转换为中文
    for (const key in achieveStatusObj) {
      seriesData.push({
        name: TASK_CALCULATE_STATUS_OBJ[key],
        value: achieveStatusObj[key],
      });
    }
  }
  const option = {
    color: achievementColorList,
    legend: {
      show: true,
      left: '10%',
      top: '10%',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      borderWidth: 0,
      formatter: (name: any) => {
        const str = seriesData.filter((item) => item.name === name)[0];
        return `{name|${name}} {value|${str.value}}`;
        // const total = seriesData.reduce((sum, item) => sum + item.value, 0);
        // const percent = ((str.value / total) * 100).toFixed(2);
        // return `{name|${name}} {value|${str.value}  ${percent}%}`;
      },
      textStyle: {
        color: 'inherit',
        rich: {
          name: {
            fontSize: 14,
            align: 'left',
          },
          value: {
            fontSize: 14,
            fontWeight: '700',
            align: 'right',
          },
        },
      },
      orient: 'vertical',
      itemGap: 20,
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['30%', '55%'],
        center: ['60%', '45%'],
        emphasis: {
          disabled: true, // 禁用emphasis效果
        },
        itemStyle: {
          borderRadius: 0,
          borderWidth: 0,
          // borderColor: getThemeColor('--el-bg-color'),
        },
        label: {
          formatter: (params: { name: any; percent: any }) => {
            return '{icon|●}{name|' + params.name + '} {value|' + params.percent + '%' + '}';
          },
          alignTo: 'labelLine',
          rich: {
            icon: {
              fontSize: 20,
              color: 'inherit',
            },
            name: {
              fontSize: 14,
              padding: [0, 6, 0, 4],
              color: 'inherit',
            },
            value: {
              fontSize: 12,
              fontWeight: 'bolder',
              color: 'inherit',
            },
          },
        },
        labelLine: {
          lineStyle: {
            cap: 'round',
          },
        },
        data: seriesData,
      },
    ],
  };
  nextTick(() => {
    if (
      !ProjectTaskAchievementChartRef.value ||
      !ProjectTaskAchievementChartRef.value.commonChartRef
    )
      return;
    ProjectTaskAchievementChartRef.value.commonChartRef.disposeEchartsByKey('chart-achievement');
    ProjectTaskAchievementChartRef.value.commonChartRef.option = { ...option };
    ProjectTaskAchievementChartRef.value.commonChartRef.initChart();
  });
};

onMounted(async () => {
  emitter.on('TASK_SEARCH', async (projectUuid: any) => {
    currentProjectId.value = projectUuid;
    if (projectUuid) {
      // 获取工位列表
      queryWorkspaceList();
      // 获取学科列表
      queryDisciplineList();
      // 更新图表
      queryProjectTaskProgress();
      queryProjectTaskAchievement();
    } else {
      // 清空下拉框
      workspaceOptions.value = [];
      disciplineOptions.value = [];
      projectTaskFormData.value = {
        workspace: '',
        discipline: '',
      };
    }
  });
});
onBeforeUnmount(() => {
  emitter.off('TASK_SEARCH');
});
</script>

<style lang="scss">
.comp-summary-charts {
  .el-empty__image {
    width: 20%;
    height: 100%;
  }
  .el-empty__description p {
    font-size: 12px;
  }
}
</style>

<style lang="scss" scoped>
.charts {
  display: flex;
  justify-content: space-between;
  height: 100%;
  .chart-box {
    width: calc(50% - 6px);
    height: 100%;
  }
  .chart-empty {
    width: 100%;
    height: 100%;
    background-color: var(--el-bg-color);
  }
}
</style>
