<!-- 成果管理 -->
<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="xmmc">
        <el-input v-model="queryParams.xmmc" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="区块" prop="qk">
        <el-input v-model="queryParams.qk" 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-table border v-loading="loading" :data="yscgList" :span-method="spanMethod">
      <el-table-column label="项目名称" align="center" prop="xmmc" min-width="150" show-overflow-tooltip />
      <el-table-column label="区块" align="center" prop="qk" min-width="120" show-overflow-tooltip />
      <el-table-column label="资料类型" align="center" prop="zllxmc" min-width="120" show-overflow-tooltip />
     
      <el-table-column label="上传情况" align="center" min-width="120">
        <template slot-scope="scope">
          <i :class="scope.row.zlsl > 0 ? 'el-icon-check' : 'el-icon-close'" 
             :style="{ color: scope.row.zlsl > 0 ? '#67C23A' : '#F56C6C', fontSize: '18px' }">
          </i>
        </template>
    </el-table-column>
    <el-table-column label="资料数量" align="center" prop="zlsl" min-width="120" show-overflow-tooltip />

      <el-table-column label="成果" align="center" prop="id" min-width="100" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">资料管理</el-button>
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleXmcyInfo(scope.row)">项目成员</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-drawer
      title=""
      :visible.sync="xmcyDrawerVisible"
      direction="rtl"
      size="500px"
      :before-close="() => { xmcyDrawerVisible = false }"
      :wrapperClosable="false"
    >
      <div class="xmcy-drawer-content">
        <!-- 标题和操作栏 -->
        <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" :class="getAvatarClass(item)">
                <i :class="getAvatarIcon(item)"></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 class="xmcy-phone">{{ item.phonenumber || item.userName || '' }}</div>
                <!-- 权限信息 -->
                <div class="xmcy-permission" v-if="isOwner(item.xmjs)">所有者</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 :command="{action: 'delete', row: item}" divided>
                    <i class="el-icon-delete"></i> 删除
                  </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 class="xmcy-pagination" v-show="xmcyTotal>0">
          <pagination
            :total="xmcyTotal"
            :page.sync="xmcyQueryParams.pageNum"
            :limit.sync="xmcyQueryParams.pageSize"
            @pagination="getXmcyList"
          />
        </div>
      </div>

      <!-- 添加或修改项目成员对话框 -->
      <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>
    </el-drawer>
  </div>
</template>

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

