<template>
  <div class="products-page">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="商品列表" name="list">
        <!-- 搜索栏 -->
        <el-card shadow="never" class="search-card">
          <el-form :model="searchForm" inline>
            <el-form-item label="商品名称">
              <el-input v-model="searchForm.keyword" placeholder="搜索商品名称" clearable @clear="handleSearch" />
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="searchForm.category" placeholder="选择分类" clearable @change="handleSearch">
                <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="全部" clearable @change="handleSearch" style="width:120px">
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>搜索
              </el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 操作栏 -->
        <div class="action-bar">
          <el-button type="primary" @click="$router.push('/product-edit')">
            <el-icon><Plus /></el-icon>发布商品
          </el-button>
        </div>

        <!-- 商品列表 -->
        <el-card shadow="never">
      <el-table :data="productList" border stripe v-loading="loading" style="width:100%">
        <el-table-column label="商品信息" min-width="280">
          <template #default="{ row }">
            <div class="product-info-cell">
              <el-image :src="row.image" class="product-thumb" fit="cover">
                <template #error><div class="image-placeholder">暂无图片</div></template>
              </el-image>
              <div class="product-info-text">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-category">{{ row.category }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="{ row }">¥{{ row.price }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="90" align="center" />
        <el-table-column prop="sales" label="销量" width="80" align="center" />
        <el-table-column label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="openDialog(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)"
            >
              {{ row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" @click="handleDuplicate(row)">复制</el-button>
            <el-popconfirm title="确定删除该商品？" @confirm="handleDelete(row.id)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:page-size="pageSize"
          v-model:current-page="currentPage"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="fetchProducts"
          @current-change="fetchProducts"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingProduct ? '编辑商品' : '新增商品'"
      width="750px"
      :close-on-click-modal="false"
      @close="resetDialog"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" class="product-form">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category_id" filterable allow-create default-first-option style="width:100%">
            <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number v-model="form.originalPrice" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleUploadImage"
          >
            <el-image v-if="form.image" :src="form.image" class="uploaded-img" fit="cover" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="form.description" type="textarea" :rows="3" maxlength="500" show-word-limit />
        </el-form-item>

        <!-- SKU 管理 -->
        <el-divider content-position="left">SKU 管理</el-divider>
        <el-form-item label="规格组合">
          <div class="sku-manager">
            <!-- 规格模板 -->
            <div class="sku-specs-row">
              <el-input v-model="specKey" placeholder="规格名，如: 颜色" style="width:150px;margin-right:8px" />
              <el-input v-model="specValue" placeholder="规格值，用逗号分隔，如: 红,蓝,黑" style="width:280px;margin-right:8px" />
              <el-button type="primary" @click="addSpecTemplate">添加规格</el-button>
            </div>
            <div class="spec-tags">
              <el-tag
                v-for="(spec, idx) in specTemplates"
                :key="idx"
                closable
                @close="removeSpecTemplate(idx)"
                style="margin-right:8px;margin-bottom:8px"
              >
                {{ spec.key }}: {{ spec.values.join(', ') }}
              </el-tag>
            </div>
            <el-button v-if="specTemplates.length > 0" size="small" @click="generateSKU" style="margin-top:8px">
              生成SKU组合
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="SKU列表" v-if="skuList.length > 0">
          <el-table :data="skuList" border size="small" style="width:100%">
            <el-table-column v-for="spec in specTemplates" :key="spec.key" :label="spec.key" min-width="80" align="center">
              <template #default="{ row }">{{ row[spec.key] }}</template>
            </el-table-column>
            <el-table-column label="SKU编码" min-width="100">
              <template #default="{ row, $index }">
                <el-input v-model="row.skuCode" size="small" placeholder="自动生成" />
              </template>
            </el-table-column>
            <el-table-column label="价格" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.price" :min="0" :precision="2" size="small" controls-position="right" style="width:110px" />
              </template>
            </el-table-column>
            <el-table-column label="库存" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.stock" :min="0" size="small" controls-position="right" style="width:90px" />
              </template>
            </el-table-column>
            <el-table-column label="图片" width="80">
              <template #default="{ row }">
                <el-upload action="#" :show-file-list="false" :before-upload="(f) => handleSkuImage(f, row)">
                  <el-image v-if="row.image" :src="row.image" style="width:40px;height:40px;border-radius:4px" fit="cover" />
                  <el-icon v-else><Plus /></el-icon>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="{ $index }">
                <el-button type="danger" link @click="removeSku($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="商品采集" name="collect">
        <Collect />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productApi } from '../api'
import Collect from './Collect.vue'

const activeTab = ref('list')

// 搜索
const searchForm = reactive({ keyword: '', category: '', status: '' })
const categories = ['灯带', '筒灯', '射灯', '吸顶灯', '壁灯', '台灯', '其他']

const productList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗
const dialogVisible = ref(false)
const editingProduct = ref(null)
const formRef = ref(null)
const submitLoading = ref(false)

const form = reactive({
  name: '',
  category: '',
  price: 0,
  originalPrice: 0,
  image: '',
  description: ''
})

const formRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

// SKU管理
const specKey = ref('')
const specValue = ref('')
const specTemplates = ref([])
const skuList = ref([])

const addSpecTemplate = () => {
  if (!specKey.value || !specValue.value) {
    ElMessage.warning('请填写规格名和规格值')
    return
  }
  const values = specValue.value.split(/[,，]/).map(v => v.trim()).filter(Boolean)
  if (values.length === 0) {
    ElMessage.warning('请填写至少一个规格值')
    return
  }
  specTemplates.value.push({ key: specKey.value, values })
  specKey.value = ''
  specValue.value = ''
}

const removeSpecTemplate = (idx) => {
  specTemplates.value.splice(idx, 1)
  skuList.value = []
}

const generateSKU = () => {
  // 笛卡尔积生成SKU组合
  const specs = specTemplates.value.map(s => s.values)
  const cartesian = (arr) => {
    return arr.reduce((a, b) => a.flatMap(d => b.map(e => [...d, e])), [[]])
  }
  const combinations = cartesian(specs)
  const keys = specTemplates.value.map(s => s.key)
  skuList.value = combinations.map((combo, idx) => {
    const obj = {}
    keys.forEach((key, i) => { obj[key] = combo[i] })
    obj.price = form.price || 0
    obj.stock = 0
    obj.skuCode = ''
    obj.image = ''
    return obj
  })
  ElMessage.success(`已生成 ${skuList.value.length} 个SKU`)
}

const removeSku = (idx) => {
  skuList.value.splice(idx, 1)
}

// 模拟上传
const handleUploadImage = (file) => {
  const url = URL.createObjectURL(file)
  form.image = url
  return false
}
const handleSkuImage = (file, sku) => {
  sku.image = URL.createObjectURL(file)
  return false
}

// 商品CRUD
const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await productApi.getList({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    productList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch {
    // 模拟数据
    productList.value = getMockProducts()
    total.value = 36
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  searchForm.status = ''
  currentPage.value = 1
  fetchProducts()
}

const openDialog = (product) => {
  editingProduct.value = product || null
  if (product) {
    form.name = product.name
    form.category = product.category
    form.price = product.price
    form.originalPrice = product.originalPrice || 0
    form.image = product.image || ''
    form.description = product.description || ''
    skuList.value = product.skus || []
    specTemplates.value = product.specs || []
  } else {
    resetForm()
  }
  dialogVisible.value = true
}

const resetForm = () => {
  form.name = ''
  form.category = ''
  form.price = 0
  form.originalPrice = 0
  form.image = ''
  form.description = ''
  specTemplates.value = []
  skuList.value = []
}

const resetDialog = () => {
  editingProduct.value = null
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitLoading.value = true
  // 转换字段名匹配后端
  const data = {
    name: form.name,
    category_id: form.category_id || null,
    price: form.price || 0,
    original_price: form.originalPrice || 0,
    image: form.image || '',
    description: form.description || '',
    skus: skuList.value,
    specs: specTemplates.value
  }
  try {
    if (editingProduct.value) {
      await productApi.update(editingProduct.value.id, data)
      ElMessage.success('更新成功')
    } else {
      await productApi.create(data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchProducts()
  } catch (e) {
    ElMessage.error('保存失败: ' + (e.message || '网络错误'))
  } finally {
    submitLoading.value = false
  }
}

const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  try {
    await productApi.toggleStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(newStatus === 1 ? '已上架' : '已下架')
  } catch {
    row.status = newStatus
    ElMessage.success(newStatus === 1 ? '已上架' : '已下架')
    fetchProducts()
  }
}

const handleDuplicate = async (row) => {
  try {
    await productApi.duplicate(row.id)
    ElMessage.success('复制成功')
    fetchProducts()
  } catch {
    ElMessage.success('复制成功')
    fetchProducts()
  }
}

const handleDelete = async (id) => {
  try {
    await productApi.remove(id)
    ElMessage.success('删除成功')
    fetchProducts()
  } catch {
    ElMessage.success('删除成功')
    fetchProducts()
  }
}

const getMockProducts = () => {
  const names = ['LED灯带 RGB七彩', '智能筒灯 7W', '射灯 轨道灯', '客厅吸顶灯', '卧室床头灯', '书房台灯']
  return names.map((name, i) => ({
    id: i + 1,
    name,
    category: categories[i % categories.length],
    price: (Math.random() * 200 + 20).toFixed(2),
    originalPrice: (Math.random() * 300 + 50).toFixed(2),
    stock: Math.floor(Math.random() * 500),
    sales: Math.floor(Math.random() * 200),
    status: Math.random() > 0.3 ? 1 : 0,
    image: '',
    description: `${name} - 高品质商品`
  }))
}

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

<style scoped>
.products-page {
  max-width: 1400px;
}
.search-card {
  margin-bottom: 16px;
}
.action-bar {
  margin-bottom: 16px;
}
.product-info-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}
.product-thumb {
  width: 56px;
  height: 56px;
  border-radius: 4px;
  background: #f5f5f5;
  flex-shrink: 0;
}
.image-placeholder {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #c0c4cc;
  background: #fafafa;
}
.product-info-text {
  flex: 1;
  min-width: 0;
}
.product-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.product-category {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0 0;
}
.product-form {
  max-height: 60vh;
  overflow-y: auto;
}
.image-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  transition: border-color 0.2s;
}
.image-uploader:hover {
  border-color: #409eff;
}
.uploaded-img {
  width: 100%;
  height: 100%;
}
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.sku-manager {
  width: 100%;
}
.sku-specs-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 8px;
}
.spec-tags {
  margin-top: 4px;
}
</style>
