<!-- <template>
  <vxe-table v-if="$route.name != 'workerDrak'" border style="width: 100%" height="400" show-overflow
    show-header-overflow show-footer-overflow :data="tableData" :column-config="{ resizable: true }"
    :scroll-x="{ enabled: true, gt: 0 }" :merge-cells="mergeCells">
    <vxe-column field="index" title="排名" width="80" fixed="left">
      <template #default="scope">
        <div v-if="scope._rowIndex == 0" class="text-center text-sm font-extrabold text-[#000000] pt-4">
          平均得分
        </div>
        <div v-if="scope._rowIndex > imgIndex" class="diamond">
          {{ scope.row.ranking }}
        </div>
        <div v-else class="text-center">
          <img :src="RANK_IMG[scope.row.ranking - 1]" alt="" />
        </div>
      </template>
    </vxe-column>
    <vxe-column v-if="$route.name == 'workerDrak' || $route.name == 'workerRank'" field="deptName" :title="deptName"
      fixed="left" width="150" />
    <vxe-column v-else field="assessmentObjectName" :title="deptName" fixed="left" width="150" />
    <vxe-column v-if="$route.name == 'workerDrak' || $route.name == 'workerRank'" field="assessmentObjectName"
      fixed="left" title="姓名" width="100" />
    <template v-for="(ita, itk) in tableData" :key="itk">
      <template v-for="item in ita.dimensionList" :key="item.dimId">
        <vxe-colgroup :title="`${item.dimName}(${soreRate(item.soreRate)}%)`" width="150">
          <template v-for="it in item.quotaList" :key="it.quotaId">
            <vxe-column :field="it.quotaScore" :title="`${it.quotaName}(${soreRate(it.quotaWeight)}%)`" width="150" />
          </template>
        </vxe-colgroup>
        <vxe-column field="totalSore" title="总分" width="150" />
      </template>
    </template>
    <vxe-column field="allScore" title="总得分" fixed="right" width="150" />
  </vxe-table>
  <vxe-table v-else border show-overflow style="width: 100%" height="400" :data="tableData">
    <vxe-column field="index" title="排名" width="80" fixed="left">
      <template #default="scope">
        <div v-if="scope._rowIndex > 2" class="diamond">
          {{ scope.row.ranking }}
        </div>
        <div v-else class="text-center">
          <img :src="RANK_IMG[scope.row.ranking - 1]" alt="" />
        </div>
      </template>
    </vxe-column>
    <vxe-column v-if="$route.name == 'workerDrak' || $route.name == 'workerRank'" field="deptName" :title="deptName"
      fixed="left" width="150" />
    <vxe-column v-else field="assessmentObjectName" :title="deptName" fixed="left" width="150" />
    <vxe-column v-if="$route.name == 'workerDrak' || $route.name == 'workerRank'" field="assessmentObjectName"
      fixed="left" title="姓名" width="100" />
    <template v-for="(ita, itk) in tableData" :key="itk">
      <template v-for="item in ita.dimensionList" :key="item.dimId">
        <vxe-colgroup :title="`${item.dimName}(${soreRate(item.soreRate)}%)`" width="150">
          <template v-for="it in item.quotaList" :key="it.quotaId">
            <vxe-column v-if="!isDuplicate(item)" :field="it.quotaScore"
              :title="`${it.quotaName}(${soreRate(it.quotaWeight)}%)`" width="150" />
          </template>
        </vxe-colgroup>
        <vxe-column field="totalSore" title="总分" width="150" />
      </template>
    </template>
    <vxe-column field="allScore" title="总得分" fixed="right" width="150" />
  </vxe-table>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, onMounted } from "vue";
