<!--
 * @Author: ysh
 * @Date: 2025-03-12 10:06:03
 * @LastEditors: wrh
 * @LastEditTime: 2026-01-05 09:22:11
-->
<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="资料名称" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入资料名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="类型" prop="title">
            <el-select v-model="queryParams.type" @change="handleQuery" clearable>
              <el-option label="视频" value="视频"></el-option>
              <el-option label="文档" value="文档"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="userId">
            <el-select v-model="queryParams.userId" clearable filterable placeholder="请输入姓名" style="width: 160px"
              @change="handleQuery">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学习年份" prop="lastTime">
            <el-date-picker clearable v-model="queryParams.lastTime" type="year" value-format="yyyy-MM-dd"
              placeholder="请选择学习年份" @change="handleQuery">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['oa:record:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="studyList">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" width="55" align="center" />
          <!-- <el-table-column label="学习id" align="center" prop="studyId" /> -->
          <el-table-column align="center" label="资料名称" prop="resource.title" />
          <el-table-column align="center" label="类型" prop="resource.type"></el-table-column>
          <el-table-column align="center" label="学习进度" prop="lastPoint">
            <template slot-scope="scope">
              <el-progress :text-inside="true" :stroke-width="26" :status="formatStatus(scope.row.lastPoint)"
                :percentage="Number(scope.row.lastPoint)" text-color="#fff"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="user.nickName" />
          <el-table-column label="上次学习时间" align="center" prop="lastTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已获学时" align="center" prop="getHours" />
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
      <el-col :span="12">
        <div>
          <el-row>
            <el-col :span="12" class=" left">
              <h2 class="text-center">部门学习情况</h2>
              <el-tree :data="deptTree" :props="treeProps" node-key="$treeNodeId" :expand-on-click-node="false">
                <div slot-scope="{ node, data }" class="custom-tree-node">
                  <!-- 部门节点 -->
                  <span v-if="data.type === 'department'">
                    <!-- <i class="el-icon-office-building"></i> -->
                    {{ data.deptName }}
                    <span class="total-hours">(总学时：{{ (data.totalHours).toFixed(1) }}h)</span>
                  </span>
                  <!-- 人员节点 -->
                  <span v-else class="user-node">
                    <i class="el-icon-user"></i>
                    {{ `${data.user.nickName} (学时：${data.getHours.toFixed(1)}h)` }}
                  </span>
                </div>
              </el-tree>
            </el-col>
            <el-col :span="12" class="left">
              <div class="text-right">
                <el-date-picker clearable v-model="rankParams.lastTime" type="year" value-format="yyyy-MM-dd"
                  placeholder="请选择学习年份" @change="getListByYear()">
                </el-date-picker>
              </div>
              <h2 class="text-center">学习排名</h2>
              <el-table v-loading="rankLoading" :data="rankList">
                <el-table-column prop="rankIndex" label="排名" />
                <el-table-column prop="user.nickName" label="姓名" />
                <el-table-column prop="getHours" label="总学时" />
              </el-table>
              <div class="mt20 text-right">
                <el-pagination layout="prev, pager, next" :total="rankTotal" :current-page.sync="rankParams.pageNum"
                  @current-change="getRankList">
                </el-pagination>
              </div>

            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listStudy, getStudy, delStudy, addStudy, updateStudy, getStudyStatistic } from "@/api/oa/study/myStudy";
import { listDept } from '@/api/system/dept'

export default {
  name: "Study",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc学习记录表格数据
      studyList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceId: null,
        userId: null,
        lastPoint: null,
        lastTime: null,
        getHours: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      rankList: [], //排行列表
      rankLoading: true,
      rankTotal: 0,
      rankParams: {
        pageNum: 1,
        pageSize: 10,
      },
      deptRankList: [], //部门排行列表
      deptRankLoading: true,
      deptRankTotal: 0,
      deptRankParams: {
        pageNum: 1,
        pageSize: 10,
      },
      deptTree: [],
      treeProps: {
        children: 'children',
        label: 'deptName' // 默认label字段，实际使用插槽自定义
      },
    };
  },
  created() {
    this.getList();
    this.getRankList();
    this.getDeptRankList();
  },
  methods: {
    /** 查询cmc学习记录列表 */
    getList() {
      this.loading = true;
      listStudy(this.queryParams).then(response => {
        this.studyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRankList() {
      this.rankLoading = true;
      getStudyStatistic(this.rankParams).then(res => {
        this.rankList = res.rows.map((item, index) => ({
          ...item,
          getHours: item.getHours ? item.getHours.toFixed(1) : 0,
          rankIndex: (this.rankParams.pageNum - 1) * this.rankParams.pageSize + index + 1
        }));
        this.rankTotal = res.total;
        this.rankLoading = false;
      })
    },
    async getDeptRankList() {
      this.deptRankParams.pageSize = 300
      this.deptRankParams.lastTime = this.rankParams.lastTime
      let res = await getStudyStatistic(this.deptRankParams)
      let userList = res.rows.map((item, index) => ({
        ...item,
        getHours: item.getHours ? item.getHours : 0,
        rankIndex: index + 1
      }));
      let deptRes = await listDept();
      let deptList = deptRes.data.filter(dept => dept.deptId != 100);
      this.deptTree = this.buildDeptTree(deptList, userList);
    },
    getListByYear() {
      this.getRankList();
      this.getDeptRankList();
    },
    // 表单重置
    reset() {
      this.form = {
        studyId: null,
        resourceId: null,
        userId: null,
        lastPoint: null,
        lastTime: null,
        getHours: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/study/export', {
        ...this.queryParams
      }, `study_${new Date().getTime()}.xlsx`)
    },
    formatStatus(row) {
      if (!row) {
        row = 0
        return 'exception'
      }
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
    buildDeptTree(deptObjList, recordList) {
      // 1. 创建部门映射表（使用Map提高查询效率）
      const deptMap = new Map();
      // 初始化部门节点并存入Map
      deptObjList.forEach(dept => {
        deptMap.set(dept.deptId, {
          ...dept,                  // 展开原有属性
          children: [],             // 存放子节点（人员）
          totalHours: 0,            // 学习时长合计
          type: 'department'        // 添加类型标识（可选）
        });
      });
      // 2. 处理学习记录
      recordList.forEach(record => {
        const dept = deptMap.get(record.deptId);
        if (dept) {
          // 构造人员节点
          const userNode = {
            ...record,              // 展开记录属性
            type: 'user'            // 添加类型标识（可选）
          };
          // 添加人员到部门子节点
          dept.children.push(userNode);
          // 累加学习时长
          dept.totalHours += record.getHours || 0;
        }
      });
      // 3. 将Map转换为数组
      return Array.from(deptMap.values());
    }
  }
};
</script>
<style lang="scss" scoped>
.left {
  padding: 10px;
  border-right: 1px solid #ececec;
}

.dept-tree-container {
  padding: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding: 2px 0;

  .el-icon-office-building {
    color: #409EFF;
    margin-right: 5px;
  }

  .el-icon-user {
    color: #67C23A;
    margin-right: 5px;
  }

  .total-hours {
    color: #909399;
    font-size: 12px;
    margin-left: 10px;
  }

  .user-node {
    color: #606266;
  }
}

/* 调整树节点缩进 */
::v-deep .el-tree-node__content {
  height: auto;
  padding: 2px 0;
}
</style>
