<script setup lang="ts">
/**
 * 选择班组成员 — 防汛任务人员分配
 *
 * 展示班组成员列表，支持搜索和多选勾选，
 * 按班组分组展示，用于分配防汛任务时选定人员。
 * DESIGN: #1E74FF NavBar, #F4F7F8 bg, white cards border-radius 10px.
 */
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'

const router = useRouter()

// ── 类型 ──
interface Member {
  id: number
  name: string
  phone: string
  team: string
  role: '组长' | '组员'
}

// ── 状态 ──
const searchText = ref('')
const checkedIds = ref<number[]>([])
const loading = ref(false)

// ── 模拟数据 ──
const members = ref<Member[]>([])

const mockMembers: Member[] = [
  { id: 1, name: '张建国', phone: '13800001001', team: 'A组', role: '组长' },
  { id: 2, name: '李明辉', phone: '13800001002', team: 'A组', role: '组员' },
  { id: 3, name: '陈志远', phone: '13800001003', team: 'A组', role: '组员' },
  { id: 4, name: '王强', phone: '13800001004', team: 'B组', role: '组长' },
  { id: 5, name: '赵勇', phone: '13800001005', team: 'B组', role: '组员' },
  { id: 6, name: '周文博', phone: '13800001006', team: 'B组', role: '组员' },
  { id: 7, name: '刘大伟', phone: '13800001007', team: 'C组', role: '组长' },
  { id: 8, name: '孙志强', phone: '13800001008', team: 'C组', role: '组员' },
  { id: 9, name: '马小军', phone: '13800001009', team: 'C组', role: '组员' },
]

// ── 计算属性 ──
const filteredList = computed(() => {
  if (!searchText.value) return members.value
  const kw = searchText.value.toLowerCase()
  return members.value.filter(m =>
    m.name.toLowerCase().includes(kw) ||
    m.phone.includes(kw) ||
    m.team.toLowerCase().includes(kw)
  )
})

/** 按班组分组 */
const groupedMembers = computed(() => {
  const groups: Record<string, Member[]> = {}
  for (const m of filteredList.value) {
    if (!groups[m.team]) groups[m.team] = []
    groups[m.team].push(m)
  }
  return groups
})

const isAllChecked = computed(() =>
  filteredList.value.length > 0 &&
  filteredList.value.every(m => checkedIds.value.includes(m.id))
)

// ── 方法 ──
function toggleCheck(id: number) {
  const idx = checkedIds.value.indexOf(id)
  if (idx >= 0) {
    checkedIds.value.splice(idx, 1)
  } else {
    checkedIds.value.push(id)
  }
}

function toggleAll() {
  if (isAllChecked.value) {
    checkedIds.value = []
  } else {
    checkedIds.value = filteredList.value.map(m => m.id)
  }
}

function onConfirm() {
  if (checkedIds.value.length === 0) {
    showToast('请至少选择一名成员')
    return
  }
  showSuccessToast(`已选择 ${checkedIds.value.length} 人`)
  router.back()
}

onMounted(async () => {
  loading.value = true
  await new Promise(resolve => setTimeout(resolve, 300))
  members.value = mockMembers
  loading.value = false
})
</script>

<template>
  <div class="page-container">
    <!-- 导航栏 -->
    <van-nav-bar title="选择班组成员" left-arrow fixed placeholder @click-left="router.back()">
      <template #right>
        <span class="nav-action" @click="toggleAll">
          {{ isAllChecked ? '取消全选' : '全选' }}
        </span>
      </template>
    </van-nav-bar>

    <!-- 搜索栏 -->
    <van-search v-model="searchText" placeholder="搜索姓名、手机号、班组" shape="round" />

    <!-- 已选提示 -->
    <div v-if="checkedIds.length > 0" class="selected-bar">
      <span>已选 <strong>{{ checkedIds.length }}</strong> 人</span>
      <span class="selected-clear" @click="checkedIds = []">清空</span>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-center" size="24" />

    <!-- 空状态 -->
    <van-empty v-else-if="filteredList.length === 0" description="暂未找到成员" />

    <!-- 成员列表 (按班组分组) -->
    <van-checkbox-group v-else v-model="checkedIds" class="member-list">
      <template v-for="(group, team) in groupedMembers" :key="team">
        <div class="group-header">{{ team }}</div>
        <van-cell-group inset>
          <van-cell
            v-for="item in group"
            :key="item.id"
            :title="item.name"
            :label="item.phone"
            clickable
            @click="toggleCheck(item.id)"
          >
            <template #value>
              <van-tag :type="item.role === '组长' ? 'primary' : undefined" size="medium">
                {{ item.role }}
              </van-tag>
            </template>
            <template #right-icon>
              <van-checkbox
                :name="item.id"
                @click.stop
                :icon-size="20"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </template>
    </van-checkbox-group>

    <!-- 底部确认栏 -->
    <div class="footer-bar">
      <van-button
        type="primary"
        block
        round
        :disabled="checkedIds.length === 0"
        @click="onConfirm"
      >
        确认选择 ({{ checkedIds.length }})
      </van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: var(--color-bg-page);
  padding-bottom: 80px;

  :deep(.van-nav-bar) {
    background: var(--color-primary);
    --van-nav-bar-title-text-color: #fff;
    --van-nav-bar-text-color: #fff;
    --van-nav-bar-icon-color: #fff;
  }
}

.nav-action {
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

// ── 已选提示栏 ──
.selected-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  font-size: 13px;
  color: var(--color-text-secondary);
  background: var(--color-primary-bg);

  strong {
    color: var(--color-primary);
  }

  .selected-clear {
    color: var(--color-danger);
    cursor: pointer;
  }
}

// ── 加载 ──
.loading-center {
  display: flex;
  justify-content: center;
  padding-top: 120px;
}

// ── 分组 ──
.group-header {
  padding: 12px 16px 6px;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.member-list {
  padding: 0 4px;
}

:deep(.van-cell-group) {
  margin: 4px 8px;
  border-radius: 10px;
  overflow: hidden;
}

:deep(.van-cell) {
  padding: 14px 16px;
}

// ── 底部栏 ──
.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  background: var(--color-bg-card);
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.06);
}
</style>