import rank1 from "@/assets/rank/rank1.png";
import rank2 from "@/assets/rank/rank2.png";
import rank3 from "@/assets/rank/rank3.png";
import { useRoute } from "vue-router";
const $route = useRoute();
const RANK_IMG = [rank1, rank2, rank3];
const tableData = ref([]);
const deptName = ref("");
const name = ref("");
const mergeCells = ref([
  // 合并第一行前两列
  { row: 0, col: 0, rowspan: 1, colspan: 2 },
  { row: 2, col: 1, rowspan: 0, colspan: 0 }
]);
const averageData = averageSore => {
  if (tableData.value.length > 0) {
    tableData.value.unshift({
      dimensionList: [],
      allScore: averageSore
    });
  }
};
const imgIndex = ref();
onMounted(() => {
  if ($route.name != "workerDrak" || $route.name != "workerRank") {
    imgIndex.value = 3;
  } else {
    imgIndex.value = 2;
  }
});
function isDuplicate(item) {
  // 根据您的标准添加逻辑以检查重复项
  return tableData.value.some(td => td.dimId === item.dimId);
}
const init = (item, deptNames, names) => {
  tableData.value = item;
  item.map((it, id) => { });
  deptName.value = deptNames;
  name.value = names;
  if ($route.name != "workerDrak") {
    averageData(item.averageSore);
  }
  console.log("item111", item);
  console.log("tableData", tableData.value);
};
const soreRate = row => {
  if (row) {
    return row;
  } else {
    return 0;
  }
};
defineExpose({
  init
});
</script> -->
<template>
  <div class="w-full aa">
    <vxe-button class="float-right -top-0 mr-20 mb-4" @click="exportEvent"
      ><el-icon> <Download /> </el-icon>&nbsp;&nbsp;导出</vxe-button
    >
    <vxe-grid
      v-if="$route.name != 'workerDrak'"
      v-bind="gridOptions"
      ref="gridRef"
      :merge-cells="mergeCells"
      class="mt-10"
    >
      <template #imgUrl_default="{ row }">
        <div>
          <div
            v-if="!row.ranking"
            class="text-center text-sm font-extrabold text-[#000000]"
          >
            平均得分
          </div>
          <div v-if="row.ranking <= 3" class="text-center">
            <img class="mt-auto" :src="RANK_IMG[Number(row.ranking) - 1]" />
          </div>
          <div v-else-if="row.ranking" class="diamond">{{ row.ranking }}</div>
        </div>
      </template>
      <template #dim-allScore="{ row }">
        {{ row.allScore }}
      </template>
    </vxe-grid>
    <vxe-grid v-else v-bind="gridOptions" ref="gridRef1" class="mt-10">
      <template #imgUrl_default="{ row }">
        <div v-if="row.ranking <= 3" class="text-center">
          <img class="mt-auto" :src="RANK_IMG[Number(row.ranking) - 1]" />
        </div>
        <div v-else-if="row.ranking" class="diamond">{{ row.ranking }}</div>
      </template>
      <template #dim-allScore="{ row }">
        {{ row.allScore }}
      </template>
    </vxe-grid>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import rank1 from "@/assets/rank/rank1.png";
import rank2 from "@/assets/rank/rank2.png";
import rank3 from "@/assets/rank/rank3.png";
import dayjs from "dayjs";
import { useRoute } from "vue-router";
import { useUserStoreHook } from "@/store/modules//user";
const $prop = defineProps({
  rankTableRefList: Object
});
const gridRef = ref(null);
const gridRef1 = ref(null);
onMounted(() => {
  // 员工排行榜无法获取组件渲染问题
  if ($prop.rankTableRefList) {
    init(
      $prop.rankTableRefList.data,
      $prop.rankTableRefList.dept,
      $prop.rankTableRefList.name
    );
  }
});
const $route = useRoute();
const fileData = ref();
const RANK_IMG = [rank1, rank2, rank3];
const deptName = ref("");
const name = ref("");
const mergeCells = ref([
  // 合并第一行前两列
  { row: 0, col: 0, rowspan: 1, colspan: 2 },
  { row: 2, col: 1, rowspan: 0, colspan: 0 }
]);
const averageData = averageSore => {
  // console.log("平均数", rawData.value);
  if (rawData.value.length > 0) {
    let num = 0;
    // rawData.value.map(it => {
    //   num = num + it.allScore;
    // });
    // num = (num / rawData.value.length).toFixed(2);
    rawData.value.unshift({
      dimensionList: [],
      allScore: rawData.value[0].averageSore,
      isAverageRow: true // 标记为平均分行
    });
  }
};
const selectYear = ref("2024-01-01");
const gridOptions = reactive({
  border: true,
  loading: false,
  height: 500,
  columns: [],
  data: [],
  sortConfig: {
    multiple: false,
    chronological: true
  },
  showOverflow: true,
  showHeaderOverflow: true,
  showFooterOverflow: true,
  columnConfig: {
    resizable: true
  },
  scrollX: {
    enabled: true,
    gt: 0
  }
});

// 判断key值是否相同返回具体值
function getValueByKey(obj, key) {
  if (key in obj) {
    return obj[key];
  }
  return null; // 如果 key 不存在则返回 null
}
// 模拟接口数据
const rawData = ref([]);
const init = async (item, deptNames, names) => {
  rawData.value = item;
  console.log("item11", item);
  deptName.value = deptNames;
  name.value = names;
  if ($route.name != "workerDrak") {
    averageData(item.averageSore);
  }
  if ($route.name == "healthDrank" || $route.name == "healthRank") {
    tabTitle.value = "医疗组";
  } else {
    tabTitle.value = "科室";
  }
  // 初始化
  await createColumns();
  await loadData();
};
defineExpose({
  init
});

