<script setup lang="ts">
defineOptions({
  name: "departmentRank"
});

import { ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  getAssessmentPageList,
  getPageScoreInfoByAssessment
} from "@/api/manage";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useAppStoreHook } from "@/store/modules/app";

// 考核活动点击交互
const activityList: any = ref([]);
const activeActivity = ref(0);
const activeObj = ref({});
const myTable = ref(null);
const handleActiveActivity = (item: any, index: number) => {
  tableData.value = [];
  myTable.value && myTable.value.clearSort();
  activeActivity.value = index;
  activeObj.value = item;
  getPageScoreInfoByAssessmentApi(item);
};

// 考核活动数据
const getAssessmentPageListApi = async (name = "") => {
  const params: {
    pageNumber: number;
    pageSize: number;
    assessmentType: number;
    name?: string;
  } = {
    pageNumber: 1,
    pageSize: 999999,
    assessmentType: 1 // 0:员工,1:部门,2:医疗组,3:部门负责人
  };
  if (name) {
    params.name = name;
  }
  const { code, msg, data } = await getAssessmentPageList(params);
  if (code === 200) {
    activityList.value = data.records || [];
    if (activityList.value && activityList.value.length) {
      handleActiveActivity(activityList.value[0], 0);
    }
  } else {
    ElMessage.error(msg);
  }
};
onMounted(() => {
  getAssessmentPageListApi();
});
const handleSearch = () => {
  getAssessmentPageListApi(searchKeyword.value);
};

// 右侧列表
const searchKeyword = ref("");
const averageScore = ref<number | string>(0);
const tableData = ref<any>([]);
const getPageScoreInfoByAssessmentApi = async (
  obj: any = {},
  sort: any = { type: 2 }
) => {
  const params = {
    assessmentId: obj.id,
    assessmentType: `${obj.assessmentType}`,
    ...sort
  };
  const { code, msg, data = [] } = await getPageScoreInfoByAssessment(params);
  if (code === 200) {
    tableData.value = data;
    if (tableData.value.length) {
      let allCount = 0;
      tableData.value.forEach(item => {
        if (item.changeScore) {
          allCount += Number(item.changeScore);
        } else if (item.score) {
          allCount += Number(item.score);
        }
      });
      let resultNum: number | string = allCount / tableData.value.length;
      if (
        resultNum.toString().split(".")[1] &&
        resultNum.toString().split(".")[1].length > 3
      ) {
        resultNum = resultNum.toFixed(3);
      }
      averageScore.value = resultNum;
    }
  } else {
    tableData.value = [];
  }
};

// 跳转到数据明细
const router = useRouter();
const toDetail = (row: any = {}, type = "") => {
  router.push({
    path: "/draw/children/department/dataDetail",
    query: {
      mid: row.templateId,
      id: activityList.value[activeActivity.value].id,
      mname: row.templateName,
      name: activityList.value[activeActivity.value].name,
      uname: type === "user" ? row.deptName : ""
    }
  });
  useAppStoreHook().toggleSideBar(false, "关闭");
};

// 倒叙
const handleSortChange = ({ column, prop, order }) => {
  fetchSortedData(order);
};
const fetchSortedData = sortOrder => {
  console.log(sortOrder, "sssss");
  let params: any = {};
  if (sortOrder) {
    params.type = sortOrder === "ascending" ? 1 : 2; // 1 从低到高 2从高到底
  } else {
    params.type = 2;
  }
  getPageScoreInfoByAssessmentApi(activeObj.value, params);
};
</script>

<template>
  <div class="assessment-rank flex">
    <div class="search-section mr-4">
      <el-input
        v-model="searchKeyword"
        placeholder="考核活动名称"
        class="w-64"
        :suffix-icon="Search"
        clearable
        @keyup.enter="handleSearch"
      />
      <div class="search-section-list">
        <p
          v-for="(item, index) in activityList"
          :key="item.id"
          class="mt-4 cursor-pointer overflow-hidden text-ellipsis whitespace-nowrap"
          :style="{ color: activeActivity === index ? '#0052d9' : '#333' }"
          @click="handleActiveActivity(item, index)"
        >
          {{ item.name }}
        </p>
      </div>
    </div>
    <el-card class="w-full">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-base font-medium">平均得分: </span>
          <span>{{ averageScore }}</span>
        </div>
      </template>

      <el-table
        ref="myTable"
        :data="tableData"
        style="width: 100%"
        border
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="排名" width="80" align="center" />
        <el-table-column prop="templateName" label="考核模板" min-width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="toDetail(row, 'model')">
              {{ row.templateName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="科室" min-width="150">
          <template #default="{ row }">
            <el-button type="primary" link @click="toDetail(row, 'user')">
              {{ row.deptName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="score"
          label="实际得分"
          width="120"
          align="right"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.changeScore || row.score }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.assessment-rank {
  padding: 20px 0;
}

.search-section {
  flex-shrink: 0;
  width: 200px;

  .search-section-list {
    height: calc(100vh - 250px);
    margin-top: 20px;
    overflow: auto;
  }
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style>
