<template>
  <ListPageLayout
    title="产品管理"
    subtitle="管理系统中的所有数据产品"
  >
    <template #actions>
      <el-button type="primary" @click="handleCreateProduct">
        新增产品
      </el-button>
    </template>

    <template #filters>
      <FilterSection>
        <FilterItem label="产品分类">
          <el-select
            v-model="filters.category_id"
            placeholder="选择分类"
            clearable
            @change="handleFilterChange"
            class="w-full"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </FilterItem>

        <FilterItem label="启用状态">
          <el-select
            v-model="filters.is_enabled"
            placeholder="选择状态"
            clearable
            @change="handleFilterChange"
            class="w-full"
          >
            <el-option label="已启用" :value="true" />
            <el-option label="已禁用" :value="false" />
          </el-select>
        </FilterItem>

        <FilterItem label="产品类型">
          <el-select
            v-model="filters.is_package"
            placeholder="选择类型"
            clearable
            @change="handleFilterChange"
            class="w-full"
          >
            <el-option label="单品" :value="false" />
            <el-option label="组合包" :value="true" />
          </el-select>
        </FilterItem>

        <FilterItem label="搜索产品">
          <el-input
            v-model="filters.keyword"
            placeholder="输入产品名称或编号"
            clearable
            @input="handleSearch"
            class="w-full"
          />
        </FilterItem>

        <template #stats>
          共找到 {{ total }} 个产品
        </template>

        <template #buttons>
          <el-button @click="resetFilters">重置筛选</el-button>
          <el-button type="primary" @click="loadProducts">应用筛选</el-button>
        </template>
      </FilterSection>
    </template>

    <template #table>
      <el-table
        v-loading="loading"
        :data="products"
        stripe
        class="w-full"
      >
        <el-table-column prop="code" label="产品编号" width="120" />
        <el-table-column prop="name" label="产品名称" min-width="150">
          <template #default="{ row }">
            <div class="flex items-center">
              <span class="font-medium text-blue-600">{{ row.name }}</span>
              <el-tag v-if="row.is_package" type="success" size="small" class="ml-2">组合包</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="category.name" label="分类" width="120">
          <template #default="{ row }">
            {{ row.category?.name || '未分类' }}
          </template>
        </el-table-column>

        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span class="text-red-600 font-semibold">¥{{ formatPrice(row.price) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="cost_price" label="成本价" width="120">
          <template #default="{ row }">
            <span class="text-gray-600">¥{{ formatPrice(row.cost_price) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="is_enabled" label="启用状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.is_enabled ? 'success' : 'danger'" size="small">
              {{ row.is_enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="is_visible" label="展示状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.is_visible ? 'success' : 'warning'" size="small">
              {{ row.is_visible ? '已展示' : '已隐藏' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="350" fixed="right">
          <template #default="{ row }">
            <div class="flex gap-2">
              <el-button
                type="primary"
                size="small"
                @click="handleEditProduct(row)"
              >
                编辑
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="handleViewProduct(row)"
              >
                查看
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleConfigDocumentation(row)"
              >
                配置文档
              </el-button>
              <el-button
                v-if="row.is_enabled"
                type="warning"
                size="small"
                @click="handleToggleEnabled(row, false)"
              >
                禁用
              </el-button>
              <el-button
                v-else
                type="success"
                size="small"
                @click="handleToggleEnabled(row, true)"
              >
                启用
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteProduct(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #pagination>
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </template>

    <template #extra>
      <!-- 产品表单弹窗 -->
      <ProductFormDialog
        v-model="dialogs.form.visible"
        :product="dialogs.form.product"
        :categories="categories"
        @success="handleFormSuccess"
      />

      <!-- API配置弹窗 -->
      <ProductApiConfigDialog
        v-model="dialogs.apiConfig.visible"
        :product="dialogs.apiConfig.product"
        @success="handleApiConfigSuccess"
      />

      <!-- 文档配置弹窗 -->
      <ProductDocumentationDialog
        v-model="dialogs.documentation.visible"
        :product="dialogs.documentation.product"
        @success="handleDocumentationSuccess"
      />
    </template>
  </ListPageLayout>
</template>

<script setup>
import { categoryApi, productAdminApi } from '@/api'
import ProductApiConfigDialog from '@/components/admin/ProductApiConfigDialog.vue'
import ProductDocumentationDialog from '@/components/admin/ProductDocumentationDialog.vue'
import ProductFormDialog from '@/components/admin/ProductFormDialog.vue'
import FilterItem from '@/components/common/FilterItem.vue'
import FilterSection from '@/components/common/FilterSection.vue'
import ListPageLayout from '@/components/common/ListPageLayout.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const products = ref([])
const categories = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 弹窗状态管理
const dialogs = reactive({
  form: {
    visible: false,
    product: null
  },
  apiConfig: {
    visible: false,
    product: null
  },
  documentation: {
    visible: false,
    product: null
  }
})

// 筛选条件
const filters = reactive({
  category_id: null,
  is_enabled: null,
  is_package: null,
  keyword: ''
})

// 搜索防抖
let searchTimer = null

// 初始化
onMounted(() => {
  loadCategories()
  loadProducts()
})

// 加载产品分类
const loadCategories = async () => {
  try {
    const response = await categoryApi.getCategories({ page: 1, page_size: 100 })
    categories.value = response.data?.items || []
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载产品列表
const loadProducts = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      ...filters
    }

    const response = await productAdminApi.getProducts(params)
    products.value = response.data?.items || []
    total.value = response.data?.total || 0
  } catch (error) {
    console.error('加载产品失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
  loadProducts()
}

// 处理搜索
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    loadProducts()
  }, 500)
}

// 重置筛选
const resetFilters = () => {
  filters.category_id = null
  filters.is_enabled = null
  filters.is_package = null
  filters.keyword = ''
  currentPage.value = 1
  loadProducts()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadProducts()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadProducts()
}

// 弹窗管理方法
const openDialog = (dialogType, product = null) => {
  // 先关闭所有弹窗
  Object.keys(dialogs).forEach(key => {
    dialogs[key].visible = false
    dialogs[key].product = null
  })

  // 打开指定弹窗
  dialogs[dialogType].visible = true
  dialogs[dialogType].product = product
}

const closeDialog = (dialogType) => {
  dialogs[dialogType].visible = false
  dialogs[dialogType].product = null
}

// 新增产品
const handleCreateProduct = () => {
  openDialog('form')
}

// 编辑产品
const handleEditProduct = (product) => {
  openDialog('form', product)
}

// 查看产品
const handleViewProduct = (product) => {
  router.push(`/products/${product.id}`)
}

// 切换产品启用状态
const handleToggleEnabled = async (product, enabled) => {
  try {
    const action = enabled ? '启用' : '禁用'
    await ElMessageBox.confirm(
      `确定要${action}产品"${product.name}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: `确定${action}`,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 更新产品状态
    await productAdminApi.updateProduct(product.id, {
      ...product,
      is_enabled: enabled
    })

    ElMessage.success(`产品已${action}`)
    await loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换状态失败:', error)
      ElMessage.error('切换状态失败')
    }
  }
}

// 删除产品
const handleDeleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品"${product.name}"吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await productAdminApi.deleteProduct(product.id)
    ElMessage.success('产品删除成功')
    await loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除产品失败:', error)
    }
  }
}

// 配置API
const handleConfigApi = (product) => {
  openDialog('apiConfig', product)
}

// API配置成功
const handleApiConfigSuccess = () => {
  closeDialog('apiConfig')
  ElMessage.success('API配置操作成功')
}

// 配置文档
const handleConfigDocumentation = (product) => {
  openDialog('documentation', product)
}

// 文档配置成功
const handleDocumentationSuccess = () => {
  closeDialog('documentation')
}

// 表单提交成功
const handleFormSuccess = () => {
  closeDialog('form')
  loadProducts()
}
</script>

<style scoped>
/* 页面特定样式可以在这里添加 */
</style>
