<template>
  <ListPageLayout
    title="产品管理"
    subtitle="管理系统中的所有数据产品"
  >
    <template #actions>
      <el-button
        type="primary"
        :size="isMobile ? 'small' : 'default'"
        @click="handleCreateProduct"
      >
        <span :class="isMobile ? 'hidden sm:inline' : ''">新增产品</span>
        <span :class="isMobile ? 'sm:hidden' : 'hidden'">新增</span>
      </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>
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <el-loading size="large" />
      </div>

      <!-- 移动端卡片布局 -->
      <div v-else-if="isMobile && products.length > 0" class="product-cards">
        <div
          v-for="product in products"
          :key="product.id"
          class="product-card"
        >
          <div class="card-header">
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-1">
                <span class="font-semibold text-base text-blue-600">{{ product.name }}</span>
                <el-tag v-if="product.is_package" type="success" size="small">组合包</el-tag>
              </div>
              <div class="text-xs text-gray-500">编号: {{ product.code }}</div>
            </div>
            <div class="flex flex-col gap-1">
              <el-tag :type="product.is_enabled ? 'success' : 'danger'" size="small">
                {{ product.is_enabled ? '已启用' : '已禁用' }}
              </el-tag>
              <el-tag :type="product.is_visible ? 'success' : 'warning'" size="small">
                {{ product.is_visible ? '已展示' : '已隐藏' }}
              </el-tag>
            </div>
          </div>
          <div class="card-body">
            <div class="card-row">
              <span class="card-label">分类</span>
              <span class="card-value">{{ product.category?.name || '未分类' }}</span>
            </div>
            <div class="card-row">
              <span class="card-label">价格</span>
              <span class="card-value text-red-600 font-semibold">¥{{ formatPrice(product.price) }}</span>
            </div>
            <div class="card-row">
              <span class="card-label">成本价</span>
              <span class="card-value text-gray-600">¥{{ formatPrice(product.cost_price) }}</span>
            </div>
          </div>
          <div class="card-footer">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleEditProduct(product)"
                class="action-btn"
              >
                编辑
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="handleViewProduct(product)"
                class="action-btn"
              >
                查看
              </el-button>
              <el-dropdown @command="(cmd) => handleMobileAction(cmd, product)" trigger="click">
                <el-button type="default" size="small" class="action-btn">
                  更多<el-icon class="ml-1"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="config-doc">配置文档</el-dropdown-item>
                    <el-dropdown-item
                      :command="product.is_enabled ? 'disable' : 'enable'"
                    >
                      {{ product.is_enabled ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 桌面端表格布局 -->
      <div v-else>
        <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>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && products.length === 0" class="text-center py-12">
        <el-empty description="暂无产品数据">
          <el-button type="primary" @click="handleCreateProduct">
            创建第一个产品
          </el-button>
        </el-empty>
      </div>
    </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="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'"
        :small="isMobile"
        @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 { useMobileTable } from '@/composables/useMobileTable'
import { ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 移动端检测
const { isMobile, isTablet } = useMobileTable()

// 响应式数据
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()
}

// 移动端操作处理
const handleMobileAction = (command, product) => {
  switch (command) {
    case 'config-doc':
      handleConfigDocumentation(product)
      break
    case 'enable':
      handleToggleEnabled(product, true)
      break
    case 'disable':
      handleToggleEnabled(product, false)
      break
    case 'delete':
      handleDeleteProduct(product)
      break
  }
}
</script>

<style scoped>
/* 移动端卡片布局 */
.product-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f3f4f6;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

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

.card-label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.card-value {
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
}

.card-footer {
  padding-top: 12px;
  border-top: 1px solid #f3f4f6;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 0;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  /* 表格在移动端优化 */
  :deep(.el-table) {
    font-size: 12px;
    min-width: 800px;
  }

  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 4px;
  }

  :deep(.el-table .cell) {
    padding: 0 4px;
    word-break: break-word;
    line-height: 1.4;
  }

  /* 操作按钮在移动端优化 */
  :deep(.el-table .el-button--small) {
    padding: 4px 8px;
    font-size: 11px;
  }

  /* 分页组件在移动端优化 */
  :deep(.el-pagination) {
    justify-content: center;
  }

  :deep(.el-pagination .el-pagination__sizes) {
    display: none;
  }

  :deep(.el-pagination .el-pagination__total) {
    display: none;
  }

  :deep(.el-pagination .el-pagination__jump) {
    display: none;
  }
}

/* 超小屏幕进一步优化 */
@media (max-width: 480px) {
  .product-card {
    padding: 12px;
  }

  .card-header {
    flex-direction: column;
    gap: 8px;
  }

  .card-body {
    gap: 6px;
  }

  .card-label {
    font-size: 11px;
  }

  .card-value {
    font-size: 13px;
  }

  .action-buttons {
    gap: 6px;
  }

  .action-btn {
    font-size: 12px;
    padding: 6px 8px;
  }
}
</style>
