<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="userId">
        <el-select v-model="queryParams.userId" filterable clearable @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="deptId">
        <el-select v-model="queryParams.deptId" filterable clearable @change="handleQuery">
          <el-option v-for="item in $store.state.user.deptList" :key="item.deptId" :label="item.deptName"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参培日期" prop="trainTime">
        <el-date-picker clearable v-model="queryParams.trainTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择参培日期">
        </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:trainApproval:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['oa:trainApproval:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainApprovalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="参培id" align="center" prop="participateId" /> -->
      <el-table-column label="参会人" align="center" prop="reportUser.nickName" />
      <el-table-column label="部门" align="center" prop="dept.deptName" />
      <el-table-column label="参培日期" align="center" prop="trainTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训名称" align="center" prop="trainName" />
      <el-table-column label="主要内容" align="center" prop="content" />
      <el-table-column label="学时" align="center" prop="hours" />
      <el-table-column label="审核人" align="center" prop="deptUser.nickName" />
      <el-table-column label="审核时间" align="center" prop="deptTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deptTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核意见" align="center" prop="deptComment" />
      <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-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:trainApproval:edit']"
            :disabled="scope.row.deptUserId !== $store.state.user.id">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['oa:trainApproval:remove']"
            :disabled="scope.row.deptUserId !== $store.state.user.id">删除</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="userId">
          {{ getUserName(form.userId) }}
        </el-form-item>
        <el-form-item label="参培日期" prop="trainTime">
          <el-date-picker clearable v-model="form.trainTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择参培日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="培训名称" prop="trainName">
          <el-input v-model="form.trainName" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="主要内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="请输入主要内容" />
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input-number v-model="form.hours" :min="0" :max="100" :precision="2" :step="0.1" placeholder="请输入学时" />
        </el-form-item>
        <el-form-item label="审核人" prop="deptUserId">
          {{ getUserName(form.deptUserId) }}
        </el-form-item>
        <el-form-item label="审核时间" prop="deptTime">
          <el-date-picker clearable v-model="form.deptTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核意见" prop="deptComment">
          <el-input type="textarea" v-model="form.deptComment" placeholder="请输入审核意见" />
        </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="title" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="培训名称" prop="trainName">
          <el-input v-model="addForm.trainName" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="主要内容" prop="content">
          <el-input type="textarea" v-model="addForm.content" placeholder="请输入主要内容" />
        </el-form-item>
        <el-form-item label="参会人" prop="userIdList">
          <el-select v-model="addForm.userIdList" multiple filterable clearable placeholder="请选择参会人"
            style="width: 100%;">
            <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="trainTime">
          <el-date-picker clearable v-model="addForm.trainTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择参培日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input-number v-model="addForm.hours" :min="0" :max="100" :precision="2" :step="0.1" placeholder="请输入学时" />
        </el-form-item>
        <el-form-item label="审核人" prop="deptUserId">
          {{ addForm.deptUserName }}
        </el-form-item>
        <el-form-item label="审核时间" prop="deptTime">
          <el-date-picker clearable v-model="addForm.deptTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核意见" prop="deptComment">
          <el-input type="textarea" v-model="addForm.deptComment" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrainApproval, getTrainApproval, delTrainApproval, addTrainApproval, updateTrainApproval } from "@/api/oa/study/trainApproval";

import { Snowflake } from '@/utils/snowFlake.js'

