<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="手机号">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 150px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="queryParams.nickname" placeholder="请输入昵称" clearable style="width: 150px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="身份类型">
          <el-select v-model="queryParams.identityType" placeholder="全部" clearable style="width: 120px">
            <el-option label="家长" value="1" />
            <el-option label="教师" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 100px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" style="margin-top: 12px">
      <el-row :gutter="10" style="margin-bottom: 12px">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="tableData" border stripe :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" style="width: 100%">
        <el-table-column prop="memberNo" label="会员编号" width="140" />
        <el-table-column prop="phone" label="手机号" width="120">
          <template #default="{ row }">
            {{ maskPhone(row.phone) }}
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="60" align="center">
          <template #default="{ row }">
            {{ row.gender === '1' ? '男' : row.gender === '2' ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="100" />
        <el-table-column prop="identityType" label="身份类型" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.identityType === '1' ? 'success' : 'warning'">
              {{ row.identityType === '1' ? '家长' : '教师' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="160" />
        <el-table-column prop="registerSource" label="注册来源" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" link :icon="Key" @click="handleResetPwd(row)">重置密码</el-button>
            <el-popconfirm
              title="确认删除该会员吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" link :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end"
        @size-change="handleQuery"
        @current-change="handleQuery"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <MemberDialog ref="memberDialogRef" @success="handleQuery" />

    <!-- 重置密码弹窗 -->
    <ResetPwdDialog ref="resetPwdDialogRef" />
  </div>
</template>

<script setup>
/**
 * 会员管理页面
 * @author pangu
 */
import { listMember, deleteMember, changeMemberStatus } from '@/api/member'
import { Delete, Edit, Key, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import MemberDialog from './components/MemberDialog.vue'
import ResetPwdDialog from './components/ResetPwdDialog.vue'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dateRange = ref([])

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  phone: '',
  nickname: '',
  identityType: '',
  status: '',
  beginTime: '',
  endTime: ''
})

const memberDialogRef = ref()
const resetPwdDialogRef = ref()

// 手机号脱敏
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 获取会员列表
const getList = async () => {
  loading.value = true
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0]
    queryParams.value.endTime = dateRange.value[1]
  } else {
    queryParams.value.beginTime = ''
    queryParams.value.endTime = ''
  }
  try {
    const res = await listMember(queryParams.value)
    if (res.code === 200) {
      tableData.value = res.rows
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    phone: '',
    nickname: '',
    identityType: '',
    status: '',
    beginTime: '',
    endTime: ''
  }
  dateRange.value = []
  getList()
}

// 新增
const handleAdd = () => {
  memberDialogRef.value?.open()
}

// 编辑
const handleEdit = (row) => {
  memberDialogRef.value?.open(row)
}

// 重置密码
const handleResetPwd = (row) => {
  resetPwdDialogRef.value?.open(row)
}

// 删除
const handleDelete = async (row) => {
  try {
    const res = await deleteMember(row.memberId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 修改状态
const handleStatusChange = async (row) => {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    await ElMessageBox.confirm(
      `确认${text}会员"${row.nickname}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    const res = await changeMemberStatus(row.memberId, row.status)
    if (res.code === 200) {
      ElMessage.success(`${text}成功`)
    } else {
      // 恢复原状态
      row.status = row.status === '0' ? '1' : '0'
      ElMessage.error(res.msg || `${text}失败`)
    }
  } catch (error) {
    // 取消操作，恢复原状态
    row.status = row.status === '0' ? '1' : '0'
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.search-wrapper {
  margin-bottom: 0;
}
</style>
