<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>盒子类型管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增类型
          </el-button>
        </div>
      </template>

      <!-- 类型列表表格 -->
      <el-table
        v-loading="loading"
        :data="typeList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="类型名称" min-width="120" />
        <el-table-column prop="value" label="类型Key" width="100" align="center" />
        <el-table-column prop="sortOrder" label="排序" width="100" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.sortOrder"
              :min="0"
              :max="9999"
              size="small"
              controls-position="right"
              @change="(val: number) => handleSortChange(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="首页显示" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.isShow"
              :active-value="1"
              :inactive-value="0"
              @change="(val: number) => handleStatusChange(row, 'is_show', val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="支付方式" min-width="200">
          <template #default="{ row }">
            <div class="pay-methods">
              <el-tag v-if="row.payWechat === 1" type="success" size="small">微信</el-tag>
              <el-tag v-if="row.payBalance === 1" type="warning" size="small">{{ currencyNames.balanceName }}</el-tag>
              <el-tag v-if="row.payCurrency === 1" type="info" size="small">{{ currencyNames.currency1Name }}</el-tag>
              <el-tag v-if="row.payCurrency2 === 1" type="danger" size="small">{{ currencyNames.currency2Name }}</el-tag>
              <el-tag v-if="row.payCoupon === 1" size="small">优惠券</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支付类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isDeduction === 1 ? 'warning' : 'primary'" size="small">
              {{ row.isDeduction === 1 ? '抵扣' : '支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cornerText" label="角标文字" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.cornerText" type="danger" size="small">{{ row.cornerText }}</el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" 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-card>

    <!-- 类型新增/编辑弹窗 -->
    <TypeFormDialog
      v-model="formDialogVisible"
      :type-data="currentType"
      :is-edit="isEdit"
      @success="fetchData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import TypeFormDialog from './components/TypeFormDialog.vue'
import {
  getGoodsTypes,
  deleteGoodsType,
  setGoodsTypeStatus,
  updateGoodsType,
  type GoodsTypeItem,
  type CurrencyNames
} from '@/api/business/goods'

// 列表数据
const loading = ref(false)
const typeList = ref<GoodsTypeItem[]>([])
const currencyNames = ref<CurrencyNames>({
  balanceName: '余额',
  currency1Name: '吧唧币',
  currency2Name: '哈尼券'
})

// 弹窗控制
const formDialogVisible = ref(false)
const isEdit = ref(false)
const currentType = ref<GoodsTypeItem | null>(null)

// 获取类型列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getGoodsTypes()
    typeList.value = res.data.list
    currencyNames.value = res.data.currencyNames
  } finally {
    loading.value = false
  }
}

// 新增类型
const handleAdd = () => {
  isEdit.value = false
  currentType.value = null
  formDialogVisible.value = true
}

// 编辑类型
const handleEdit = (row: GoodsTypeItem) => {
  isEdit.value = true
  currentType.value = { ...row }
  formDialogVisible.value = true
}

// 删除类型
const handleDelete = async (row: GoodsTypeItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除类型 "${row.name}" 吗？删除后不可恢复！`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteGoodsType(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 状态切换
const handleStatusChange = async (row: GoodsTypeItem, type: string, value: number) => {
  try {
    await setGoodsTypeStatus(row.id, { type, value })
    ElMessage.success('操作成功')
  } catch {
    // 恢复原状态
    fetchData()
  }
}

// 排序变更
const handleSortChange = async (row: GoodsTypeItem, sortOrder: number) => {
  try {
    await updateGoodsType(row.id, {
      name: row.name,
      value: row.value,
      sortOrder,
      isShow: row.isShow,
      isFenlei: row.isFenlei,
      flName: row.flName,
      cornerText: row.cornerText || undefined,
      payWechat: row.payWechat,
      payBalance: row.payBalance,
      payCurrency: row.payCurrency,
      payCurrency2: row.payCurrency2,
      payCoupon: row.payCoupon,
      isDeduction: row.isDeduction,
      remark: row.remark || undefined
    })
    ElMessage.success('排序更新成功')
  } catch {
    fetchData()
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pay-methods {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.text-muted {
  color: #909399;
}
</style>