// 生成动态表头
// 生成动态表头
const tabTitle = ref();
const createColumns = () => {
  let columns = [];
  if ($route.name == "workerDrak" || $route.name == "headDrank") {
    columns = [
      {
        title: "排名",
        field: "ranking",
        width: 70,
        slots: { default: "imgUrl_default" },
        fixed: "left" // 将此列固定在左侧
      },
      {
        title: "姓名",
        field: "assessmentObjectName",
        width: 100,
        fixed: "left" // 将此列固定在左侧
      },
      {
        title: "部门",
        field: "deptName",
        width: 150,
        fixed: "left" // 将此列固定在左侧
      },
      {
        title: "总得分",
        field: "allScore",
        sortable: true,
        width: 150,
        fixed: "right", // 将此列固定在右侧
        slots: { default: "dim-allScore" },
        sortBy({ column, row }) {
          // 如果是平均行（isAverageRow为true），则返回一个很大的值，避免被排序
          if (column.field in row && typeof row[column.field] === "number") {
            if (column.order == "asc") {
              if (row.isAverageRow) {
                return -9999999999;
              }
            } else {
              if (row.isAverageRow) {
                return 99999999999;
              }
            }
          } else {
            return -9999999999;
          }
          return row.allScore; // 返回正常的得分，进行排序
        }
      }
    ];
  } else {
    columns = [
      {
        title: "排名",
        field: "ranking",
        width: 70,
        slots: { default: "imgUrl_default" },
        fixed: "left" // 将此列固定在左侧
      },
      {
        title: tabTitle.value,
        field: "assessmentObjectName",
        width: 100,
        fixed: "left" // 将此列固定在左侧
      },
      {
        title: "总得分",
        field: "allScore",
        width: 150,
        sortable: true,
        fixed: "right", // 将此列固定在右侧
        slots: { default: "dim-allScore" },
        sortBy({ column, row }) {
          // 如果是平均行（isAverageRow为true），则返回一个很大的值，避免被排序

          // console.log(123, column)
          // console.log("1231row", row)
          if (column.field in row && typeof row[column.field] === "number") {
            if (column.order == "asc") {
              if (row.isAverageRow) {
                return -9999999999;
              }
            } else {
              if (row.isAverageRow) {
                return 99999999999;
              }
            }
          } else {
            return -9999999999;
          }
          return getValueByKey(row, column.field); // 返回正常的得分，进行排序
        }
      }
    ];
  }
  const headerMap = new Map();
  // 遍历数据生成表头结构
  rawData.value.forEach(item => {
    item.dimensionList.forEach(dim => {
      if (!headerMap.has(dim.dimName)) {
        // 存储维度相关信息，包括 totalSore 和 dimWeight
        headerMap.set(dim.dimName, {
          dimWeight: dim.dimWeight || "0", // 默认值为 "-"
          totalSore: dim.totalSore || "0", // 默认值为 "-"
          quotas: [] // 用于存储 quota 列表
        });
      }
      dim.quotaList.forEach(quota => {
        const dimData = headerMap.get(dim.dimName);
        if (!dimData.quotas.some(q => q.quotaName === quota.quotaName)) {
          dimData.quotas.push({
            quotaName: quota.quotaName,
            quotaWeight: quota.quotaWeight || "0" // 默认值为 "-"
          });
        }
      });
    });
  });

  // 构建多级表头
  headerMap.forEach((dimData, dimName) => {
    const children = dimData.quotas.map(quota => ({
      title: `${quota.quotaName} ${quota.quotaWeight && quota.quotaWeight != "0" ? `(${quota.quotaWeight}%)` : ""}`, // 在 title 后拼接 quotaWeight
      width: 120,
      sortable: true,
      field: `${dimName}_${quota.quotaName}`, // 确保字段唯一
      sortBy({ column, row }) {
        // 如果是平均行（isAverageRow为true），则返回一个很大的值，避免被排序
        let aa = Number(row[column.field]);
        if (typeof aa === "number" && !isNaN(aa)) {
          if (column.order == "asc") {
            if (row.isAverageRow) {
              return -9999999999;
            }
          } else {
            if (row.isAverageRow) {
              return 99999999999;
            }
          }
        } else {
          // 倒序在最后
          if (column.order == "asc") {
            if (!row.isAverageRow) {
              return 9999999999999;
            } else {
              return -999999999999;
            }
          } else {
            if (!row.isAverageRow) {
              return -999999999999;
            } else {
              return 999999999999;
            }
          }
        }
        return getValueByKey(row, column.field); // 返回正常的得分，进行排序
      }
    }));

    // 添加维度名称及其对应的子列
    columns.push({
      title: `${dimName} ${dimData.dimWeight && dimData.dimWeight != "0" ? `(${dimData.dimWeight}%)` : ""}`, // 在 title 后拼接 dimWeight
      children
    });

    // 添加该维度的总分列
    columns.push({
      title: `总分`, // 可根据需要调整标题
      field: `${dimName}_totalSore`,
      width: 120,
      sortable: true,
      sortBy({ column, row }) {
        // 如果是平均行（isAverageRow为true），则返回一个很大的值，避免被排序
        let aa = Number(row[column.field]);
        if (typeof aa === "number" && !isNaN(aa)) {
          if (column.order == "asc") {
            if (row.isAverageRow) {
              return -9999999999;
            }
          } else {
            if (row.isAverageRow) {
              return 99999999999;
            }
          }
        } else {
          // 倒序在最后
          if (column.order == "asc") {
            if (!row.isAverageRow) {
              return 9999999999999;
            } else {
              return -999999999999;
            }
          } else {
            if (!row.isAverageRow) {
              return -999999999999;
            } else {
              return 999999999999;
            }
          }
        }
        return getValueByKey(row, column.field); // 返回正常的得分，进行排序
      }
    });
  });
  gridOptions.columns = columns;
};

