<template>
  <div class="products-page">
    <div class="page-header">
      <el-button type="primary" @click="openAdd">创建商品</el-button>
    </div>
    <div class="table-card">
      <el-table :data="paginatedProducts" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="图片" width="80">
          <template #default="{ row }">
            <el-image v-if="getFirstImage(row.images)" :src="getFirstImage(row.images)" fit="cover" style="width: 50px; height: 50px; border-radius: 4px;">
              <template #error>
                <div class="table-image-placeholder">-</div>
              </template>
            </el-image>
            <span v-else style="color: rgba(255,255,255,0.3)">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column label="品牌" width="100">
          <template #default="{ row }">
            <span v-if="row.brand">{{ row.brand.name }}</span>
            <span v-else style="color: rgba(255,255,255,0.3)">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">¥{{ row.price }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column label="上架" width="80">
          <template #default="{ row }">
            <el-switch v-model="row.is_active" @change="toggleActive(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editProd(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteProd(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <el-dialog v-model="showAdd" :title="editing ? '编辑商品' : '创建商品'" width="800px" top="5vh">
      <el-form :model="form" label-width="90px" class="product-form">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-form-item label="商品名称" required>
            <el-input v-model="form.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              v-model:file-list="fileList"
              action=""
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              accept="image/*"
              multiple
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">支持 jpg、png、gif、webp 格式</div>
          </el-form-item>
        </div>
        
        <div class="form-section">
          <div class="section-title">价格库存</div>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="价格" required>
                <el-input-number v-model="form.price" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库存">
                <el-input-number v-model="form.stock" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上架">
                <el-switch v-model="form.is_active" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="最低购买">
                <el-input-number v-model="form.min_purchase" :min="1" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大购买">
                <el-input-number v-model="form.max_purchase" :min="0" style="width: 100%" placeholder="0表示不限" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <div class="form-section">
          <div class="section-title">分类品牌</div>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="所属分类">
                <el-select v-model="form.category_ids" multiple placeholder="选择分类" popper-class="dark-select-dropdown" style="width: 100%">
                  <el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属品牌">
                <el-select v-model="form.brand_id" placeholder="选择品牌" clearable popper-class="dark-select-dropdown" style="width: 100%">
                  <el-option v-for="b in brands" :key="b.id" :label="b.name" :value="b.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <div class="form-section">
          <div class="section-title">资格设置</div>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="需要资格">
                <el-switch v-model="form.require_credit" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资格消耗">
                <el-input-number v-model="form.credit_cost" :min="0" style="width: 100%" :disabled="!form.require_credit" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资格奖励">
                <el-input-number v-model="form.credit_reward" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveProd" :loading="saving">保存</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 type { UploadFile, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { adminApi, categoryApi, brandApi, uploadApi } from '../../api'
import { getImageUrl } from '../../utils/image'

const products = ref<any[]>([])
const categories = ref<any[]>([])
const brands = ref<any[]>([])
const loading = ref(false)
const saving = ref(false)
const showAdd = ref(false)
const editing = ref<any>(null)
const fileList = ref<UploadUserFile[]>([])
const uploadedUrls = ref<string[]>([])
const page = ref(1)
const pageSize = 20
const total = computed(() => products.value.length)
const paginatedProducts = computed(() => {
  const start = (page.value - 1) * pageSize
  return products.value.slice(start, start + pageSize)
})

function handlePageChange() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const form = reactive({
  name: '',
  description: '',
  price: 0,
  stock: 0,
  min_purchase: 1,
  max_purchase: undefined as number | undefined,
  require_credit: false,
  credit_cost: 0,
  credit_reward: 0,
  is_active: true,
  category_ids: [] as number[],
  brand_id: undefined as number | undefined
})

function getFirstImage(images: string) {
  if (!images) return ''
  const arr = images.split(',').map(s => s.trim()).filter(Boolean)
  return getImageUrl(arr[0] || '')
}

function handleFileChange(file: UploadFile) {
  if (file.status === 'ready') {
    file.status = 'ready'
  }
}

function handleFileRemove(file: UploadFile) {
  const index = fileList.value.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
  const urlIndex = uploadedUrls.value.findIndex(u => u === file.url || getImageUrl(u) === file.url)
  if (urlIndex > -1) {
    uploadedUrls.value.splice(urlIndex, 1)
  }
}

async function uploadFiles(): Promise<string[]> {
  const urls: string[] = [...uploadedUrls.value]
  const filesToUpload = fileList.value.filter(f => f.raw && f.status === 'ready')
  
  for (const file of filesToUpload) {
    try {
      const res: any = await uploadApi.uploadImage(file.raw as File)
      if (res.url) {
        urls.push(res.url)
        file.url = getImageUrl(res.url)
        file.status = 'success'
      }
    } catch (e) {
      console.error('Upload failed:', e)
      file.status = 'fail'
    }
  }
  return urls
}