export default {
  name: "Yscg",
  dicts: ['xm_js'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
      total: 0,
      // 成果管理表格数据
      yscgList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xmmc: null,
        qk: null
      },
      // 项目成员抽屉显示状态
      xmcyDrawerVisible: false,
      // 项目成员列表加载状态
      xmcyLoading: false,
      // 项目成员列表
      xmcyList: [],
      // 项目成员总条数
      xmcyTotal: 0,
      // 项目成员查询参数
      xmcyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        zbid: null
      },
      // 项目成员表单参数
      xmcyForm: {},
      // 项目成员表单校验
      xmcyRules: {
        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "change" }
        ],
        xmjs: [
          { required: true, message: "项目角色不能为空", trigger: "change" }
        ]
      },
      // 项目成员弹出层标题
      xmcyTitle: "",
      // 是否显示项目成员弹出层
      xmcyOpen: false,
      // 当前选中的项目id
      currentZbid: null,
      // 选择用户对话框
      userDialogVisible: false,
      // 用户列表加载状态
      userLoading: false,
      // 用户列表
      userList: [],
      // 用户列表总条数
      userTotal: 0,
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null
      },
      // 是否显示搜索框
      showSearchBox: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询成果管理列表 */
    getList() {
      this.loading = true
      listYscgList(this.queryParams).then(response => {
        this.yscgList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 成果按钮操作 */
    handleView(row) {
      // 跳转到成果详情页面，传id
      this.$router.push({
        path: '/yscgWjscqk/wjscqk',
        query: {
          xmid: row.id
        }
      })
    },
    /** 项目成员按钮操作 */
    handleXmcyInfo(row) {
      // 设置当前选中的项目id
      this.currentZbid = row.id
      // 重置项目成员查询参数
      this.xmcyQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        zbid: row.id
      }
      // 打开抽屉并加载项目成员列表
      this.xmcyDrawerVisible = true
      this.getXmcyList()
    },
    /** 表格行合并方法 */
    spanMethod({ row, column, rowIndex, columnIndex }) {
      // 项目名称列（第0列）、区块列（第1列）和成果列（第5列）需要合并
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 5) {
        let fieldName, currentValue
        
        if (columnIndex === 0) {
          // 项目名称列根据xmmc合并
          fieldName = 'xmmc'
          currentValue = row[fieldName]
        } else if (columnIndex === 1) {
          // 区块列根据qk合并
          fieldName = 'xmmc'
          currentValue = row[fieldName]
        } else if (columnIndex === 5) {
          // 成果列根据id合并
          fieldName = 'id'
          currentValue = row[fieldName]
        }
        
        // 如果当前值为空，不合并
        if (!currentValue) {
          return [1, 1]
        }
        
        // 如果当前值与上一行相同，则隐藏当前行
        if (rowIndex > 0 && this.yscgList[rowIndex - 1][fieldName] === currentValue) {
          return [0, 0]
        }
        
        // 计算需要合并的行数
        let rowspan = 1
        for (let i = rowIndex + 1; i < this.yscgList.length; i++) {
          if (this.yscgList[i][fieldName] === currentValue) {
            rowspan++
          } else {
            break
          }
        }
        
        return [rowspan, 1]
      }
      
      // 其他列不合并
      return [1, 1]
    },
    /** 查询项目成员列表 */
    getXmcyList() {
      this.xmcyLoading = true
      listXmcy(this.xmcyQueryParams).then(response => {
        this.xmcyList = response.rows
        this.xmcyTotal = response.total
        this.xmcyLoading = false
      }).catch(() => {
        this.xmcyLoading = false
      })
    },
    /** 搜索项目成员 */
    handleXmcyQuery() {
      this.xmcyQueryParams.pageNum = 1
      this.getXmcyList()
    },
    /** 重置项目成员查询 */
    resetXmcyQuery() {
      this.xmcyQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        zbid: this.currentZbid
      }
      this.getXmcyList()
    },
    /** 项目成员表单重置 */
    resetXmcyForm() {
      this.xmcyForm = {
        cyid: null,
        zbid: this.currentZbid,
        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.currentZbid
        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
      this.$modal.confirm('是否确认删除项目成员编号为"' + cyid + '"的数据项？').then(function() {
        return 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
        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)
      } else if (command.action === 'delete') {
        this.handleXmcyDelete(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'
    }
  }
}
</script>

<style lang="scss" scoped>
.xmcy-drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

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

  .xmcy-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #202124;
  }

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

    .invite-btn {
      height: 32px;
      padding: 0 16px;
      font-size: 14px;
    }

    .search-btn {
      padding: 8px;
      font-size: 18px;
    }
  }
}

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

.xmcy-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
}

.xmcy-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.2s;

  &:hover {
    background: #f1f3f5;
  }

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

  .xmcy-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    flex-shrink: 0;

    i {
      font-size: 24px;
    }

    &.avatar-admin {
      background: #e8f5e9;
      color: #4caf50;
    }

    &.avatar-member {
      background: #e3f2fd;
      color: #2196f3;
    }
  }

  .xmcy-info {
    flex: 1;
    min-width: 0;
  }

  .xmcy-role-tag {
    margin-bottom: 4px;

    ::v-deep .el-tag {
      margin-right: 8px;
      border: none;
      font-size: 12px;
      padding: 2px 8px;
    }
  }

  .xmcy-name {
    font-size: 15px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .xmcy-phone {
    font-size: 13px;
    color: #5f6368;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .xmcy-permission {
    font-size: 12px;
    color: #5f6368;
    margin-top: 4px;
  }

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

    .el-dropdown-link {
      cursor: pointer;
      color: #5f6368;
      font-size: 16px;
      padding: 4px;
      transition: color 0.2s;

      &:hover {
        color: #202124;
      }
    }
  }
}

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

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

.xmcy-pagination {
  margin-top: 20px;
  padding-top: 16px;
  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>
