<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="培训资料" prop="resourceIds">
        <el-button type="primary" size="mini" @click="showResourceDialog">选择培训资料</el-button>
        <div v-if="selectedResources.length > 0" class="selected-resources mt10">
          <el-tag v-for="resource in selectedResources" :key="resource.resourceId" closable @close="removeResource(resource.resourceId)"
            class="mr10 mb10">
            {{ resource.title }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item label="参培成员" prop="userIds">
        <el-button type="primary" size="mini" @click="showUserDialog" :disabled="!form.resourceIds || form.resourceIds.length === 0">选择参培成员</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>

    <!-- 培训资料选择对话框 -->
    <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" @selection-change="handleResourceSelectionChange" ref="resourceTable">
        <el-table-column type="selection" width="55" reserve-selection />
        <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" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmResourceSelection">确 定</el-button>
        <el-button @click="resourceDialogVisible = false">取 消</el-button>
      </div>
    </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 { listResource } from "@/api/oa/study/resource";
import { listUser } from "@/api/system/user";
import { listStudy } from "@/api/oa/study/myStudy";

export default {
  name: "TrainRecord",
  props: {
    trainId: {
      type: String,
    }
  },
  data() {
    return {
      // 表单数据
      form: {
        resourceIds: [],
        userIds: [],
        lastTime: null
      },
      // 表单校验规则
      rules: {
        resourceIds: [
          { required: true, message: "请选择培训资料", trigger: "change" }
        ],
        userIds: [
          { required: true, message: "请选择参培成员", trigger: "change" }
        ],
        lastTime: [
          { required: true, message: "请选择学习时间", trigger: "change" }
        ]
      },
      // 培训资料选择对话框
      resourceDialogVisible: false,
      resourceLoading: false,
      resourceList: [],
      resourceTotal: 0,
      resourceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      },
      selectedResources: [],
      tempSelectedResources: [], // 临时存储选中的资源
      // 参培成员选择对话框
      userDialogVisible: false,
      userLoading: false,
      userList: [],
      userTotal: 0,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      selectedUsers: [],
      existingUserIds: [],
      tempSelectedUsers: [], // 临时存储选中的用户
    };
  },
  methods: {
    /** 显示培训资料选择对话框 */
    showResourceDialog() {
      this.resourceDialogVisible = true;
      this.tempSelectedResources = [...this.selectedResources]; // 初始化临时选中资源
      this.getResourceList();
      // 在下一个tick中设置选中状态
      this.$nextTick(() => {
        if (this.$refs.resourceTable) {
          this.resourceList.forEach(row => {
            if (this.tempSelectedResources.some(resource => resource.resourceId === row.resourceId)) {
              this.$refs.resourceTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },
    /** 查询培训资料列表 */
    getResourceList() {
      this.resourceLoading = true;
      listResource(this.resourceQueryParams).then(response => {
        this.resourceList = response.rows;
        this.resourceTotal = response.total;
        this.resourceLoading = false;
        // 在数据加载后恢复选中状态
        this.$nextTick(() => {
          if (this.$refs.resourceTable) {
            this.resourceList.forEach(row => {
              if (this.tempSelectedResources.some(resource => resource.resourceId === row.resourceId)) {
                this.$refs.resourceTable.toggleRowSelection(row, true);
              }
            });
          }
        });
      });
    },
    /** 培训资料查询按钮操作 */
    handleResourceQuery() {
      this.resourceQueryParams.pageNum = 1;
      this.getResourceList();
    },
    /** 重置培训资料查询 */
    resetResourceQuery() {
      this.resourceQueryParams = {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      };
      this.handleResourceQuery();
    },
    /** 培训资料选择变化 */
    handleResourceSelectionChange(selection) {
      this.tempSelectedResources = selection;
    },
    /** 确认培训资料选择 */
    confirmResourceSelection() {
      // 去重处理
      const uniqueResources = this.tempSelectedResources.reduce((acc, current) => {
        const x = acc.find(item => item.resourceId === current.resourceId);
        if (!x) {
          return acc.concat([current]);
        } else {
          return acc;
        }
      }, []);
      
      this.selectedResources = uniqueResources;
      this.form.resourceIds = this.selectedResources.map(resource => resource.resourceId);
      this.resourceDialogVisible = false;
      // 获取所有选中资源的已学习记录
      this.getExistingRecords(this.form.resourceIds);
    },
    /** 移除已选培训资料 */
    removeResource(resourceId) {
      this.selectedResources = this.selectedResources.filter(resource => resource.resourceId !== resourceId);
      this.form.resourceIds = this.selectedResources.map(resource => resource.resourceId);
      // 同时更新临时选中资源
      this.tempSelectedResources = this.tempSelectedResources.filter(resource => resource.resourceId !== resourceId);
      // 更新表格选中状态
      this.$nextTick(() => {
        if (this.$refs.resourceTable) {
          this.resourceList.forEach(row => {
            if (row.resourceId === resourceId) {
              this.$refs.resourceTable.toggleRowSelection(row, false);
            }
          });
        }
      });
      // 重新获取已学习记录
      this.getExistingRecords(this.form.resourceIds);
    },
    /** 显示参培成员选择对话框 */
    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(resourceIds) {
      if (!resourceIds || resourceIds.length === 0) return;
      // 获取所有选中资源的已学习记录
      const promises = resourceIds.map(resourceId => 
        listStudy({
          resourceId,
          pageSize: 9999,
          pageNum: 1
        })
      );
      
      Promise.all(promises).then(responses => {
        // 合并所有资源的已学习用户ID
        this.existingUserIds = responses.reduce((acc, response) => {
          return [...acc, ...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-resources,
.selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>