<template>
  <el-dialog
    v-model="dialogVisible"
    title="成员列表"
    width="700px"
    destroy-on-close
  >
    <div class="mb-15px">
      <el-button
        type="primary"
        plain
        @click="showTransfer = true"
      >
        <Icon icon="ep:plus" /> 添加成员
      </el-button>
    </div>
    <el-table v-loading="loading" :data="memberList">
      <el-table-column label="姓名" align="center" prop="name" width="120" />
      <el-table-column label="手机号码" align="center" prop="mobile" width="140" />
      <el-table-column label="年龄" align="center" prop="age" width="80" />
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template #default="scope">
        {{ scope.row.gender === 'male' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="关系" align="center" prop="relation" width="100">
        <template #default="scope">
        {{ scope.row.relation }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            type="danger"
            link
            @click="handleRemove(scope.row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!-- 添加成员抽屉 -->
  <member-drawer
    v-model="showTransfer"
    :all-members="allMembers"
    @confirm="handleAddMembers"
  />
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import PersonForm from './PersonFrom.vue'
import MemberDrawer from './memberdrawer.vue'

defineOptions({ name: 'PersonMember' })

const dialogVisible = ref(false)
const showTransfer = ref(false)
const loading = ref(false)
const memberList = ref<FamilyMember[]>([])
const currentMember = ref<FamilyMember | null>(null)
const selectedMembers = ref<FamilyMember[]>([])
const formRef = ref()

interface FamilyMember {
  id: number
  name: string
  mobile: string
  age: number
  gender: string
  relation: string
  address: string
  createTime: string
}

// 模拟所有可选成员数据
const allMembers = ref<FamilyMember[]>([
  {
    id: 5,
    name: '赵六',
    mobile: '13800138005',
    age: 30,
    gender: 'male',
    relation: '父亲',
    address: '北京市海淀区中关村大街2号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 6,
    name: '钱七',
    mobile: '13800138006',
    age: 28,
    gender: 'female',
    relation: '母亲',
    address: '北京市海淀区中关村大街3号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 7,
    name: '孙八',
    mobile: '13800138007',
    age: 25,
    gender: 'male',
    relation: '兄弟',
    address: '北京市海淀区中关村大街4号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 8,
    name: '周九',
    mobile: '13800138008',
    age: 22,
    gender: 'female',
    relation: '姐妹',
    address: '北京市海淀区中关村大街5号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 9,
    name: '吴十',
    mobile: '13800138009',
    age: 20,
    gender: 'male',
    relation: '兄弟',
    address: '北京市海淀区中关村大街6号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 10,
    name: '郑十一',
    mobile: '13800138010',
    age: 18,
    gender: 'female',
    relation: '姐妹',
    address: '北京市海淀区中关村大街7号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 11,
    name: '王十二',
    mobile: '13800138011',
    age: 16,
    gender: 'male',
    relation: '兄弟',
    address: '北京市海淀区中关村大街8号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 12,
    name: '赵十三',
    mobile: '13800138010',
    age: 48,
    gender: 'female',
    relation: '舅妈',
    address: '北京市朝阳区建国路10号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 13,
    name: '赵十四',
    mobile: '13800138010',
    age: 48,
    gender: 'female',
    relation: '舅妈',
    address: '北京市朝阳区建国路10号',
    createTime: '2024-03-20 10:00:00'
  },
  {
    id: 14,
    name: '赵十五',
    mobile: '13800138010',
    age: 48,
    gender: 'male',
    relation: '舅妈',
    address: '北京市朝阳区建国路10号',
    createTime: '2024-03-20 10:00:00'
  }
  ])

// 模拟数据 - 这里应该根据实际业务逻辑从后端获取数据
const mockMemberData = {
  1: [
    {
      id: 4,
      name: '张小明',
      mobile: '13800138004',
      age: 12,
      gender: 'male',
      relation: '儿子',
      address: '北京市朝阳区建国路88号',
      createTime: '2024-03-20 10:00:00'
    }
  ],
  2: [],
  3: [],
  4: []
}

const open = (member: FamilyMember) => {
  currentMember.value = member
  dialogVisible.value = true
  getMemberList()
}

const getMemberList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    if (currentMember.value) {
      memberList.value = mockMemberData[currentMember.value.id] || []
    }
  } finally {
    loading.value = false
  }
}

// 判断是否可选
const isSelectable = (row: FamilyMember) => {
  return selectedMembers.value.length < 5 || selectedMembers.value.some(item => item.id === row.id)
}

// 处理选择变化
const handleSelectionChange = (selection: FamilyMember[]) => {
  if (selection.length > 5) {
    // 如果超过5个，只保留前5个
    selectedMembers.value = selection.slice(0, 5)
  } else {
    selectedMembers.value = selection
  }
}

/** 添加成员 */
const handleAddMembers = async (members: FamilyMember[]) => {
  if (!currentMember.value) return
  
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 更新成员列表
  if (!mockMemberData[currentMember.value.id]) {
    mockMemberData[currentMember.value.id] = []
  }
  mockMemberData[currentMember.value.id].push(...members)
  
  // 刷新列表
  await getMemberList()
}

/** 移除成员 */
const handleRemove = async (row: FamilyMember) => {
  if (!currentMember.value) return
  
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 从列表中移除
  const index = mockMemberData[currentMember.value.id].findIndex(
    member => member.id === row.id
  )
  if (index > -1) {
    mockMemberData[currentMember.value.id].splice(index, 1)
  }
  
  // 刷新列表
  await getMemberList()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

const handleSuccess = () => {
  getMemberList()
}

defineExpose({
  open
})
</script>
