<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="部门ID" prop="deptId">
        <el-input v-model="queryParams.deptId" placeholder="请输入部门ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目编号" prop="projectId">
        <el-input v-model="queryParams.projectId" placeholder="请输入项目编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="审核节点" prop="nodeOrder">
        <el-input
          v-model="queryParams.nodeOrder"
          placeholder="请输入审核节点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
<!--      <el-form-item label="审核人" prop="approver">-->
<!--        <el-input v-model="queryParams.approver" placeholder="请输入审核人" clearable @keyup.enter.native="handleQuery" />-->
<!--      </el-form-item>-->
      <!-- <el-form-item label="审核链" prop="chain">
        <el-input
          v-model="queryParams.chain"
          placeholder="请输入审核链"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['system:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:config:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:config:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <!-- <el-table-column label="部门ID" align="center" prop="deptId" />
      <el-table-column label="项目编号" align="center" prop="projectId" />-->
      <el-table-column label="审核顺序" align="center" prop="nodeOrder" />
      <el-table-column label="审核人" align="center" prop="userName" />
      <!-- <el-table-column label="审核链" align="center" prop="chain" /> -->
      <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="['system:config:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:config: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="currentForm" :model="currentForm" :rules="rules" label-width="80px">
        <!--<el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" :disabled="true" />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目编号" :disabled="true" />
        </el-form-item>-->
        <el-form-item label="审核顺序" prop="nodeOrder">
          <el-input type="number" v-model="currentForm.nodeOrder" placeholder="请输入审核顺序" :disabled="false" />
        </el-form-item>
        <el-form-item label="审核人" prop="approver">
          <el-select v-model="currentForm.approver" multiple placeholder="请选择审核人" filterable  >
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
          </el-select>
          <!-- <div style="display: flex; align-items: center; gap: 10px">
            <el-input v-model="form.approver" placeholder="请输入审核人" style="flex: 1" @focus="handleFocusUserInput" /> -->
          <!-- <el-button type="primary" @click="addApprover">新增</el-button>
            <el-button type="danger" @click="removeApprover" :disabled="!currentApprover">删除</el-button> -->
          <!-- </div> -->
          <!-- <div style="margin-top: 10px">
            <el-tag v-for="(approver, index) in this.approverOptions" :key="index" closable @close="handleCloseTag(approver)"
              style="margin-right: 10px; margin-bottom: 5px">
              {{ approver }}
            </el-tag>
          </div> -->
        </el-form-item>
        <!-- <el-form-item label="审核链" prop="chain">
          <el-input v-model="form.chain" placeholder="请输入审核链" :disabled="true" />
        </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="showUserDialog" width="500" append-to-body>
      <el-form :model="queryUserParams" ref="queryUserForm" size="small" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="queryUserParams.userName" placeholder="请输入用户名" clearable @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
      </el-form-item>
      </el-form>

      <el-table :data="userList" style="width: 100%" @row-click="selectUser">
        <el-table-column prop="userId" label="用户ID"></el-table-column>
        <el-table-column prop="userName" label="用户名"></el-table-column>
      </el-table>
      <div class="pagination-container" style="margin-top: 15px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryUserParams.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="queryUserParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="userTotal"></el-pagination>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from "@/api/system/auditConfig";
import { listUser } from "@/api/system/user";

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审核配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        projectId: null,
        // nodeOrder: null,
        approver: null,
        // chain: null,
      },
      currentForm:{
        nodeOrder:null,
        approver:null,
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        approver: [
          { required: true, message: '审核人不能为空', trigger: 'red' }
        ],
         nodeOrder: [
           { required: true, message: '审核顺序能为空', trigger: 'red'}
         ]
      },
      currentApprover: '', // Temporary input for new approver
      approverOptions: [], // List of available approvers
      showUserDialog: false,
      userList: [],
      userTotal: 0,
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        username: null
      },
      list: [],
      appList: [],
      userTotal: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleFocusUserInput() {
      this.showUserDialog = true;
      this.getUserList();
      this.getList();
    },

    // 获取用户列表
    getUserList() {
      listUser(this.queryUserParams).then(response => {
        this.userList = response.rows;
        this.userTotal = response.total;

      });
    },

    handleUserQuery() {
      this.queryParams.pageNum = 1;
      this.getUserList();
    },

    resetUserQuery() {
      this.resetForm("queryUserParams");
      this.handleUserQuery();
    },

    handleUserQuery() {
      this.queryParams.pageNum = 1;
      this.getUserList();
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryUserParams.pageSize = val;
      this.getUserList();
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.queryUserParams.pageNum = val;
      this.getUserList();
    },

    // 选择用户
    selectUser(row) {
      this.form.approver = '';
      this.form.approver = row.userId;
      this.form.userName = row.userName;
      // this.userList.push({ userName: row.userName, userId: row.userId });
      this.showUserDialog = false;
      this.userList = [];
    },

    addApprover() {
      if (this.currentApprover && !this.approverOptions.includes(this.currentApprover)) {
        this.approverOptions.push(this.currentApprover);
        this.currentApprover = '';
      } else if (this.approverOptions.includes(this.currentApprover)) {
        this.$message.warning('该审核人已存在！');
      }
    },

    // 删除审核人
    removeApprover() {
      if (this.currentApprover) {
        const index = this.approverOptions.indexOf(this.currentApprover);
        if (index !== -1) {
          this.approverOptions.splice(index, 1);
          this.currentApprover = '';
          this.$message.success('删除成功！');
        } else {
          this.$message.warning('未找到该审核人！');
        }
      }
    },

    // 处理标签关闭
    handleCloseTag(approver) {
      const index = this.approverOptions.indexOf(approver);
      if (index !== -1) {
        this.approverOptions.splice(index, 1);
        this.$message.success('删除成功！');
      }
    },
    /** 查询审核配置列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        projectId: null,
        nodeOrder: null,
        approver: [],
        chain: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    reset() {
      this.form = {
        userId: null
      };
      this.resetForm("queryUserForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.approverOptions = [];
      this.title = "添加审核配置";
      this.getUserList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('初始')
      this.reset();
      const id = row.id || this.ids
      // this.queryUserParams.userId = row.approver;
      this.approverOptions = [];
      this.getUserList();

      this.currentForm.approver = row.approverList;
      this.currentForm.nodeOrder = row.nodeOrder;
      this.currentForm.id = row.id;
      // getConfig(id).then(response => {
      //   this.form = response.data;
      //   this.approverOptions = this.form.approver.split(',');
        this.open = true;
        this.title = "修改审核配置";
      // });
      // this.queryUserParams.userId = '';
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["currentForm"].validate(valid => {
        if (valid) {
          // 创建表单副本，避免直接修改原始数据
          const submitForm = { ...this.currentForm };
          console.log("123123");
          // 如果 approval 是数组，转换为逗号分隔的字符串
          if (Array.isArray(submitForm.approver)) {
            submitForm.approver = submitForm.approver.join(',');
          }
          if (this.currentForm.id != null) {
            updateConfig(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除审核配置编号为"' + ids + '"的数据项？').then(function () {
        return delConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
