<!-- 成果列表 -->
<template>
  <div class="app-container">
    <!-- 左右分栏布局 -->
    <div class="main-layout" :class="{ 'viewer-mode': isViewerRole }">
      <!-- 左侧：文件上传情况 -->
      <div class="left-panel">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="文件名称" prop="wjmc">
            <el-input v-model="queryParams.wjmc" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="资料类型" prop="zllx">
            <el-select v-model="queryParams.zllx" placeholder="请选择资料类型" clearable>
              <el-option
                v-for="item in zllxOptions"
                :key="item.id"
                :label="item.lxmc"
                :value="item.lxmc">
              </el-option>
            </el-select>
          </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-button v-if="!isViewerRole" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['yscgWjscqk:wjscqk:add']">新增</el-button>
            <el-button v-if="!isViewerRole" type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['yscgWjscqk:wjscqk:edit']">修改</el-button>
            <el-button v-if="!isViewerRole" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['yscgWjscqk:wjscqk:remove']">删除</el-button>
            <el-button v-if="!isViewerRole" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['yscgWjscqk:wjscqk:export']">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="loading" :data="wjscqkList" @selection-change="handleSelectionChange">
          <el-table-column v-if="!isViewerRole" type="selection" width="55" align="center" />
          <el-table-column label="文件名称" align="center" prop="wjmc" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="text" @click="handleDownload(scope.row)" style="padding: 0; color: #409EFF;">
                {{ scope.row.wjmc }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="资料类型" align="center" prop="zllx" min-width="100" show-overflow-tooltip />
          <el-table-column label="上传时间" align="center" prop="createdTime" min-width="170" show-overflow-tooltip />
          <el-table-column v-if="!isViewerRole" label="操作" min-width="110" 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="['yscgWjscqk:wjscqk:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['yscgWjscqk:wjscqk:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-share" @click="handleShare(scope.row)"
                v-hasPermi="['yscgWjscqk:wjscqk:share']">分享</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" />
      </div>

      <!-- 右侧：项目成员 -->
      <div v-if="!isViewerRole" class="right-panel">
        <div class="xmcy-panel">
          <!-- 标题和操作栏 -->
          <div class="xmcy-header">
            <h3 class="xmcy-title">项目成员 ({{ xmcyTotal }})</h3>
            <div class="xmcy-actions">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleXmcyAdd"
                class="invite-btn"
              >邀请作成员</el-button>
              <el-button
                type="text"
                icon="el-icon-search"
                size="small"
                @click="toggleSearch"
                class="search-btn"
              ></el-button>
            </div>
          </div>

          <!-- 搜索框 -->
          <div v-show="showSearchBox" class="xmcy-search">
            <el-input
              v-model="xmcyQueryParams.nickName"
              placeholder="搜索成员"
              clearable
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleXmcyQuery"
              @clear="handleXmcyQuery"
              size="small"
            >
            </el-input>
          </div>

          <!-- 项目成员列表 -->
          <div class="xmcy-list" v-loading="xmcyLoading">
            <div
              v-for="item in xmcyList"
              :key="item.cyid"
              class="xmcy-item"
            >
              <div class="xmcy-item-left">
                <!-- 头像图标 -->
                <div class="xmcy-avatar avatar-member">
                  <i class="el-icon-user"></i>
                </div>
                <div class="xmcy-info">
                  <!-- 角色标签 -->
                  <div class="xmcy-role-tag">
                    <dict-tag :options="dict.type.xm_js" :value="item.xmjs"/>
                  </div>
                  <!-- 用户姓名 -->
                  <div class="xmcy-name">{{ item.nickName }}</div>
                </div>
              </div>
              <div class="xmcy-item-right">
                <el-dropdown trigger="click" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <i class="el-icon-arrow-down"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{action: 'edit', row: item}">
                      <i class="el-icon-edit"></i> 修改
                    </el-dropdown-item>
                    <el-dropdown-item divided>
                      <el-popconfirm
                        title="是否确认删除该成员？"
                        @confirm="handleXmcyDelete(item)"
                        placement="top"
                      >
                        <span slot="reference" style="display: block; width: 100%;">
                          <i class="el-icon-delete"></i> 删除
                        </span>
                      </el-popconfirm>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!xmcyLoading && xmcyList.length === 0" class="xmcy-empty">
              <p>暂无成员</p>
            </div>
          </div>

        </div>
      </div>
    </div>

    <!-- 添加或修改成果管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="89px">

      <el-form-item label="资料类型" prop="zllx">
        <el-select v-model="form.zllx" placeholder="请选择资料类型" clearable>
          <el-option
            v-for="item in zllxOptions"
            :key="item.id"
            :label="item.lxmc"
            :value="item.lxmc">
          </el-option>
        </el-select>
      </el-form-item>

       <el-form-item label="文件上传" prop="fileList">
         <el-upload
           ref="fileUpload"
           :action="uploadUrl"
           :headers="uploadHeaders"
           :file-list="fileList"
           :before-upload="handleBeforeUpload"
           :on-success="handleUploadSuccess"
           :on-error="handleUploadError"
           :on-remove="handleRemove"
           :on-exceed="handleExceed"
           :on-change="handleFileChange"
           :data="uploadData"
           drag
           class="upload-dragger"
         >
           <i class="el-icon-upload"></i>
           <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
           <div class="el-upload__tip" slot="tip">
             支持 doc、docx、pdf、xls、xlsx、ppt、pptx、txt、jpg、jpeg、png、gif 格式文件<br/>
             <span style="color: #409EFF;">上传新文件将自动替换已有文件</span>
           </div>
         </el-upload>
       </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="xmcyTitle" :visible.sync="xmcyOpen" width="500px" append-to-body>
      <el-form ref="xmcyForm" :model="xmcyForm" :rules="xmcyRules" label-width="80px">
        <el-form-item label="用户姓名" prop="nickName">
          <el-input v-model="xmcyForm.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="xmcyForm.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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitXmcyForm">确 定</el-button>
        <el-button @click="cancelXmcy">取 消</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 { listWjscqk, getWjscqk, delWjscqk, addWjscqk, updateWjscqk } from "@/api/yscgWjscqk/wjscqk"
import { selectZllx } from "@/api/yscgZllx/zllx"
import { getToken } from "@/utils/auth"
import { listXmcy, getXmcy, delXmcy, addXmcy, updateXmcy } from "@/api/ysqqXmxxXmcy/xmcy"
import { listUser } from "@/api/system/user"

export default {
  name: "Wjscqk",
  dicts: ['xm_js'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成果管理表格数据
      wjscqkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        xmid: null,
        wjmc: null,
        zllx: null,
        wjlj: null,
        createdBy: null,
        createdTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 资料类型选项
      zllxOptions: [],
      // 文件列表
      fileList: [],
      // 上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      uploadHeaders: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {},
      // 项目成员相关数据
      // 项目成员列表加载状态
      xmcyLoading: false,
      // 项目成员列表
      xmcyList: [],
      // 项目成员总条数
      xmcyTotal: 0,
      // 项目成员查询参数
      xmcyQueryParams: {
        pageNum: 1,
        pageSize: 9999,
        nickName: null,
        zbid: null
      },
      // 项目成员表单参数
      xmcyForm: {},
      // 项目成员表单校验
      xmcyRules: {
        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "change" }
        ],
        xmjs: [
          { required: true, message: "项目角色不能为空", trigger: "change" }
        ]
      },
      // 项目成员弹出层标题
      xmcyTitle: "",
      // 是否显示项目成员弹出层
      xmcyOpen: false,
      // 选择用户对话框
      userDialogVisible: false,
      // 用户列表加载状态
      userLoading: false,
      // 用户列表
      userList: [],
      // 用户列表总条数
      userTotal: 0,
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null
      },
      // 是否显示搜索框
      showSearchBox: false,
      // 当前用户的项目角色
      currentUserRole: null,
      // 是否为查看者角色
      isViewerRole: false
    }
  },
  created() {
    // 获取路由参数中的id和角色
    if (this.$route.query.xmid) {
      this.queryParams.xmid = this.$route.query.xmid
      // 设置项目成员查询的zbid（xmid对应zbid）
      this.xmcyQueryParams.zbid = this.$route.query.xmid
    }
    // 获取路由参数中的项目角色
    if (this.$route.query.xmjs) {
      this.currentUserRole = this.$route.query.xmjs
    }
    this.getList()
    this.getZllxOptions()
  },
  mounted() {
    // 在字典加载完成后判断角色
    this.$nextTick(() => {
      if (this.dict && this.dict.type && this.dict.type.xm_js) {
        this.checkViewerRole()
      }
      // 加载项目成员列表
      if (this.xmcyQueryParams.zbid && !this.isViewerRole) {
        this.getXmcyList()
      }
    })
  },
  watch: {
    // 监听路由参数变化
    '$route.query.xmid'(newId) {
      if (newId) {
        this.queryParams.xmid = newId
        this.xmcyQueryParams.zbid = newId
        this.getList()
        if (!this.isViewerRole) {
          this.getXmcyList()
        }
      }
    },
    // 监听路由参数中的角色变化
    '$route.query.xmjs'(newRole) {
      if (newRole) {
        this.currentUserRole = newRole
      }
    },
    // 监听字典数据变化，字典加载完成后再判断角色
    'dict.type.xm_js'() {
      if (this.dict && this.dict.type && this.dict.type.xm_js) {
        this.checkViewerRole()
      }
    },
    // 监听当前用户角色变化
    currentUserRole() {
      this.checkViewerRole()
    }
  },
  methods: {
    /** 查询成果管理列表 */
    getList() {
      this.loading = true
      listWjscqk(this.queryParams).then(response => {
        const mergedRows = this.mergeRowsById(response.rows || [])
        this.wjscqkList = mergedRows
        this.total = mergedRows.length
        this.loading = false
      })
    },
      /** 将相同id的记录进行合并（合并文件名与文件路径） */
      mergeRowsById(rows) {
        const idToRowMap = {}
        const mergeCommaSeparated = (first, second) => {
          const parts = []
          if (first) parts.push(...String(first).split(',').filter(Boolean))
          if (second) parts.push(...String(second).split(',').filter(Boolean))
          const seen = new Set()
          return parts.filter(item => {
            if (seen.has(item)) return false
            seen.add(item)
            return true
          }).join(',') || null
        }
        rows.forEach(row => {
          const key = row.id
          if (key == null) {
            // 无id的记录直接保留为独立项
            const tempKey = `__no_id__${Math.random()}_${Date.now()}`
            idToRowMap[tempKey] = { ...row }
            return
          }
          if (!idToRowMap[key]) {
            idToRowMap[key] = { ...row }
          } else {
            const existing = idToRowMap[key]
            existing.wjmc = mergeCommaSeparated(existing.wjmc, row.wjmc)
            existing.wjlj = mergeCommaSeparated(existing.wjlj, row.wjlj)
            // 其它字段保持首次出现的值，或可在此按需处理
          }
        })
        return Object.values(idToRowMap)
      },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xmid: null,
        wjmc: null,
        zllx: null,
        wjlj: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      }
      this.fileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    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()
      // 设置xmid参数
      if (this.queryParams.xmid) {
        this.form.xmid = this.queryParams.xmid
      }
      this.open = true
      this.title = "添加成果管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWjscqk(id).then(response => {
        this.form = response.data
        // 确保xmid参数被保持
        if (this.queryParams.xmid) {
          this.form.xmid = this.queryParams.xmid
        }
        // 如果有文件信息，加载到文件列表中（单文件）
        if (this.form.wjmc && this.form.wjlj) {
          this.fileList = [{
            name: this.form.wjmc,
            url: this.form.wjlj,
            status: 'success',
            uid: Date.now()
          }]
        }
        this.open = true
        this.title = "修改成果管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWjscqk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWjscqk(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 delWjscqk(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 分享按钮操作 */
    handleShare(row) {
      // 跳转到文件权限管理页面，传递文件ID
      const fileId = row.id
      this.$router.push({
        path: '/yscgFileRole/filerole',
        query: {
          fileId: fileId,
          wjmc: row.wjmc
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yscgWjscqk/wjscqk/export', {
        ...this.queryParams
      }, `wjscqk_${new Date().getTime()}.xlsx`)
    },
    /** 获取资料类型选项 */
    getZllxOptions() {
      selectZllx().then(response => {
        this.zllxOptions = response.rows || []
      }).catch(() => {
        this.zllxOptions = []
      })
    },
    /** 上传前校验 */
    handleBeforeUpload(file) {
      // 校验文件类型
      const allowedTypes = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'jpeg', 'png', 'gif']
      const fileExt = file.name.split('.').pop().toLowerCase()
      if (!allowedTypes.includes(fileExt)) {
        this.$modal.msgError('文件格式不正确，请上传支持的文件格式！')
        return false
      }

      // 校验文件大小
      // const isLt50M = file.size / 1024 / 1024 < 50
      // if (!isLt50M) {
      //   this.$modal.msgError('上传文件大小不能超过 50MB!')
      //   return false
      // }

      return true
    },
    /** 文件状态改变 */
    handleFileChange(file, fileList) {
      // 如果文件列表超过1个，只保留最新的文件
      if (fileList.length > 1) {
        this.fileList = [fileList[fileList.length - 1]]
      } else {
        this.fileList = fileList
      }
      this.updateFormFiles()
    },
    /** 上传成功 */
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList
      this.updateFormFiles()
      this.$modal.msgSuccess('文件上传成功')
    },
    /** 上传失败 */
    handleUploadError(err, file, fileList) {
      this.$modal.msgError('文件上传失败')
    },
    /** 删除文件 */
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.updateFormFiles()
    },
    /** 文件数量超出限制 */
    handleExceed(files, fileList) {
      // 由于已实现自动替换，此方法不再需要显示错误提示
      // 新文件会自动替换旧文件
    },
    /** 更新表单文件信息 */
    updateFormFiles() {
      if (this.fileList && this.fileList.length > 0) {
        // 单文件上传，直接取第一个文件
        const file = this.fileList[0]
        this.form.wjmc = file.name
        this.form.wjlj = file.response ? file.response.url : file.url
      } else {
        this.form.wjmc = null
        this.form.wjlj = null
      }
    },
    /** 下载文件 */
    handleDownload(row) {
      // 检查是否有文件链接
      if (!row.wjlj) {
        this.$modal.msgWarning('该文件没有下载链接')
        return
      }

      // 处理多个文件的情况（逗号分隔）
      const fileNames = row.wjmc ? String(row.wjmc).split(',').filter(Boolean) : []
      const fileLinks = String(row.wjlj).split(',').filter(Boolean)

      if (fileLinks.length === 0) {
        this.$modal.msgWarning('该文件没有下载链接')
        return
      }

      // 如果只有一个文件，直接下载
      if (fileLinks.length === 1) {
        this.downloadFile(fileLinks[0], fileNames[0] || '文件')
        return
      }

      // 如果有多个文件，显示选择列表
      const fileOptions = fileLinks.map((link, index) => {
        return {
          name: fileNames[index] || `文件${index + 1}`,
          link: link
        }
      })

      // 使用MessageBox选择要下载的文件
      const h = this.$createElement
      const fileListHtml = fileOptions.map((file, index) => {
        return h('div', {
          style: {
            padding: '8px 0',
            cursor: 'pointer',
            color: '#409EFF'
          },
          on: {
            click: () => {
              this.downloadFile(file.link, file.name)
              this.$msgbox.close()
            }
          }
        }, file.name)
      })

      this.$msgbox({
        title: '请选择要下载的文件',
        message: h('div', null, fileListHtml),
        showCancelButton: true,
        confirmButtonText: '取消',
        cancelButtonText: '',
        showConfirmButton: true,
        showCancelButton: false
      }).catch(() => {})
    },
    /** 执行文件下载 */
    downloadFile(url, fileName) {
      if (!url) {
        this.$modal.msgWarning('文件链接无效')
        return
      }

      // 创建一个a标签进行下载
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      this.$modal.msgSuccess('开始下载文件')
    },
    /** 查询项目成员列表 */
    getXmcyList() {
      if (!this.xmcyQueryParams.zbid) {
        return
      }
      this.xmcyLoading = true
      listXmcy(this.xmcyQueryParams).then(response => {
        this.xmcyList = response.rows || []
        this.xmcyTotal = response.total || 0
        this.xmcyLoading = false
      }).catch(() => {
        this.xmcyLoading = false
      })
    },
    /** 搜索项目成员 */
    handleXmcyQuery() {
      this.xmcyQueryParams.pageNum = 1
      this.getXmcyList()
    },
    /** 重置项目成员查询 */
    resetXmcyQuery() {
      this.xmcyQueryParams = {
        pageNum: 1,
        pageSize: 9999,
        nickName: null,
        zbid: this.queryParams.xmid
      }
      this.getXmcyList()
    },
    /** 项目成员表单重置 */
    resetXmcyForm() {
      this.xmcyForm = {
        cyid: null,
        zbid: this.queryParams.xmid,
        userId: null,
        nickName: null,
        xmjs: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("xmcyForm")
    },
    /** 新增项目成员按钮操作 */
    handleXmcyAdd() {
      this.resetXmcyForm()
      this.xmcyOpen = true
      this.xmcyTitle = "添加项目成员"
    },
    /** 修改项目成员按钮操作 */
    handleXmcyUpdate(row) {
      this.resetXmcyForm()
      const cyid = row.cyid
      getXmcy(cyid).then(response => {
        this.xmcyForm = response.data
        // 确保zbid被设置
        this.xmcyForm.zbid = this.queryParams.xmid
        this.xmcyOpen = true
        this.xmcyTitle = "修改项目成员"
      })
    },
    /** 提交项目成员表单 */
    submitXmcyForm() {
      this.$refs["xmcyForm"].validate(valid => {
        if (valid) {
          if (this.xmcyForm.cyid != null) {
            updateXmcy(this.xmcyForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.xmcyOpen = false
              this.getXmcyList()
            })
          } else {
            addXmcy(this.xmcyForm).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.xmcyOpen = false
              this.getXmcyList()
            })
          }
        }
      })
    },
    /** 删除项目成员按钮操作 */
    handleXmcyDelete(row) {
      const cyid = row.cyid
      delXmcy(cyid).then(() => {
        this.getXmcyList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 取消项目成员表单 */
    cancelXmcy() {
      this.xmcyOpen = false
      this.resetXmcyForm()
    },
    /** 打开选择用户对话框 */
    openUserDialog() {
      // 重置查询参数
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: null
      }
      this.userList = []
      this.userTotal = 0
      this.userDialogVisible = true
      this.getUserList()
    },
    /** 搜索用户 */
    handleUserSearch() {
      this.userQueryParams.pageNum = 1
      this.getUserList()
    },
    /** 查询用户列表 */
    getUserList() {
      this.userLoading = true
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows || []
        this.userTotal = response.total || 0
        this.userLoading = false
      }).catch(() => {
        this.userLoading = false
      })
    },
    /** 重置用户查询 */
    resetUserQuery() {
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: null
      }
      this.userList = []
      this.userTotal = 0
    },
    /** 选择用户 */
    handleUserSelect(row) {
      this.xmcyForm.userId = row.userId
      this.xmcyForm.nickName = row.nickName
      this.xmcyForm.phonenumber = row.phonenumber
      this.userDialogVisible = false
    },
    /** 切换搜索框显示 */
    toggleSearch() {
      this.showSearchBox = !this.showSearchBox
      if (this.showSearchBox) {
        this.$nextTick(() => {
          const searchInput = this.$el.querySelector('.xmcy-search input')
          if (searchInput) {
            searchInput.focus()
          }
        })
      } else {
        // 隐藏搜索框时重置查询
        this.resetXmcyQuery()
      }
    },
    /** 下拉菜单命令处理 */
    handleCommand(command) {
      if (command.action === 'edit') {
        this.handleXmcyUpdate(command.row)
      }
    },
    /** 获取头像样式类 */
    getAvatarClass(item) {
      // 根据角色返回不同的样式类，管理员用绿色，其他用蓝色
      if (this.isOwner(item.xmjs)) {
        return 'avatar-admin'
      }
      return 'avatar-member'
    },
    /** 获取头像图标 */
    getAvatarIcon(item) {
      if (this.isOwner(item.xmjs)) {
        return 'el-icon-user-solid'
      }
      return 'el-icon-user'
    },
    /** 判断是否为所有者/管理员 */
    isOwner(xmjs) {
      // 查找字典中标签包含"管理员"或"所有者"的角色
      if (!this.dict || !this.dict.type || !this.dict.type.xm_js) {
        return false
      }
      const role = this.dict.type.xm_js.find(item => item.value === xmjs)
      if (role && (role.label.includes('管理员') || role.label.includes('所有者'))) {
        return true
      }
      // 如果字典值为'1'或'admin'等，也认为是管理员
      return xmjs === '1' || xmjs === 'admin'
    },
    /** 判断是否为查看者角色 */
    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>