export default {
  name: "TrainApproval",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参培审核表格数据
      trainApprovalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        reportTime: null,
        trainName: null,
        content: null,
        hours: null,
        deptUserId: null,
        deptTime: null,
        deptComment: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trainTime: [
          { required: true, message: "参培日期不能为空", trigger: "change" }
        ],
        trainName: [
          { required: true, message: "培训名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "主要内容不能为空", trigger: "blur" }
        ],
        hours: [
          { required: true, message: "学时不能为空", trigger: "blur" },
          { type: 'number', min: 0.1, message: "学时必须大于0", trigger: "blur" }
        ],
        deptTime: [
          { required: true, message: "审核时间不能为空", trigger: "change" }
        ],
        deptComment: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      // 新增表单验证规则
      addRules: {
        userIdList: [
          { required: true, type: 'array', min: 1, message: "请至少选择一位参会人", trigger: "change" }
        ],
        trainTime: [
          { required: true, message: "参培日期不能为空", trigger: "change" }
        ],
        trainName: [
          { required: true, message: "培训名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "主要内容不能为空", trigger: "blur" }
        ],
        hours: [
          { required: true, message: "学时不能为空", trigger: "blur" },
          { type: 'number', min: 0.1, message: "学时必须大于0", trigger: "blur" }
        ],
        deptTime: [
          { required: true, message: "审核时间不能为空", trigger: "change" }
        ],
        deptComment: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      addOpen: false,
      addForm: {
        userIdList: [],
        reportTime: null,
        trainName: null,
        content: null,
        hours: 0,
        deptUserId: null,
        deptUserName: null,
        deptTime: null,
        deptComment: null
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询参培审核列表 */
    getList() {
      this.loading = true;
      listTrainApproval(this.queryParams).then(response => {
        this.trainApprovalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        participateId: null,
        userId: null,
        reportTime: null,
        trainName: null,
        content: null,
        hours: null,
        deptUserId: null,
        deptTime: null,
        deptComment: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.participateId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetAddForm("addForm");
      // 设置当前登录用户为审核人
      this.addForm.deptUserId = this.$store.state.user.id;
      this.addForm.deptUserName = this.$store.state.user.name;
      this.addOpen = true;
      this.title = "添加参培记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const participateId = row.participateId || this.ids
      getTrainApproval(participateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参培审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.participateId != null) {
            updateTrainApproval(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrainApproval(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const participateIds = row.participateId || this.ids;
      this.$modal.confirm('是否确认删除参培审核编号为"' + participateIds + '"的数据项？').then(function () {
        return delTrainApproval(participateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/trainApproval/export', {
        ...this.queryParams
      }, `trainApproval_${new Date().getTime()}.xlsx`)
    },
    submitAddForm() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          // 检查是否选择了参会人员
          if (!this.addForm.userIdList || this.addForm.userIdList.length === 0) {
            this.$modal.msgError("请选择至少一位参会人员");
            return;
          }
          // 获取当前登录用户ID作为审核人
          const currentUserId = this.$store.state.user.id;
          const userList = this.$store.state.user.userList;
          // 为每个参会人员创建一条记录
          const promises = this.addForm.userIdList.map((userId, index) => {
            // 为每个记录使用不同的workerId确保ID唯一性
            const workerId = BigInt((index % 31) + 1); // workerId范围: 1-31
            const snowflake = new Snowflake(workerId, 1n, 0n);
            // 从userList中获取用户的deptId
            const user = userList.find(u => u.userId === userId);
            const deptId = user ? user.deptId : null;
            const recordData = {
              participateId: snowflake.nextId().toString(),
              userId: userId, // 参会人员ID
              deptId: deptId, // 用户的部门ID
              trainTime: this.addForm.trainTime, // 当前日期作为参培日期
              trainName: this.addForm.trainName,
              content: this.addForm.content,
              hours: this.addForm.hours,
              deptUserId: currentUserId, // 当前登录用户作为审核人
              deptTime: this.addForm.deptTime,
              deptComment: this.addForm.deptComment
            };
            return addTrainApproval(recordData);
          });

          // 执行所有新增操作
          Promise.all(promises).then(() => {
            this.$modal.msgSuccess(`成功为 ${this.addForm.userIdList.length} 位参会人员添加培训记录`);
            this.addOpen = false;
            this.resetAddForm("addForm");
            this.getList(); // 刷新列表
          }).catch(error => {
            console.error('添加培训记录失败:', error);
            this.$modal.msgError("添加培训记录失败，请检查网络连接或联系管理员");
          });
        }
      });
    },
    cancelAdd() {
      this.addOpen = false;
      this.resetAddForm("addForm");
    },
    resetAddForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.addForm = {
        userIdList: [],
        reportTime: null,
        trainName: null,
        content: null,
        hours: 0,
        deptUserId: this.$store.state.user.id,
        deptUserName: this.$store.state.user.name,
        deptTime: null,
        deptComment: null
      };
    },
    getUserName(userId) {
      const user = this.$store.state.user.userList.find(item => item.userId === userId);
      return user ? user.nickName : '';
    }
  }
};
</script>
