<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          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" v-if="!isViewerRole">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ysqqXmxxXmcy:xmcy: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="['ysqqXmxxXmcy:xmcy: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="['ysqqXmxxXmcy:xmcy: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="['ysqqXmxxXmcy:xmcy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  border v-loading="loading" :data="xmcyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户姓名" align="center" prop="nickName" />
      <el-table-column label="项目角色" align="center" prop="xmjs">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.xm_js" :value="scope.row.xmjs"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建人" align="center" prop="createdBy" /> -->
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!isViewerRole">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ysqqXmxxXmcy:xmcy:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ysqqXmxxXmcy:xmcy: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="nickName">
          <el-input v-model="form.nickName" placeholder="请选择用户" readonly>
            <el-button slot="append" icon="el-icon-search" @click="openUserDialog"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="项目角色" prop="xmjs">
          <el-select style="width: 100%;" v-model="form.xmjs" placeholder="请选择项目角色">
            <el-option
              v-for="dict in dict.type.xm_js"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            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="userDialogVisible" width="800px" append-to-body>
      <el-form :model="userQueryParams" ref="userQueryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="统一账号" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入统一账号"
            clearable
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleUserSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        v-loading="userLoading" 
        :data="userList"    
        @row-click="handleUserSelect"
        highlight-current-row
        style="cursor: pointer;"
      >
        <el-table-column label="统一账号" align="center" prop="userName" />
        <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"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listXmcy, getXmcy, delXmcy, addXmcy, updateXmcy } from "@/api/ysqqXmxxXmcy/xmcy"
import { listUser } from "@/api/system/user"

export default {
  name: "Xmcy",
  dicts: ['xm_js'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 验收前期-项目信息-项目成员表格数据
      xmcyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 项目主键id
      zbid: null,
      // 当前用户在该项目中的角色
      currentUserRole: null,
      // 是否为查看者角色
      isViewerRole: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        zbid: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "change" }
        ],
        xmjs: [
          { required: true, message: "项目角色不能为空", trigger: "change" }
        ]
      },
      // 选择用户对话框
      userDialogVisible: false,
      // 用户列表加载状态
      userLoading: false,
      // 用户列表
      userList: [],
      // 用户列表总条数
      userTotal: 0,
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null
      }
    }
  },
  created() {
    // 从路由参数中获取zbid和当前用户角色
    this.zbid = this.$route.query.zbid
    this.currentUserRole = this.$route.query.xmjs
    this.queryParams.zbid = this.zbid
    this.getList()
  },
  watch: {
    // 监听字典数据变化，字典加载完成后再判断角色
    'dict.type.xm_js'() {
      if (this.dict && this.dict.type && this.dict.type.xm_js) {
        this.checkViewerRole()
      }
    }
  },
  methods: {
    /** 查询验收前期-项目信息-项目成员列表 */
    getList() {
      this.loading = true
      listXmcy(this.queryParams).then(response => {
        this.xmcyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        cyid: null,
        zbid: this.zbid,
        userId: null,
        nickName: null,
        xmjs: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: 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.cyid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加验收前期-项目信息-项目成员"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const cyid = row.cyid || this.ids
      getXmcy(cyid).then(response => {
        this.form = response.data
        // 确保zbid被设置
        this.form.zbid = this.zbid
        this.open = true
        this.title = "修改验收前期-项目信息-项目成员"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cyid != null) {
            updateXmcy(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addXmcy(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cyids = row.cyid || this.ids
      this.$modal.confirm('是否确认删除验收前期-项目信息-项目成员编号为"' + cyids + '"的数据项？').then(function() {
        return delXmcy(cyids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ysqqXmxxXmcy/xmcy/export', {
        ...this.queryParams
      }, `xmcy_${new Date().getTime()}.xlsx`)
    },
    /** 打开选择用户对话框 */ 
    openUserDialog() {
      // 重置查询参数
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null
      }
      this.userList = []
      this.userTotal = 0
      this.userDialogVisible = true
      this.getUserList()
    },
    /** 搜索用户 */
    handleUserSearch() {
      this.userQueryParams.pageNum = 1
      this.getUserList()
    },
    /** 查询用户列表 */
    getUserList() {
      // if (!this.userQueryParams.nickName) {
      //   this.$modal.msgWarning("请输入用户账号")
      //   return
      // }
      this.userLoading = true
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows
        this.userTotal = response.total
        this.userLoading = false
      }).catch(() => {
        this.userLoading = false
      })
    },
    /** 重置用户查询 */
    resetUserQuery() {
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null
      }
      this.userList = []
      this.userTotal = 0
    },
    /** 选择用户 */
    handleUserSelect(row) {
      this.form.userId = row.userId
      this.form.nickName = row.nickName
      this.userDialogVisible = false
    },
    /** 判断是否为查看者角色 */
    checkViewerRole() {
      if (!this.currentUserRole || !this.dict || !this.dict.type || !this.dict.type.xm_js) {
        this.isViewerRole = false
        return
      }
      // 查找字典中标签包含"查看者"的角色
      const role = this.dict.type.xm_js.find(item => item.value === this.currentUserRole)
      if (role && role.label.includes('查看者')) {
        this.isViewerRole = true
      } else {
        this.isViewerRole = false
      }
    }
  }
}
</script>