async function fetchProducts() {
  loading.value = true
  try {
    const res: any = await adminApi.getProducts()
    products.value = res.data || []
  } finally {
    loading.value = false
  }
}

async function fetchCategories() {
  const res: any = await categoryApi.list()
  categories.value = res.data || []
}

async function fetchBrands() {
  const res: any = await brandApi.list()
  brands.value = res.data || []
}

function openAdd() {
  editing.value = null
  Object.assign(form, { 
    name: '', description: '', price: 0, stock: 0, 
    min_purchase: 1, max_purchase: undefined, 
    require_credit: false, credit_cost: 0, credit_reward: 0, 
    is_active: true, category_ids: [], brand_id: undefined 
  })
  fileList.value = []
  uploadedUrls.value = []
  showAdd.value = true
}

function editProd(row: any) {
  editing.value = row
  Object.assign(form, {
    name: row.name,
    description: row.description || '',
    price: row.price,
    stock: row.stock || 0,
    min_purchase: row.min_purchase || 1,
    max_purchase: row.max_purchase,
    require_credit: row.require_credit,
    credit_cost: row.credit_cost || 0,
    credit_reward: row.credit_reward || 0,
    is_active: row.is_active !== false,
    category_ids: (row.categories || []).map((c: any) => c.id),
    brand_id: row.brand_id
  })
  const images = row.images ? row.images.split(',').map((s: string) => s.trim()).filter(Boolean) : []
  uploadedUrls.value = images
  fileList.value = images.map((url: string, index: number) => ({
    name: `image-${index}`,
    url: getImageUrl(url),
    status: 'success' as const,
    uid: Date.now() + index
  }))
  showAdd.value = true
}

async function saveProd() {
  if (!form.name) {
    ElMessage.warning('请输入商品名称')
    return
  }
  saving.value = true
  try {
    const urls = await uploadFiles()
    const submitData = { ...form, images: urls.join(',') }
    if (editing.value) {
      await adminApi.updateProduct(editing.value.id, submitData)
    } else {
      await adminApi.createProduct(submitData)
    }
    ElMessage.success('保存成功')
    showAdd.value = false
    editing.value = null
    await fetchProducts()
  } catch (e) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

async function toggleActive(row: any) {
  await adminApi.updateProduct(row.id, { is_active: row.is_active })
  ElMessage.success(row.is_active ? '已上架' : '已下架')
}

async function deleteProd(id: number) {
  await ElMessageBox.confirm('确定删除此商品？', '确认删除')
  await adminApi.deleteProduct(id)
  ElMessage.success('删除成功')
  await fetchProducts()
}

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

<style scoped lang="scss">
.products-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }
.table-image-placeholder { width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.04); border-radius: 4px; color: rgba(255,255,255,0.3); }
.upload-tip { font-size: 12px; color: rgba(255,255,255,0.4); margin-top: 8px; }

.pagination-wrap {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination-wrap :deep(.el-pagination) {
  --el-pagination-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-text-color: rgba(255, 255, 255, 0.6);
  --el-pagination-button-disabled-bg-color: rgba(255, 255, 255, 0.04);
  --el-pagination-button-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-hover-color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination .el-pager li) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
  margin: 0 4px;
}

.pagination-wrap :deep(.el-pagination .el-pager li:hover),
.pagination-wrap :deep(.el-pagination .el-pager li.is-active) {
  background: #4e6ef2;
  color: #fff;
}

.product-form {
  padding-right: 10px;
}

.form-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  
  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #4e6ef2;
  margin-bottom: 16px;
  padding-left: 10px;
  border-left: 3px solid #4e6ef2;
}

:deep(.el-upload--picture-card) {
  background: rgba(255, 255, 255, 0.06);
  border: 1px dashed rgba(255, 255, 255, 0.15);
  border-radius: 8px;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.5);
}

:deep(.el-upload--picture-card:hover) {
  border-color: #4e6ef2;
  color: #4e6ef2;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.el-dialog__body) {
  padding: 20px 24px;
  max-height: 65vh;
  overflow-y: auto;
  overflow-x: hidden;
}

:deep(.el-dialog) {
  background: #2d2d44;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  padding: 16px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.5);
  
  &:hover {
    color: #fff;
  }
}

:deep(.el-dialog__footer) {
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  padding: 16px 20px;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: none;
  
  &:hover, &:focus {
    border-color: #4e6ef2;
  }
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  color: #fff;
  
  &::placeholder {
    color: rgba(255, 255, 255, 0.3);
  }
}

:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.06);
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.08);
}
</style>
