<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="projectPid">
        <el-select v-model="queryParams.projectPid"
                   filterable
                    clearable
        >
          <el-option v-for="itemP in projectList" :key="itemP.projectPid" :label="itemP.projectName"
            :value="itemP.projectPid" />
        </el-select>
      </el-form-item>
      <el-form-item label="成员" prop="userId">
        <div class="approver-selector">
          <div class="approver-input" @click="openQueryUserSelect">
            <span v-if="selectedQueryUsers.length === 0" class="placeholder">请选择成员</span>
            <el-tag 
              v-for="(user, index) in selectedQueryUsers" 
              :key="user.userId" 
              closable 
              @close="removeQueryUser(user, index)"
              style="margin-right: 8px; margin-bottom: 5px"
            >
              {{ user.nickName || user.userName }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item label="角色" prop="roleId">
        <el-select v-model="queryParams.roleId">
          <el-option v-for="itemR in roleList" :key="itemR.roleId" :label="itemR.roleName" :value="itemR.roleId" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="进入项目日期" prop="mBdate">
        <el-date-picker clearable v-model="queryParams.mBdate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择进入项目日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="撤出项目日期" prop="mEdate">
        <el-date-picker clearable v-model="queryParams.mEdate" 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="['system:staff: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:staff: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:staff: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:staff:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="staffList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="projectPid" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目来源" align="center" prop="sourceFromName" />
      <el-table-column label="成员账号" align="center" prop="userName" />
      <el-table-column label="成员名称" align="center" prop="nickName" />
      <el-table-column label="成员类型" align="center" prop="userTypeName" />
      <el-table-column label="系统角色" align="center" prop="roleName" />
      <el-table-column label="创建日期" align="center" prop="createTime" />
      <!-- <el-table-column label="进入项目日期" align="center" prop="mBdate" width="180" />
      <el-table-column label="项目编号" align="center" prop="projectPid" min-width="90" >
        <template slot-scope="scope">
          <el-tooltip placement="top" popper-class="pid-tooltip">
            <div slot="content" class="pid-tooltip-content">{{ scope.row.projectPid }}</div>
            <span class="pid-ellipsis">{{ scope.row.projectPid }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName" min-width="320">
        <template slot-scope="scope">
          <el-tooltip placement="top" popper-class="pid-tooltip">
            <div slot="content" class="pid-tooltip-content">{{ scope.row.projectName }}</div>
            <span class="name-ellipsis">{{ scope.row.projectName }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName" /> -->
      <!-- <el-table-column label="角色" align="center" prop="roleName" /> -->
      <el-table-column label="进入项目日期" align="center" prop="mBdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mBdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撤出项目日期" align="center" prop="mEdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mEdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <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:staff:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:staff: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="100px">
        <el-form-item label="项目" prop="projectPid">
          <el-select v-model="form.projectPid"
                     filterable
                     clearable>
            <el-option v-for="itemP in projectList" :key="itemP.projectPid" :label="itemP.projectName"
              :value="itemP.projectPid" />
          </el-select>
        </el-form-item>
        <el-form-item label="成员" prop="userName">
          <div class="approver-selector">
            <div class="approver-input" @click="openUserSelect">
              <span v-if="selectedUsers.length === 0" class="placeholder">请选择成员</span>
              <el-tag 
                v-for="(user, index) in selectedUsers" 
                :key="user.userId" 
                closable 
                @close="removeUser(user, index)"
                style="margin-right: 8px; margin-bottom: 5px"
              >
                {{ user.nickName || user.userName }}
              </el-tag>
            </div>
          </div>
        </el-form-item>

        <!-- <el-form-item label="进入项目日期" prop="mBdate">-->
<!--        <el-form-item label="角色" prop="roleId">-->
<!--          <el-select v-model="form.roleId"-->
<!--                     filterable-->
<!--                     clearable>-->
<!--            <el-option v-for="itemR in roleList" :key="itemR.roleId" :label="itemR.roleName" :value="itemR.roleId" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="进入项目日期" prop="mBdate">
          <el-date-picker clearable v-model="form.mBdate" type="date" value-format="yyyy-MM-dd" placeholder="请选择进入项目日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="撤出项目日期" prop="mEdate">
          <el-date-picker clearable v-model="form.mEdate" type="date" value-format="yyyy-MM-dd" placeholder="请选择撤出项目日期">
          </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="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 />
        </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-column prop="userTypeName" 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>

    <!-- 用户选择组件 -->
    <user-select
      :visible.sync="showUserSelectDialog"
      title="选择成员"
      select-mode="single"
      @confirm="handleUserSelectConfirm"
    />
    
    <!-- 查询表单用户选择组件 -->
    <user-select
      :visible.sync="showQueryUserSelectDialog"
      title="查询成员"
      select-mode="single"
      @confirm="handleQueryUserSelectConfirm"
    />
  </div>
</template>

<script>
import { listStaff, getStaff, delStaff, addStaff, updateStaff, projectList, userList, roleList } from "@/api/system/staff";
import UserSelect from "@/components/UserSelect";

export default {
  name: "Staff",
  components: {
    UserSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目成员表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectPid: null,
        userId: null,
        roleId: null,
        mBdate: null,
        mEdate: null,
      },
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        username: null
      },
      projectList: [],
      userList: [],
      roleList: [],
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        projectPid: [
          { required: true, message: '项目不能为空', trigger: 'red' }
        ],
        userId: [
          { required: true, message: '成员不能为空', trigger: 'red' }
        ],
      },
      showUserDialog: false,
      userTotal: 0,
      // 用户选择相关数据
      showUserSelectDialog: false,
      selectedUsers: [], // 当前选中的用户列表
      
      // 查询表单用户选择相关数据
      showQueryUserSelectDialog: false,
      selectedQueryUsers: [], // 查询表单中选中的用户列表
    };
  },
  created() {
    this.getList();
    this.getProjectList();
    this.getUserList();
    this.getRoleList();
  },
  methods: {

    handleFocusUserInput() {
      this.showUserDialog = true;
      this.getUserList();
      this.getList();
    },

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

    // 获取用户列表
    getUserList() {
      userList(this.queryUserParams).then(response => {
        console.log(response, 'queryUserParams');
        this.userList = response.rows;
        this.userTotal = response.total;
      });
    },

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

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


    /** 查询项目成员列表 */
    getList() {
      this.loading = true;
      listStaff(this.queryParams).then(response => {
        this.staffList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectPid: null,
        userId: null,
        role: null,
        mBdate: null,
        mEdate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.selectedUsers = []; // 清空选中的用户
      this.resetForm("form");
      this.resetForm("queryUserForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectedQueryUsers = []; // 清空查询表单中选中的用户
      this.resetForm("queryForm");
      this.handleQuery();
    },

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

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

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectedUsers = []; // 清空选中的用户
      this.open = true;
      this.title = "添加项目成员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row, 'row');
      this.reset();
      const id = row.id || this.ids
      this.queryUserParams.userId = row.userId;
      this.getUserList();
      getStaff(id).then(response => {
        this.form = response.data;
        // 设置选中的用户信息
        if (row.userName && row.userId) {
          this.selectedUsers = [{
            userId: row.userId,
            userName: row.userName,
            nickName: row.nickName || row.userName
          }];
        }
        this.open = true;
        this.title = "修改项目成员";
      });
      this.queryUserParams.userId = '';
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStaff(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStaff(this.form).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 delStaff(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/staff/export', {
        ...this.queryParams
      }, `staff_${new Date().getTime()}.xlsx`)
    },

    /**获取项目列表 */
    getProjectList() {
      projectList().then(response => {
        this.projectList = response.rows;
      });
    },

    /** 获取用户列表 */
    // getUserList() {
    //   userList().then(response => {
    //     this.userList = response.rows;
    //   });
    // },

    getRoleList() {
      roleList().then(response => {
        this.roleList = response.rows;
      });
    },
    
    // 打开用户选择对话框
    openUserSelect() {
      this.showUserSelectDialog = true;
    },
    
    // 处理用户选择确认
    handleUserSelectConfirm(data) {
      // 单选模式，只取第一个用户
      if (data.users && data.users.length > 0) {
        this.selectedUsers = [data.users[0]];
        this.form.userId = data.users[0].userId;
      }
    },
    
    // 移除选中的用户
    removeUser(user, index) {
      this.selectedUsers.splice(index, 1);
      this.form.userId = null;
    },
    
    // 打开查询表单用户选择对话框
    openQueryUserSelect() {
      this.showQueryUserSelectDialog = true;
    },
    
    // 处理查询表单用户选择确认
    handleQueryUserSelectConfirm(data) {
      // 单选模式，只取第一个用户
      if (data.users && data.users.length > 0) {
        this.selectedQueryUsers = [data.users[0]];
        this.queryParams.userId = data.users[0].userId;
      }
    },
    
    // 移除查询表单中选中的用户
    removeQueryUser(user, index) {
      this.selectedQueryUsers.splice(index, 1);
      this.queryParams.userId = null;
    },
  }
};
</script>

<style scoped>
.approver-selector {
  width: 100%;
}

.approver-input {
  min-height: 32px;
  padding: 0 15px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.2s;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 5px;
}

.approver-input:hover {
  border-color: #C0C4CC;
}

.approver-input:focus {
  border-color: #409EFF;
  outline: none;
}

.placeholder {
  color: #C0C4CC;
  font-size: 14px;
}
</style>

<style>
.pid-ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.name-ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.pid-tooltip {
  max-width: 640px;
  user-select: text;
  word-break: break-all;
}
.pid-tooltip .pid-tooltip-content {
  font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
}
</style>
