<template>
  <div class="app-container">
    <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="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['oa:train:add']">新增</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['oa:train: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 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-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['oa:train:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改培训学习记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="培训资料" prop="resourceId">
          <el-button type="primary" size="mini" @click="showResourceDialog">选择培训资料</el-button>
          <span v-if="selectedResource" class="ml10">{{ selectedResource.title }}</span>
        </el-form-item>
        <el-form-item label="参培成员" prop="userIds">
          <el-button type="primary" size="mini" @click="showUserDialog" :disabled="!form.resourceId">选择参培成员</el-button>
          <div v-if="selectedUsers.length > 0" class="selected-users mt10">
            <el-tag v-for="user in selectedUsers" :key="user.userId" closable @close="removeUser(user.userId)"
              class="mr10 mb10">
              {{ user.nickName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="学习时间" prop="lastTime">
          <el-date-picker v-model="form.lastTime" type="date" placeholder="选择学习时间" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 培训资料选择对话框 -->
    <el-dialog title="选择培训资料" :visible.sync="resourceDialogVisible" width="800px" append-to-body>
      <el-form :inline="true" :model="resourceQueryParams" class="demo-form-inline">
        <el-form-item label="资料名称">
          <el-input v-model="resourceQueryParams.title" placeholder="请输入资料名称" clearable
            @keyup.enter.native="handleResourceQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleResourceQuery">查询</el-button>
          <el-button @click="resetResourceQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="resourceLoading" :data="resourceList" @row-click="handleResourceSelect">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="资料名称" align="center" prop="title" />
        <el-table-column label="类型" align="center" prop="type" />
        <el-table-column label="学时" align="center" prop="hours" />
      </el-table>
      <pagination v-show="resourceTotal > 0" :total="resourceTotal" :page.sync="resourceQueryParams.pageNum"
        :limit.sync="resourceQueryParams.pageSize" @pagination="getResourceList" />
    </el-dialog>

    <!-- 参培成员选择对话框 -->
    <el-dialog title="选择参培成员" :visible.sync="userDialogVisible" width="800px" append-to-body>
      <el-table v-loading="userLoading" :data="userList" @selection-change="handleUserSelectionChange" ref="userTable">
        <el-table-column type="selection" width="55" :selectable="checkUserSelectable" reserve-selection />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="部门" align="center" prop="dept.deptName" />
      </el-table>
      <pagination v-show="userTotal > 0" :total="userTotal" :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize" @pagination="getUserList" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmUserSelection">确 定</el-button>
        <el-button @click="userDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudy, getStudy, delStudy, addStudy, updateStudy } from "@/api/oa/study/myStudy";
import { listResource } from "@/api/oa/study/resource";
import { listUser } from "@/api/system/user";

export default {
  name: "Participate",
  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: {
        resourceId: null,
        userIds: [],
        resourceHours: 0,
        lastTime: null
      },
      // 表单校验
      rules: {
        resourceId: [
          { required: true, message: "培训资料不能为空", trigger: "change" }
        ],
        userIds: [
          { required: true, message: "参培成员不能为空", trigger: "change" }
        ],
        lastTime: [
          { required: true, message: "学习时间不能为空", trigger: "change" }
        ]
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 培训资料选项
      resourceOptions: [],
      // 用户选项
      userOptions: [],
      // 已学习记录
      existingRecords: [],
      // 培训资料选择对话框
      resourceDialogVisible: false,
      resourceLoading: false,
      resourceList: [],
      resourceTotal: 0,
      resourceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      },
      selectedResource: null,
      // 参培成员选择对话框
      userDialogVisible: false,
      userLoading: false,
      userList: [],
      userTotal: 0,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      selectedUsers: [],
      existingUserIds: [],
      tempSelectedUsers: [], // 临时存储选中的用户
    };
  },
  created() {
    this.getList();
    this.getResourceOptions();
  },
  methods: {
    /** 查询cmc学习记录列表 */
    getList() {
      this.loading = true;
      listStudy(this.queryParams).then(response => {
        this.studyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        resourceId: null,
        userIds: [],
        resourceHours: 0,
        lastTime: null
      };
      this.selectedResource = null;
      this.selectedUsers = [];
      this.existingUserIds = [];
      this.tempSelectedUsers = [];
      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'
      }
    },
    /** 获取培训资料选项 */
    getResourceOptions() {
      listResource().then(response => {
        this.resourceOptions = response.rows;
      });
    },
    /** 处理培训资料选择变化 */
    handleResourceChange(value) {
      this.form.userIds = []; // 清空已选择的用户
      this.form.resourceId = value;
      // 获取选中资源的学时
      const selectedResource = this.resourceOptions.find(item => item.resourceId === value);
      if (selectedResource) {
        this.form.resourceHours = selectedResource.hours || 0;
      }
      this.getExistingRecords(value);
    },
    /** 获取已学习记录 */
    getExistingRecords(resourceId) {
      if (!resourceId) return;
      // 设置较大的pageSize以获取所有记录
      listStudy({
        resourceId,
        pageSize: 9999, // 设置一个足够大的值以获取所有记录
        pageNum: 1
      }).then(response => {
        this.existingRecords = response.rows;
        this.updateUserOptions();
      });
    },
    /** 更新用户选项 */
    updateUserOptions() {
      // 获取所有已学习该资源的用户ID
      const existingUserIds = this.existingRecords.map(record => record.userId);

      // 更新用户选项，禁用已存在的用户
      this.userOptions = this.$store.state.user.userList.map(user => ({
        ...user,
        disabled: existingUserIds.includes(user.userId)
      }));

      // 过滤掉已选择的已存在用户
      this.form.userIds = this.form.userIds.filter(userId =>
        !existingUserIds.includes(userId)
      );
    },
    /** 处理用户选择变化 */
    handleUserChange(value) {
      // 获取所有已学习该资源的用户ID
      const existingUserIds = this.existingRecords.map(record => record.userId);

      // 过滤掉已存在的用户
      const validUserIds = value.filter(userId => !existingUserIds.includes(userId));

      // 如果过滤后的数组与原数组不同，说明有无效选择
      if (validUserIds.length !== value.length) {
        this.$message.warning('已存在的学习记录将被忽略');
        this.form.userIds = validUserIds;
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训学习记录";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const promises = this.form.userIds.map(userId =>
            addStudy({
              resourceId: this.form.resourceId,
              userId,
              lastPoint: 100, // 设置学习进度为100%
              getHours: this.form.resourceHours, // 使用资源的学时
              lastTime: this.form.lastTime // 使用选择的学习时间
            })
          );

          Promise.all(promises)
            .then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
            .catch(() => {
              this.$modal.msgError("新增失败");
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studyIds = row.studyId;
      this.$modal.confirm('是否确认删除该培训学习记录？').then(() => {
        return delStudy(studyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 显示培训资料选择对话框 */
    showResourceDialog() {
      this.resourceDialogVisible = true;
      this.getResourceList();
    },
    /** 查询培训资料列表 */
    getResourceList() {
      this.resourceLoading = true;
      listResource(this.resourceQueryParams).then(response => {
        this.resourceList = response.rows;
        this.resourceTotal = response.total;
        this.resourceLoading = false;
      });
    },
    /** 培训资料查询按钮操作 */
    handleResourceQuery() {
      this.resourceQueryParams.pageNum = 1;
      this.getResourceList();
    },
    /** 重置培训资料查询 */
    resetResourceQuery() {
      this.resourceQueryParams = {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      };
      this.handleResourceQuery();
    },
    /** 选择培训资料 */
    handleResourceSelect(row) {
      this.selectedResource = row;
      this.form.resourceId = row.resourceId;
      this.form.resourceHours = row.hours || 0;
      this.resourceDialogVisible = false;
      this.getExistingRecords(row.resourceId);
    },
    /** 显示参培成员选择对话框 */
    showUserDialog() {
      this.userDialogVisible = true;
      this.tempSelectedUsers = [...this.selectedUsers]; // 初始化临时选中用户
      this.getUserList();
      // 在下一个tick中设置选中状态
      this.$nextTick(() => {
        if (this.$refs.userTable) {
          this.userList.forEach(row => {
            if (this.tempSelectedUsers.some(user => user.userId === row.userId)) {
              this.$refs.userTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows;
        this.userTotal = response.total;
        this.userLoading = false;
        // 在数据加载后恢复选中状态
        this.$nextTick(() => {
          if (this.$refs.userTable) {
            this.userList.forEach(row => {
              if (this.tempSelectedUsers.some(user => user.userId === row.userId)) {
                this.$refs.userTable.toggleRowSelection(row, true);
              }
            });
          }
        });
      });
    },
    /** 检查用户是否可选 */
    checkUserSelectable(row) {
      return !this.existingUserIds.includes(row.userId);
    },
    /** 用户选择变化 */
    handleUserSelectionChange(selection) {
      // 更新临时选中用户
      this.tempSelectedUsers = selection;
    },
    /** 确认用户选择 */
    confirmUserSelection() {
      // 去重处理
      const uniqueUsers = this.tempSelectedUsers.reduce((acc, current) => {
        const x = acc.find(item => item.userId === current.userId);
        if (!x) {
          return acc.concat([current]);
        } else {
          return acc;
        }
      }, []);
      
      this.selectedUsers = uniqueUsers;
      this.form.userIds = this.selectedUsers.map(user => user.userId);
      this.userDialogVisible = false;
    },
    /** 移除已选用户 */
    removeUser(userId) {
      this.selectedUsers = this.selectedUsers.filter(user => user.userId !== userId);
      this.form.userIds = this.selectedUsers.map(user => user.userId);
      // 同时更新临时选中用户
      this.tempSelectedUsers = this.tempSelectedUsers.filter(user => user.userId !== userId);
      // 更新表格选中状态
      this.$nextTick(() => {
        if (this.$refs.userTable) {
          this.userList.forEach(row => {
            if (row.userId === userId) {
              this.$refs.userTable.toggleRowSelection(row, false);
            }
          });
        }
      });
    },
    /** 获取已学习记录 */
    getExistingRecords(resourceId) {
      if (!resourceId) return;
      listStudy({
        resourceId,
        pageSize: 9999,
        pageNum: 1
      }).then(response => {
        this.existingUserIds = response.rows.map(record => record.userId);
        this.selectedUsers = this.selectedUsers.filter(user => !this.existingUserIds.includes(user.userId));
        this.form.userIds = this.selectedUsers.map(user => user.userId);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.mb8 {
  margin-bottom: 8px;
}

.ml10 {
  margin-left: 10px;
}

.mt10 {
  margin-top: 10px;
}

.mr10 {
  margin-right: 10px;
}

.mb10 {
  margin-bottom: 10px;
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
}
</style>