<style lang="scss" scoped>
.main-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 150px);
}

.left-panel {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

// 查看者模式下，左侧面板占满整个宽度
.main-layout.viewer-mode .left-panel {
  width: 100%;
}

.right-panel {
  width: 410px;
  flex-shrink: 0;
  border-left: 1px solid #e8eaed;
  padding-left: 20px;
  padding-right: 20px;
}

.xmcy-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

}

.xmcy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8eaed;

  .xmcy-title {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
    color: #212121;
    letter-spacing: 0.1px;
  }

  .xmcy-actions {
    display: flex;
    align-items: center;
    gap: 8px;

    .invite-btn {
      height: 28px;
      padding: 0 12px;
      font-size: 12px;
      border-radius: 4px;
      font-weight: 500;
    }

    .search-btn {
      padding: 4px;
      font-size: 16px;
      color: #757575;
      border-radius: 4px;
      transition: all 0.2s;

      &:hover {
        color: #212121;
        background: rgba(0, 0, 0, 0.04);
      }
    }
  }
}

.xmcy-search {
  margin-bottom: 12px;
}

.xmcy-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 6px;
  padding-top: 2px;
  border: 1px solid #e8eaed;
}

.xmcy-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  margin-bottom: 8px;
  background: #fafafa;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  transition: all 0.2s ease;

  &:hover {
    background: #f5f5f5;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .xmcy-item-left {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
  }

  .xmcy-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    flex-shrink: 0;
    background: #e3f2fd;
    color: #1976d2;

    i {
      font-size: 18px;
    }

    &.avatar-admin {
      background: #e3f2fd;
      color: #1976d2;
    }

    &.avatar-member {
      background: #e3f2fd;
      color: #1976d2;
    }
  }

  .xmcy-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .xmcy-role-tag {
    margin: 0;
    line-height: 1.2;

    ::v-deep .el-tag {
      margin: 0;
      border: none;
      font-size: 10px;
      padding: 0;
      background: transparent;
      color: #999;
      height: auto;
      line-height: 1.2;
      font-weight: 400;
    }
  }

  .xmcy-name {
    font-size: 13px;
    font-weight: 500;
    color: #424242;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 1.3;
  }

  .xmcy-item-right {
    flex-shrink: 0;
    margin-left: 8px;

    .el-dropdown-link {
      cursor: pointer;
      color: #bbb;
      font-size: 14px;
      padding: 4px;
      transition: color 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;

      &:hover {
        color: #666;
        background: rgba(0, 0, 0, 0.04);
      }

      i {
        font-size: 14px;
      }
    }
  }
}

.xmcy-empty {
  text-align: center;
  padding: 60px 20px;
  color: #9aa0a6;

  p {
    margin: 0;
    font-size: 14px;
  }
}

.xmcy-pagination {
  margin-top: 14px;
  padding-top: 12px;
  border-top: 1px solid #e8eaed;
}

// 滚动条样式
.xmcy-list::-webkit-scrollbar {
  width: 6px;
}

.xmcy-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.xmcy-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}
</style>
