<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="会员姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入会员姓名"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="会员状态" prop="vipStatus">
          <el-select
            v-model="queryParams.vipStatus"
            placeholder="请选择会员状态"
            clearable
            class="!w-240px"
          >
            <el-option label="已开通" :value="true" />
            <el-option label="未开通" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="memberList"
      >
        <el-table-column label="编号" align="center" prop="id"  width="100"/>
        <el-table-column label="姓名" align="center" prop="name"  width="100"/>
        <el-table-column label="手机号" align="center" prop="phone"  width="200"/>
        <el-table-column label="VIP状态" align="center" prop="isvip" width="100" >
          <template #default="scope">
            <el-tag :type="scope.row.isvip === 1 ? 'success' : 'info'">
              {{ scope.row.isvip === 1 ? '已开通' : '未开通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="address"   />
        <el-table-column label="剩余天数" align="center" prop="vipendtime" width="100">
          <template #default="scope">
            <span v-if="scope.row.isvip === 1" class="text-primary">{{ calculateRemainingDays(scope.row.vipendtime, scope.row.vipstarttime) }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="到期时间" align="center" prop="vipendtime" width="200">
          <template #default="scope">
            <span v-if="scope.row.isvip === 1" class="text-primary">{{ formatDate(scope.row.vipendtime) }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <div class="flex items-center justify-center">
              <el-button
                v-if="scope.row.isvip === 0"
                type="primary"
                link
                size="small"
                @click="handleRecharge(scope.row)"
              >
                <Icon icon="ep:video-play" />开通会员
              </el-button>
              <template v-else>
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleRecharge(scope.row)"
                >
                  <Icon icon="ep:refresh" />续费
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleCancel(scope.row)"
                >
                  <Icon icon="ep:close" />取消会员
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 续费弹窗 -->
    <RechargeDialog
      v-model:visible="rechargeDialogVisible"
      :member="currentMember"
      @success="handleRechargeSuccess"
    />

    <!-- 密码验证弹窗 -->
    <PasswordVerifyDialog
      v-model:visible="passwordVerifyVisible"
      @success="handlePasswordVerifySuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RechargeDialog from './components/RechargeDialog.vue'
import { PersonApi } from '@/api/person'
import { getUserProfile } from '@/api/system/user/profile'

// 会员列表数据
const memberList = ref([])
const loading = ref(false)
const total = ref(0)
const userProfile = ref()
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
})

const queryFormRef = ref()

// 对话框控制
const rechargeDialogVisible = ref(false)
const passwordVerifyVisible = ref(false)

// 当前选中的会员
const currentMember = ref(null)

// 计算剩余天数
const calculateRemainingDays = (endTime, startTime) => {
  if (!endTime || !startTime) return '-'
  const end = new Date(endTime)
  const start = new Date(startTime)
  const now = new Date()
  
  // 计算总天数
  const totalDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))
  // 计算剩余天数
  const remainingDays = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  
  return remainingDays > 0 ? `${remainingDays}天` : '已过期'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取会员列表
const getList = async () => {
  loading.value = true
  try {
    //首先获取用户信息
    userProfile.value = await getUserProfile()
    const res = await PersonApi.getPersonPage({
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      orgid: userProfile.value.dept.id
    })
    // 检查返回的数据结构
    if (res) {
      memberList.value = res.list
      total.value = res.total
      console.log(memberList.value)
    } else {
      memberList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取会员列表失败:', error)
    ElMessage.error('获取会员列表失败')
    memberList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 续费/开通会员
const handleRecharge = (member) => {
  currentMember.value = member
  rechargeDialogVisible.value = true
}

// 续费成功
const handleRechargeSuccess = (data) => {
  const member = mockMembers.find(m => m.id === data.memberId)
  if (member) {
    member.vipStatus = true
    member.vipExpireDate = data.expireDate
    getList()
    ElMessage.success('操作成功')
  }
}

// 取消会员
const handleCancel = (member) => {
  currentMember.value = member
  passwordVerifyVisible.value = true
}

// 密码验证成功
const handlePasswordVerifySuccess = (password) => {
  // TODO: 这里需要调用后端API验证密码并取消会员
  // 模拟API调用
  setTimeout(() => {
    const index = mockMembers.findIndex(m => m.id === currentMember.value.id)
    if (index !== -1) {
      mockMembers[index] = {
        ...currentMember.value,
        vipStatus: false,
        vipExpireDate: ''
      }
      getList()
      ElMessage.success('已取消会员资格')
      // 关闭密码验证弹窗
      passwordVerifyVisible.value = false
      // 清空当前选中的会员
      currentMember.value = null
    }
  }, 500)
}

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

<style scoped>
.text-primary {
  color: var(--el-color-primary);
}

.text-gray-400 {
  color: var(--el-text-color-secondary);
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-border: 1px solid var(--el-table-border-color);
  --el-table-text-color: var(--el-text-color-regular);
  --el-table-header-text-color: var(--el-text-color-secondary);
  --el-table-row-hover-bg-color: var(--el-fill-color-light);
  --el-table-current-row-bg-color: var(--el-color-primary-light-9);
  --el-table-header-height: 50px;
  --el-table-row-height: 60px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 4px;
}

:deep(.el-button--link) {
  padding: 0 6px;
  height: 26px;
  font-size: 13px;
}

:deep(.el-button--link .el-icon) {
  margin-right: 2px;
  font-size: 14px;
}
</style>