// 加载数据
// 保存原始数据副本
const originalData = ref([]);
const loadData = () => {
  gridOptions.loading = true;

  const tableData = rawData.value.map(item => {
    const row = {
      assessmentObjectName: item.assessmentObjectName,
      deptName: item.deptName,
      ranking: item.ranking,
      allScore: item.allScore,
      isAverageRow: item.isAverageRow || false // 确保数据里标记了是否为平均分行
    };

    item.dimensionList.forEach(dim => {
      let totalScore = 0;
      // 填充指标得分
      dim.quotaList.forEach(quota => {
        const fieldName = `${dim.dimName}_${quota.quotaName}`;
        row[fieldName] = quota.quotaScore;
        totalScore += quota.quotaScore;
      });

      // 填充维度总分
      const totalFieldName = `${dim.dimName}_totalSore`;
      row[totalFieldName] = dim.totalSore || totalScore; // 使用 dim.totalSore 或计算得出的总分
    });

    return row;
  });
  originalData.value = [...tableData]; // 深拷贝原始数据

  setTimeout(() => {
    gridOptions.data = tableData;
    fileData.value = JSON.parse(JSON.stringify(tableData));
    console.log("fileData", fileData.value);
    if ($route.name != "workerDrak" && fileData.value.length > 0) {
      fileData.value[0].ranking = "平均得分";
    }
    gridOptions.loading = false;
    useUserStoreHook().tabload = false;
  }, 500);
};

// 监听重新渲染 (造成递归死循环修改逻辑)
// watch($prop.rankTableRefList, newVal => {
//   init(newVal.data, newVal.dept, newVal.name);
//   createColumns();
//   loadData();
//   gridRef.value.setMergeCells([
//     // 合并第一行前两列
//     { row: 0, col: 0, rowspan: 1, colspan: 2 },
//     { row: 2, col: 1, rowspan: 0, colspan: 0 }
//   ]);
// });
// 导出
const exportEvent = () => {
  let $grid;
  let fileName =
    localStorage.getItem("fileName") + dayjs().format("YYYY-MM-DD HH:mm:ss");
  if ($route.name != "workerDrak") {
    $grid = gridRef.value;
  } else {
    $grid = gridRef1.value;
  }
  if ($grid) {
    $grid.exportData({
      type: "xlsx",
      filename: fileName,
      useStyle: true,
      isMerge: true,
      data: fileData.value
    });
  } else {
    ElMessage({
      message: "暂无数据",
      type: "warning"
    });
  }
};
</script>

<style lang="scss" scoped>
.diamond {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 25px;

  /* 菱形宽度 */
  height: 25px;

  /* 菱形高度 */
  padding-top: 1px;
  margin: auto;
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);

  /* 定义六边形的形状 */

  font-size: 12px;
  color: white;
  background-color: #d3e8f0;

  /* 背景颜色 */
}

.aa {
  position: relative;
}
</style>
