<template>
  <div class="gl-page-content-grey data-statistics" v-loading="loading">
    <!-- 配置按钮 -->
    <div class="icon-btn">
      <el-tooltip :content="$t('个性化配置')" placement="top">
        <div class="setting-btn" @click="settingDiaVisible = true">
          <el-icon :size="18">
            <Setting />
          </el-icon>
        </div>
      </el-tooltip>
    </div>
    <settingDia
      v-model="settingDiaVisible"
      :configJson="configJson"
      @updateConfig="updateConfigFun"
    />
    <!-- echart 图表 -->
    <div class="content">
      <div v-for="config in currentList" :key="config.id" class="chart-box">
        <component :is="config.component" v-bind="config.props" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getThemeColor } from '@/utils/theme';
// 引入子组件
import userGroupProjectChart from './dataStatistics/userGroupProjectChart.vue';
import userTaskCompleteChart from './dataStatistics/userTaskCompleteChart.vue';
import userDifficultyCoefficientChart from './dataStatistics/userDifficultyCoefficientChart.vue';
import taskCompletion from './dataStatistics/taskCompletion.vue';
import performanceCompletion from './dataStatistics/performanceCompletion.vue';
import projectTaskComplete from './dataStatistics/projectTaskComplete.vue';
import reviewPassed from './dataStatistics/reviewPassed.vue';
import settingDia from './dataStatistics/settingDia.vue';
import { getUserId, getUserTenantId } from '@/utils/user';
import { ElMessage } from 'element-plus';
import {
  addFormConfigureApi,
  getFormConfigureApi,
  updateFormConfigureApi,
} from '@/api/system/systemData';

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 settingDiaVisible = ref(false);
// 组件基础配置数组
const baseList = ref([
  {
    id: 'userGroupProject',
    component: userGroupProjectChart, // 用户组项目统计
    props: {},
  },
  {
    id: 'userDifficultyCoefficient',
    component: userDifficultyCoefficientChart, // 用户组难度系数统计
    props: {
      difficultyCountColorList,
    },
  },
  {
    id: 'userTaskComplete',
    component: userTaskCompleteChart, // 用户组任务完成情况统计
    props: {
      statusColorList,
    },
  },
  {
    id: 'projectTaskComplete',
    component: projectTaskComplete, // 项目任务完成情况统计
    props: {
      statusColorList,
    },
  },
  {
    id: 'taskCompletionMechine',
    component: taskCompletion, // 任务完成统计（机台）
    props: {
      statusColorList,
      resultTagType: 'mechine',
    },
  },
  {
    id: 'taskCompletionDiscipline',
    component: taskCompletion, // 任务完成统计（学科）
    props: {
      statusColorList,
      resultTagType: 'discipline',
    },
  },
  {
    id: 'performanceCompletionMechine',
    component: performanceCompletion, // 指标完成统计（机台）
    props: {
      performanceColorList,
      resultTagType: 'mechine',
    },
  },
  {
    id: 'performanceCompletionDiscipline',
    component: performanceCompletion, // 指标完成统计（学科）
    props: {
      performanceColorList,
      resultTagType: 'discipline',
    },
  },
  {
    id: 'reviewPassed',
    component: reviewPassed, // 工位评审通过统计
    props: {
      processNodeColorList,
    },
  },
]);
// 当前展示的图表
const currentList = ref();
const loading = ref(false);
// 配置弹窗点击确定
const updateConfigFun = async (info: any) => {
  try {
    let res: any;
    // 新增 or 修改
    if (hasConfig.value) {
      res = await updateFormConfigureApi({
        formName: 'data_Statistics_Setting' + '_' + getUserId() + '_' + getUserTenantId(),
        formConfig: info,
      });
    } else {
      res = await addFormConfigureApi({
        formName: 'data_Statistics_Setting' + '_' + getUserId() + '_' + getUserTenantId(),
        formConfig: info,
      });
    }
    // 接口成功后才更新 configJson
    if (res.code === 200) {
      ElMessage.success('配置成功');
      configJson.value = info;
      hasConfig.value = true;
      // 根据配置的结果对展示的图表进行排序
      setConfig(info);
    }
  } catch (error) {
    console.error('更新配置失败:', error);
  }
};

// 设置 参数json
const setConfig = (dataStatisticsSetting: any) => {
  if (dataStatisticsSetting) {
    const configInfo = JSON.parse(dataStatisticsSetting);
    // 根据配置的结果对展示的图表进行排序
    const list = configInfo
      .filter((config: any) => config.inBoard)
      .map((config: any) => baseList.value.find((item) => item.id === config.key))
      .filter(Boolean);
    currentList.value = list;
  } else {
    currentList.value = baseList.value;
  }
};
// 是否配置过
const hasConfig = ref(false);
// 配置规则
const configJson = ref('');
// 获取该用户的配置
const getFormConfigure = async () => {
  loading.value = true;
  const params = {
    formName: 'data_Statistics_Setting' + '_' + getUserId() + '_' + getUserTenantId(),
  };
  try {
    // 临时保存原始的 ElMessage.warning
    const originalWarning = ElMessage.warning;
    // 临时禁用警告消息
    ElMessage.warning = () => ({ close: () => {} }) as any;
    const res = await getFormConfigureApi(params);
    if (res.code === 200) {
      // 如果存在配置，则使用配置
      hasConfig.value = true;
      configJson.value = res.data.formConfig;
      setConfig(res.data.formConfig);
    } else {
      // 如果不存在配置，则使用默认配置
      hasConfig.value = false;
      setConfig('');
    }
    // 恢复原始的 ElMessage.warning
    ElMessage.warning = originalWarning;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getFormConfigure();
});
</script>

<style lang="scss" scoped>
.gl-page-content-grey {
  .icon-btn {
    height: 20px;
    background: var(--el-bg-color);
    display: flex;
    justify-content: flex-end;
    padding-right: 8px;
    .setting-btn {
      cursor: pointer;
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 20px);
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .chart-box {
      width: calc(50% - 8px);
      height: 400px;
      position: relative;
      margin-bottom: 16px;
      &:nth-last-child(-n + 2) {
        margin-bottom: 0;
      }
    }
  }
}
</style>
