<template>
  <div class="points-product-container">
    <h2 class="page-title">积分商品管理</h2>
    
    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button type="primary" icon="Plus" @click="showCreateDialog">新增商品</el-button>
          <el-button icon="Refresh" @click="loadList">刷新</el-button>
        </el-col>
        <el-col :span="12">
          <el-space wrap style="float: right">
            <el-select v-model="filters.category" placeholder="商品类型" clearable style="width: 120px" @change="loadList">
              <el-option label="全部" :value="undefined" />
              <el-option label="实物" :value="1" />
              <el-option label="虚拟" :value="2" />
            </el-select>
            
            <el-select v-model="filters.status" placeholder="状态" clearable style="width: 120px" @change="loadList">
              <el-option label="全部" :value="undefined" />
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
            
            <el-input v-model="filters.keyword" placeholder="搜索商品名称" clearable style="width: 200px" @keyup.enter="loadList">
              <template #append>
                <el-button icon="Search" @click="loadList" />
              </template>
            </el-input>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 商品列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="list"
        stripe
        style="width: 100%"
      >
        <template #empty>
          <el-empty description="暂无商品数据" />
        </template>
        
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column label="商品图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 6px; cursor: pointer;"
              :preview-src-list="[row.imageUrl]"
              preview-teleported
              hide-on-click-modal
            />
            <span v-else style="color: #999;">暂无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="description" label="商品描述" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="pointsPrice" label="积分价格" width="100" align="center">
          <template #default="{ row }">
            <span style="color: #E91E63; font-weight: bold;">{{ row.pointsPrice }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="stock" label="库存" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.stock > 0 ? 'success' : 'danger'" size="small">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.category === 1 ? 'primary' : 'warning'" size="small">
              {{ row.category === 1 ? '实物' : '虚拟' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="isRecommend" label="推荐" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isRecommend === 1" type="danger" size="small">推荐</el-tag>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" 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 prop="sortOrder" label="排序" width="80" align="center" />
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="info"
                size="small"
                link
                @click="handleViewDetail(row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button type="primary" size="small" link @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                v-if="row.status === 0"
                type="success"
                size="small"
                link
                @click="handleOnShelf(row)"
              >
                <el-icon><Top /></el-icon>
                上架
              </el-button>
              <el-button
                v-if="row.status === 1"
                type="warning"
                size="small"
                link
                @click="handleOffShelf(row)"
              >
                <el-icon><Bottom /></el-icon>
                下架
              </el-button>
              <el-button type="danger" size="small" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="list.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>
    
    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商品' : '新增商品'"
      width="700px"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :http-request="handleUpload"
          >
            <el-image
              v-if="form.imageUrl"
              :src="form.imageUrl"
              class="uploaded-image"
              fit="cover"
            />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 JPG、PNG 格式，大小不超过 10MB</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="积分价格" prop="pointsPrice">
              <el-input-number v-model="form.pointsPrice" :min="1" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="form.stock" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品类型" prop="category">
              <el-select v-model="form.category" placeholder="请选择商品类型" style="width: 100%">
                <el-option label="实物" :value="1" />
                <el-option label="虚拟" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="isRecommend">
              <el-switch v-model="form.isRecommend" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="上架" inactive-text="下架" />
            </el-form-item>
          </el-col>
        </el-row>
      </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-dialog
      v-model="detailDialogVisible"
      title="商品详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="detailData" class="detail-content">
        <!-- 基本信息 -->
        <el-card shadow="never" class="detail-section">
          <template #header>
            <div class="section-header">
              <el-icon><InfoFilled /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品ID">
              {{ detailData.id || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="商品名称">
              {{ detailData.name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="商品描述" :span="2">
              <div class="description-content">
                {{ detailData.description || '-' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="商品图片" :span="2">
              <el-image
                v-if="detailData.imageUrl"
                :src="detailData.imageUrl"
                fit="cover"
                style="width: 200px; height: 200px; border-radius: 6px;"
                :preview-src-list="[detailData.imageUrl]"
                preview-teleported
                hide-on-click-modal
              />
              <span v-else style="color: #999;">暂无图片</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 价格与库存 -->
        <el-card shadow="never" class="detail-section">
          <template #header>
            <div class="section-header">
              <el-icon><Money /></el-icon>
              <span>价格与库存</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="积分价格">
              <span style="color: #E91E63; font-weight: bold; font-size: 16px;">
                {{ detailData.pointsPrice || 0 }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="库存">
              <el-tag :type="detailData.stock > 0 ? 'success' : 'danger'" size="small">
                {{ detailData.stock || 0 }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 商品属性 -->
        <el-card shadow="never" class="detail-section">
          <template #header>
            <div class="section-header">
              <el-icon><Setting /></el-icon>
              <span>商品属性</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品类型">
              <el-tag :type="detailData.category === 1 ? 'primary' : 'warning'" size="small">
                {{ detailData.category === 1 ? '实物' : '虚拟' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否推荐">
              <el-tag v-if="detailData.isRecommend === 1" type="danger" size="small">推荐</el-tag>
              <span v-else style="color: #999;">否</span>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailData.status === 1 ? 'success' : 'info'" size="small">
                {{ detailData.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="排序">
              {{ detailData.sortOrder || 0 }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, InfoFilled, Money, Setting, View, Top, Bottom } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])
const detailDialogVisible = ref(false)
const detailData = ref(null)

const filters = reactive({
  status: null,
  category: null,
  keyword: ''
})

const form = reactive({
  id: null,
  name: '',
  description: '',
  imageUrl: '',
  pointsPrice: 0,
  stock: 0,
  category: 1,
  isRecommend: 0,
  status: 0,
  sortOrder: 0
})

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

const loadList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    if (filters.status !== null && filters.status !== undefined) params.status = filters.status
    if (filters.category !== null && filters.category !== undefined) params.category = filters.category
    if (filters.keyword) params.keyword = filters.keyword
    
    const response = await request.get('/admin/points-product/list', { params })
    
    if (response.code === 200) {
      list.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description || '',
    imageUrl: row.imageUrl || '',
    pointsPrice: row.pointsPrice,
    stock: row.stock || 0,
    category: row.category,
    isRecommend: row.isRecommend || 0,
    status: row.status,
    sortOrder: row.sortOrder || 0
  })
  dialogVisible.value = true
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = null
  form.name = ''
  form.description = ''
  form.imageUrl = ''
  form.pointsPrice = 0
  form.stock = 0
  form.category = 1
  form.isRecommend = 0
  form.status = 0
  form.sortOrder = 0
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const url = isEdit.value ? '/admin/points-product/update' : '/admin/points-product/create'
    const method = isEdit.value ? 'put' : 'post'
    
    const response = await request[method](url, form)
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadList()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleOnShelf = async (row) => {
  try {
    const response = await request.put(`/admin/points-product/on-shelf/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('上架成功')
      loadList()
    } else {
      ElMessage.error(response.msg || '上架失败')
    }
  } catch (error) {
    console.error('上架失败:', error)
    ElMessage.error('上架失败')
  }
}

const handleOffShelf = async (row) => {
  try {
    const response = await request.put(`/admin/points-product/off-shelf/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('下架成功')
      loadList()
    } else {
      ElMessage.error(response.msg || '下架失败')
    }
  } catch (error) {
    console.error('下架失败:', error)
    ElMessage.error('下架失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`/admin/points-product/delete/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 图片上传相关
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传图片
const handleUpload = async (options) => {
  const formData = new FormData()
  formData.append('file', options.file)
  
  try {
    const response = await request.post(API_ENDPOINTS.UPLOAD_IMAGE, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    if (response.code === 200) {
      // 处理不同的返回格式
      let imageUrl = ''
      if (typeof response.data === 'string') {
        imageUrl = response.data
      } else if (response.data && response.data.url) {
        imageUrl = response.data.url
      } else if (response.data && response.data.path) {
        imageUrl = response.data.path
      } else {
        imageUrl = String(response.data || '')
      }
      
      form.imageUrl = imageUrl
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    console.error('上传异常:', error)
    ElMessage.error('图片上传失败，请重试')
  }
}

onMounted(() => loadList())
</script>

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

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

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

/* 图片上传样式 */
.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  :deep(.el-upload:hover) {
    border-color: #409eff;
  }
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 150px;
  height: 150px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 详情对话框样式 */
.detail-content {
  padding: 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.section-header .el-icon {
  font-size: 18px;
  color: #409eff;
}

.description-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #666;
}
</style>

