<template>
  <div class="member-card-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left-section">
            <el-select
              v-model="filterType"
              placeholder="卡类型"
              clearable
              style="width: 140px"
              @change="handleFilter"
            >
              <el-option value="TIME_CARD" label="时长卡" />
              <el-option value="COUNT_CARD" label="次卡" />
              <el-option value="STORED_VALUE_CARD" label="储值卡" />
            </el-select>
            <el-input
              v-model="filterName"
              placeholder="搜索卡名称"
              clearable
              style="width: 200px"
              @clear="handleFilter"
              @keyup.enter="handleFilter"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleFilter">搜索</el-button>
          </div>
          <div class="right-section">
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新增会员卡
            </el-button>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="dataSource"
        style="width: 100%"
      >
        <el-table-column prop="memberCardId" label="ID" width="80" />
        <el-table-column prop="memberCardName" label="卡名称" min-width="140" />
        <el-table-column label="卡类型" width="100">
          <template #default="{ row }">
            {{ cardTypeMap[row.memberCardType as string] || row.memberCardTypeDesc || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            ¥{{ row.memberCardPrice ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="卡片详情" min-width="180">
          <template #default="{ row }">
            <template v-if="row.memberCardType === 'TIME_CARD'">
              有效期 {{ row.memberCardValidityDays ?? '-' }} 天
            </template>
            <template v-else-if="row.memberCardType === 'COUNT_CARD'">
              共 {{ row.memberCardTotalTimes ?? '-' }} 次
            </template>
            <template v-else-if="row.memberCardType === 'STORED_VALUE_CARD'">
              面额 ¥{{ row.memberCardAmount ?? '-' }}
            </template>
            <template v-else>
              -
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-switch
              :model-value="row.memberCardStatus === 1"
              active-text="上架"
              inactive-text="下架"
              inline-prompt
              @change="(val: boolean) => handleToggleStatus(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="170">
          <template #default="{ row }">
            {{ row.createdAt ? formatDateTime(row.createdAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end"
        @current-change="fetchData"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="110px"
      >
        <el-form-item label="卡名称" prop="memberCardName">
          <el-input v-model="form.memberCardName" placeholder="请输入卡名称" />
        </el-form-item>
        <el-form-item label="卡类型" prop="memberCardType">
          <el-select
            v-model="form.memberCardType"
            placeholder="请选择卡类型"
            style="width: 100%"
            :disabled="isEditing"
            @change="handleTypeChange"
          >
            <el-option value="TIME_CARD" label="时长卡" />
            <el-option value="COUNT_CARD" label="次卡" />
            <el-option value="STORED_VALUE_CARD" label="储值卡" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="memberCardPrice">
          <el-input-number
            v-model="form.memberCardPrice"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 100%"
            placeholder="请输入价格"
          />
        </el-form-item>
        <!-- 时长卡专用 -->
        <el-form-item
          v-if="form.memberCardType === 'TIME_CARD'"
          label="有效天数"
          prop="memberCardValidityDays"
        >
          <el-input-number
            v-model="form.memberCardValidityDays"
            :min="1"
            :step="30"
            style="width: 100%"
            placeholder="请输入有效天数"
          />
        </el-form-item>
        <!-- 次卡专用 -->
        <el-form-item
          v-if="form.memberCardType === 'COUNT_CARD'"
          label="总次数"
          prop="memberCardTotalTimes"
        >
          <el-input-number
            v-model="form.memberCardTotalTimes"
            :min="1"
            :step="10"
            style="width: 100%"
            placeholder="请输入总次数"
          />
        </el-form-item>
        <!-- 储值卡专用 -->
        <el-form-item
          v-if="form.memberCardType === 'STORED_VALUE_CARD'"
          label="面额"
          prop="memberCardAmount"
        >
          <el-input-number
            v-model="form.memberCardAmount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
            placeholder="请输入面额"
          />
        </el-form-item>
        <el-form-item label="状态" prop="memberCardStatus">
          <el-radio-group v-model="form.memberCardStatus">
            <el-radio :value="1">上架</el-radio>
            <el-radio :value="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { memberCardApi, type MemberCardType } from '@/api/memberCard.api'
import { formatDateTime } from '@/utils/dateFormat'

const loading = ref(false)
const dataSource = ref<MemberCardType[]>([])
const filterType = ref('')
const filterName = ref('')

const cardTypeMap: Record<string, string> = {
  TIME_CARD: '时长卡',
  COUNT_CARD: '次卡',
  STORED_VALUE_CARD: '储值卡',
}

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const fetchData = async () => {
  loading.value = true
  try {
    const res: any = await memberCardApi.list({
      status: undefined,
      name: filterName.value || undefined,
      type: filterType.value || undefined,
      page: pagination.current - 1,
      size: pagination.pageSize,
    })
    if (Array.isArray(res)) {
      dataSource.value = res
      pagination.total = res.length
    } else if (res?.content) {
      dataSource.value = res.content
      pagination.total = res.totalElements ?? res.total ?? 0
    } else if (res?.data) {
      dataSource.value = res.data
      pagination.total = res.total ?? res.data?.length ?? 0
    } else {
      dataSource.value = []
      pagination.total = 0
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

const handleFilter = () => {
  pagination.current = 1
  fetchData()
}

const handleSizeChange = () => {
  pagination.current = 1
  fetchData()
}

// ========== 新增/编辑 ==========

const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)
const isEditing = ref(false)
const editingId = ref<number>()
const formRef = ref()

const defaultForm = () => ({
  memberCardName: '',
  memberCardType: 'TIME_CARD' as string,
  memberCardPrice: undefined as number | undefined,
  memberCardValidityDays: undefined as number | undefined,
  memberCardTotalTimes: undefined as number | undefined,
  memberCardAmount: undefined as number | undefined,
  memberCardStatus: 1,
})

const form = reactive(defaultForm())

const formRules = {
  memberCardName: [{ required: true, message: '请输入卡名称', trigger: 'blur' }],
  memberCardType: [{ required: true, message: '请选择卡类型', trigger: 'change' }],
  memberCardPrice: [{ required: true, message: '请输入价格', trigger: 'blur' }],
}

const handleTypeChange = () => {
  // 切换类型时清空不相关字段
  if (!isEditing.value) {
    form.memberCardValidityDays = undefined
    form.memberCardTotalTimes = undefined
    form.memberCardAmount = undefined
  }
}

const handleCreate = () => {
  isEditing.value = false
  editingId.value = undefined
  dialogTitle.value = '新增会员卡'
  Object.assign(form, defaultForm())
  dialogVisible.value = true
}

const handleEdit = (row: MemberCardType) => {
  isEditing.value = true
  editingId.value = row.memberCardId
  dialogTitle.value = '编辑会员卡'
  form.memberCardName = row.memberCardName || ''
  form.memberCardType = row.memberCardType || 'TIME_CARD'
  form.memberCardPrice = row.memberCardPrice
  form.memberCardValidityDays = row.memberCardValidityDays
  form.memberCardTotalTimes = row.memberCardTotalTimes
  form.memberCardAmount = row.memberCardAmount
  form.memberCardStatus = row.memberCardStatus ?? 1
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  submitting.value = true
  try {
    const body: any = {
      memberCardName: form.memberCardName,
      memberCardType: form.memberCardType,
      memberCardPrice: form.memberCardPrice,
      memberCardStatus: form.memberCardStatus,
    }
    if (form.memberCardType === 'TIME_CARD') {
      body.memberCardValidityDays = form.memberCardValidityDays
    } else if (form.memberCardType === 'COUNT_CARD') {
      body.memberCardTotalTimes = form.memberCardTotalTimes
    } else if (form.memberCardType === 'STORED_VALUE_CARD') {
      body.memberCardAmount = form.memberCardAmount
    }
    if (isEditing.value && editingId.value) {
      await memberCardApi.update(editingId.value, body)
      ElMessage.success('更新成功')
    } else {
      await memberCardApi.create(body)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// ========== 上下架切换 ==========

const handleToggleStatus = async (row: MemberCardType, val: boolean) => {
  if (!row.memberCardId) return
  try {
    const body: any = {
      memberCardName: row.memberCardName,
      memberCardType: row.memberCardType,
      memberCardPrice: row.memberCardPrice,
      memberCardStatus: val ? 1 : 0,
    }
    if (row.memberCardType === 'TIME_CARD') {
      body.memberCardValidityDays = row.memberCardValidityDays
    } else if (row.memberCardType === 'COUNT_CARD') {
      body.memberCardTotalTimes = row.memberCardTotalTimes
    } else if (row.memberCardType === 'STORED_VALUE_CARD') {
      body.memberCardAmount = row.memberCardAmount
    }
    await memberCardApi.update(row.memberCardId, body)
    ElMessage.success(val ? '已上架' : '已下架')
    fetchData()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '操作失败')
  }
}

// ========== 删除 ==========

const handleDelete = async (row: MemberCardType) => {
  if (!row.memberCardId) return
  try {
    await ElMessageBox.confirm(`确定删除会员卡 "${row.memberCardName}" 吗？`, '确认删除', {
      type: 'warning',
    })
    await memberCardApi.delete(row.memberCardId)
    ElMessage.success('删除成功')
    fetchData()
  } catch (e: any) {
    if (e !== 'cancel' && e?.message !== 'cancel') {
      ElMessage.error(e?.response?.data?.message || e?.message || '删除失败')
    }
  }
}

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

<style scoped lang="css">
.member-card-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .left-section {
      display: flex;
      gap: 8px;
      align-items: center;
    }

    .right-section {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
}
</style>
