<template>
  <el-dialog :title="'成员管理 - ' + teamName" :visible.sync="dialogVisible" width="1000px" append-to-body :close-on-click-modal="false" @close="handleClose">
    <!-- 查询区域 -->
    <el-form :model="memberQueryParams" ref="memberQueryForm" size="small" :inline="true" label-width="68px" style="margin-bottom: 10px;">
      <el-form-item label="成员姓名" prop="memberName">
        <el-input
          v-model="memberQueryParams.memberName"
          placeholder="请输入成员姓名"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleMemberQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="memberQueryParams.status" placeholder="成员状态" clearable style="width: 200px">
          <el-option
            v-for="dict in dict.type.team_member_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMemberQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetMemberQuery">重置</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="handleMemberAdd"
          v-hasPermi="['resource:team:member:add']"
        >新增成员</el-button>
      </el-col>
    </el-row>

    <!-- 成员列表表格 -->
    <el-table v-loading="memberLoading" :data="memberList" border>
      <el-table-column label="成员姓名" align="center" prop="memberName" :show-overflow-tooltip="true" />
      <el-table-column label="成员编号" align="center" prop="memberCode" :show-overflow-tooltip="true" />
      <el-table-column label="身份证号" align="center" prop="idCard" width="180" />
      <el-table-column label="联系电话" align="center" prop="phone" width="120" />
      <el-table-column label="绑定账号" align="center" min-width="180">
        <template slot-scope="scope">
          <template v-if="scope.row.userId">
            <span>{{ formatBoundUser(scope.row) }}</span>
          </template>
          <el-tag v-else type="info" effect="plain" size="mini">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="职位/角色" align="center" prop="position" :show-overflow-tooltip="true" />
      <el-table-column label="专长" align="center" prop="specialty" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="memberStatusTagType(scope.row.status)">
            {{ memberStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="加入日期" align="center" prop="joinDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleMemberUpdate(scope.row)"
            v-hasPermi="['resource:team:member:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleMemberDelete(scope.row)"
            v-hasPermi="['resource:team:member:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="memberTotal > 0"
      :total="memberTotal"
      :page.sync="memberQueryParams.pageNum"
      :limit.sync="memberQueryParams.pageSize"
      @pagination="getMemberList"
    />

    <!-- 添加或修改成员对话框 -->
    <el-dialog :title="memberTitle" :visible.sync="memberOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="memberForm" :model="memberForm" :rules="memberRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="成员姓名" prop="memberName">
              <el-input v-model="memberForm.memberName" placeholder="请输入成员姓名" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成员编号" prop="memberCode">
              <el-input v-model="memberForm.memberCode" placeholder="请输入成员编号" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="memberForm.idCard" placeholder="请输入身份证号" maxlength="18" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="memberForm.phone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="绑定账号" prop="userId">
              <el-select
                v-model="memberForm.userId"
                placeholder="请选择系统账号"
                filterable
                clearable
                reserve-keyword
                :filter-method="filterUserOptions"
                :loading="userSelectLoading"
                @visible-change="handleUserSelectVisible"
                style="width: 100%"
              >
                <el-option
                  v-for="user in filteredUserOptions"
                  :key="user.userId"
                  :label="formatUserOptionLabel(user)"
                  :value="user.userId"
                />
              </el-select>
              <div class="hint-text" v-if="memberForm.userId">
                绑定账号将用于“我的任务”过滤，如需解绑可清除选择
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职位/角色" prop="position">
              <el-input v-model="memberForm.position" placeholder="请输入职位/角色" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="memberForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.team_member_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="加入日期" prop="joinDate">
              <el-date-picker
                v-model="memberForm.joinDate"
                type="date"
                placeholder="选择加入日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="专长" prop="specialty">
              <el-input v-model="memberForm.specialty" type="textarea" placeholder="请输入专长" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="memberForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMemberForm">确 定</el-button>
        <el-button @click="cancelMemberForm">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listTeamMember, getTeamMember, delTeamMember, addTeamMember, updateTeamMember } from "@/api/resource/team"
import { listUser, getUser as getSystemUser } from "@/api/system/user"

export default {
  name: "TeamMemberDialog",
  dicts: ['team_member_status'],
  props: {
    teamId: {
      required: true
    },
    teamName: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,

      // 成员列表相关
      memberLoading: false,
      memberList: [],
      memberTotal: 0,
      memberQueryParams: {
        pageNum: 1,
        pageSize: 10,
        memberName: undefined,
        status: undefined
      },
      // 成员表单相关
      memberOpen: false,
      memberTitle: "",
      memberForm: {},
      memberRules: {
        memberName: [
          { required: true, message: "成员姓名不能为空", trigger: "blur" },
          { max: 64, message: '成员姓名长度不能超过64个字符', trigger: 'blur' }
        ],
        memberCode: [
          { max: 50, message: '成员编号长度不能超过50个字符', trigger: 'blur' }
        ],
        idCard: [
          {
            validator: (rule, value, callback) => {
              if (value && !/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
                callback(new Error("请输入正确的身份证号"))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value && !/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
                callback(new Error("请输入正确的手机号码"))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        position: [
          { max: 64, message: '职位/角色长度不能超过64个字符', trigger: 'blur' }
        ],
        specialty: [
          { max: 200, message: '专长长度不能超过200个字符', trigger: 'blur' }
        ]
      },
      userOptions: [],
      userSelectLoading: false,
      userOptionsLoaded: false,
      userLabelCache: {},
      filteredUserOptions: []
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val || false;
      if (val) {
        this.getMemberList()
      }
    }
  },
  methods: {
    /** 查询成员列表 */
    getMemberList() {
      this.memberLoading = true
      listTeamMember(this.teamId, this.memberQueryParams).then(response => {
        this.memberList = response.rows
        this.memberTotal = response.total
        this.hydrateMemberUserLabels()
        this.memberLoading = false
      })
    },
    /** 搜索按钮操作 */
    handleMemberQuery() {
      this.memberQueryParams.pageNum = 1
      this.getMemberList()
    },
    /** 重置按钮操作 */
    resetMemberQuery() {
      this.memberQueryParams = {
        pageNum: 1,
        pageSize: 10,
        memberName: undefined,
        status: undefined
      }
      this.handleMemberQuery()
    },
    /** 新增成员按钮操作 */
    handleMemberAdd() {
      this.resetMemberForm()
      this.memberOpen = true
      this.memberTitle = "添加成员"
    },
    /** 修改成员按钮操作 */
    handleMemberUpdate(row) {
      this.resetMemberForm()
      const memberId = row.id
      getTeamMember(this.teamId, memberId).then(response => {
        this.memberForm = response.data
        // 确保状态有默认值
        if (!this.memberForm.status) {
          this.memberForm.status = 'active'
        }
        this.ensureSelectedUserOption(this.memberForm.userId)
        this.memberOpen = true
        this.memberTitle = "修改成员"
      })
    },
    /** 提交成员表单 */
    submitMemberForm() {
      this.$refs["memberForm"].validate(valid => {
        if (valid) {
          // 设置队伍ID
          this.memberForm.teamId = this.teamId
          if (this.memberForm.id != undefined) {
            updateTeamMember(this.teamId, this.memberForm.id, this.memberForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.memberOpen = false
              this.getMemberList()
              // 通知父组件刷新成员数量
              this.$emit('refresh')
            })
          } else {
            addTeamMember(this.teamId, this.memberForm).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.memberOpen = false
              this.getMemberList()
              // 通知父组件刷新成员数量
              this.$emit('refresh')
            })
          }
        }
      })
    },
    /** 取消成员表单 */
    cancelMemberForm() {
      this.memberOpen = false
      this.resetMemberForm()
    },
    /** 表单重置 */
    resetMemberForm() {
      this.memberForm = {
        id: undefined,
        teamId: this.teamId,
        memberName: undefined,
        memberCode: undefined,
        idCard: undefined,
        phone: undefined,
        userId: undefined,
        position: undefined,
        specialty: undefined,
        status: 'active',
        joinDate: undefined,
        remark: undefined
      }
      this.resetForm("memberForm")
    },
    /** 删除成员按钮操作 */
    handleMemberDelete(row) {
      const memberId = row.id
      this.$modal.confirm('是否确认删除成员编号为"' + memberId + '"的数据项？').then(function() {
        return delTeamMember(this.teamId, memberId)
      }.bind(this)).then(() => {
        this.getMemberList()
        this.$modal.msgSuccess("删除成功")
        // 通知父组件刷新成员数量
        this.$emit('refresh')
      }).catch(() => {})
    },
    /** 成员状态标签类型 */
    memberStatusTagType(status) {
      const map = {
        'active': 'success',
        'leave': 'warning',
        'retired': 'info'
      }
      return map[status] || 'info'
    },
    /** 成员状态标签文本 */
    memberStatusLabel(status) {
      const dict = this.dict.type.team_member_status.find(item => item.value === status)
      return dict ? dict.label : status
    },
    handleUserSelectVisible(visible) {
      if (!visible) {
        this.filterUserOptions('')
        return
      }
      if (!this.userOptionsLoaded) {
        this.fetchSystemUsers()
      }
    },
    fetchSystemUsers() {
      if (this.userSelectLoading) return
      this.userSelectLoading = true
      const query = {
        pageNum: 1,
        pageSize: 100,
        status: '0'
      }
      listUser(query)
        .then(res => {
          const rows = (res.rows || []).map(this.normalizeUserOption)
          this.userOptions = rows
          this.filteredUserOptions = rows
          this.userOptionsLoaded = true
          rows.forEach(user => {
            this.setUserLabelCache(user.userId, this.formatUserOptionLabel(user))
          })
        })
        .finally(() => {
          this.userSelectLoading = false
        })
    },
    filterUserOptions(keyword) {
      if (!keyword) {
        this.filteredUserOptions = this.userOptions.slice()
        return
      }
      const lower = keyword.toLowerCase()
      this.filteredUserOptions = this.userOptions.filter(user => {
        const label = this.formatUserOptionLabel(user).toLowerCase()
        return label.includes(lower)
          || (user.userName && user.userName.toLowerCase().includes(lower))
          || (user.nickName && user.nickName.toLowerCase().includes(lower))
          || (user.phonenumber && user.phonenumber.toLowerCase().includes(lower))
      })
    },
    /** 标准化系统用户对象 */
    normalizeUserOption(user) {
      if (!user) return { userId: undefined }
      return {
        userId: user.userId,
        nickName: user.nickName,
        userName: user.userName,
        phonenumber: user.phonenumber
      }
    },
    /** 格式化系统用户选项 */
    formatUserOptionLabel(user) {
      if (!user) return ''
      const display = user.nickName || user.userName || '未命名'
      const extras = []
      if (user.userName && user.userName !== display) {
        extras.push(user.userName)
      }
      if (user.phonenumber) {
        extras.push(user.phonenumber)
      }
      return extras.length ? `${display}（${extras.join(' / ')}）` : display
    },
    /** 为成员列表补齐用户标签 */
    hydrateMemberUserLabels() {
      const ids = Array.from(new Set((this.memberList || []).map(item => item.userId).filter(Boolean)))
      if (!ids.length) {
        this.applyUserLabels()
        return
      }
      const missing = ids.filter(id => !this.userLabelCache[id])
      if (!missing.length) {
        this.applyUserLabels()
        return
      }
      Promise.all(
        missing.map(id =>
          getSystemUser(id)
            .then(res => {
              if (res && res.code === 200 && res.data) {
                const option = this.normalizeUserOption(res.data)
                this.setUserLabelCache(id, this.formatUserOptionLabel(option))
                this.mergeUserOption(option)
              } else {
                this.setUserLabelCache(id, `用户ID: ${id}`)
              }
            })
            .catch(() => {
              this.setUserLabelCache(id, `用户ID: ${id}`)
            })
        ))
        .finally(() => {
          this.applyUserLabels()
        })
    },
    applyUserLabels() {
      (this.memberList || []).forEach(member => {
        if (member.userId) {
          this.$set(member, 'userLabel', this.userLabelCache[member.userId] || `用户ID: ${member.userId}`)
        } else {
          this.$set(member, 'userLabel', '')
        }
      })
    },
    setUserLabelCache(userId, label) {
      if (!userId) return
      this.$set(this.userLabelCache, userId, label || `用户ID: ${userId}`)
    },
    mergeUserOption(option) {
      if (!option || !option.userId) return
      if (!this.userOptions.find(item => item.userId === option.userId)) {
        this.userOptions = [option, ...this.userOptions]
      }
      if (!this.filteredUserOptions.find(item => item.userId === option.userId)) {
        this.filteredUserOptions = [option, ...this.filteredUserOptions]
      }
    },
    ensureSelectedUserOption(userId) {
      if (!userId) return
      if (this.userLabelCache[userId]) {
        this.mergeUserOption({ userId, nickName: this.userLabelCache[userId], userName: '', phonenumber: '' })
        return
      }
      getSystemUser(userId)
        .then(res => {
          if (res && res.code === 200 && res.data) {
            const option = this.normalizeUserOption(res.data)
            this.setUserLabelCache(userId, this.formatUserOptionLabel(option))
            this.mergeUserOption(option)
          }
        })
        .catch(() => {
          this.setUserLabelCache(userId, `用户ID: ${userId}`)
        })
    },
    formatBoundUser(member) {
      if (!member) return '-'
      return member.userLabel
        || this.userLabelCache[member.userId]
        || member.userName
        || member.nickName
        || `ID: ${member.userId}`
    },
    /** 关闭弹窗 */
    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.hint-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>