<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>产品管理</h1>
      <a-space>
        <a-button @click="exportProducts" :loading="exportLoading">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          添加产品
        </a-button>
      </a-space>
    </div>
    
    <!-- 搜索区域 -->
    <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
      <a-auto-complete
        v-model:value="searchProductName"
        :options="productNameOptions"
        placeholder="请选择或输入产品名称进行搜索"
        style="width: 300px;"
        :filter-option="false"
        @search="handleSearchInput"
        @press-enter="searchProducts"
      />
      <a-button type="primary" @click="searchProducts" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="products" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'price'">
          ¥{{ record.price }}
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <a-tag :color="record.status === 'active' ? 'green' : 'red'">
            {{ record.status === 'active' ? '活跃' : '停用' }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editProduct(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个产品吗？"
            @confirm="deleteProduct(record.id)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑产品模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑产品' : '添加产品'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="产品名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入产品名称" />
        </a-form-item>
        <a-form-item label="产品描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请输入产品描述" :rows="3" />
        </a-form-item>
        <a-form-item label="价格" name="price">
          <a-input-number 
            v-model:value="formData.price" 
            placeholder="请输入价格" 
            :min="0" 
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="库存" name="stock">
          <a-input-number 
            v-model:value="formData.stock" 
            placeholder="请输入库存数量" 
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model="formData.status" placeholder="请选择状态">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">停用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
import { api } from '../utils/api'
import { ExportUtils } from '../utils/exportUtils'

// 响应式数据
const products = ref([])
const loading = ref(false)
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索相关的响应式数据
const searchProductName = ref('')
const searchLoading = ref(false)
const isSearching = ref(false)
const productNameOptions = ref([])

// 导出相关
const exportLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  description: '',
  price: null,
  stock: null,
  status: 'active'
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '产品名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 120
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 获取产品列表
const fetchProducts = async () => {
  try {
    loading.value = true
    const response = await api.get('/products')
    if (response.success) {
      products.value = response.data
    } else {
      message.error('获取产品列表失败')
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    message.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加模态框
const showAddModal = () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

// 编辑产品
const editProduct = (record) => {
  isEdit.value = true
  Object.assign(formData, record)
  modalVisible.value = true
}

// 删除产品
const deleteProduct = async (id) => {
  try {
    const response = await api.delete(`/products/${id}`)
    if (response.success) {
      message.success('删除成功')
      fetchProducts()
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    console.error('删除产品失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let response
    if (isEdit.value) {
      response = await api.put(`/products/${formData.id}`, formData)
    } else {
      response = await api.post('/products', formData)
    }
    
    if (response.success) {
      message.success(isEdit.value ? '更新成功' : '创建成功')
      modalVisible.value = false
      fetchProducts()
    } else {
      message.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    description: '',
    price: null,
    stock: null,
    status: 'active'
  })
  formRef.value?.resetFields()
}

// 搜索产品
const searchProducts = async () => {
  if (!searchProductName.value.trim()) {
    message.warning('请输入产品名称进行搜索')
    return
  }
  
  try {
    searchLoading.value = true
    const response = await api.get('/products/search', {
      params: { name: searchProductName.value.trim() }
    })
    
    if (response.success) {
      products.value = response.data || []
      isSearching.value = true
      message.success(response.message || `找到 ${products.value.length} 个匹配的产品`)
    } else {
      products.value = []
      message.info('未找到匹配的产品')
    }
  } catch (error) {
    console.error('搜索产品失败:', error)
    message.error('搜索产品失败')
    products.value = []
  } finally {
    searchLoading.value = false
  }
}

// 处理搜索输入（为自动完成提供选项）
const handleSearchInput = (value) => {
  if (!value) {
    productNameOptions.value = []
    return
  }
  
  // 从现有产品列表中筛选匹配的产品名称
  const matchingProducts = products.value.filter(product => 
    product.name.toLowerCase().includes(value.toLowerCase())
  )
  
  productNameOptions.value = matchingProducts.map(product => ({
    value: product.name,
    label: product.name
  }))
}

// 更新产品名称选项（在数据加载后）
const updateProductNameOptions = () => {
  productNameOptions.value = products.value.map(product => ({
    value: product.name,
    label: product.name
  }))
}

// 重置搜索
const resetSearch = () => {
  searchProductName.value = ''
  isSearching.value = false
  productNameOptions.value = []
  fetchProducts() // 重新加载全部产品
}

// 导出产品数据
const exportProducts = async () => {
  try {
    if (!products.value || products.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    exportLoading.value = true
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportProductsData(products.value)
    
    if (result.success) {
      message.destroy()
      message.success(`导出成功！文件：${result.filename}`)
    } else {
      message.destroy()
      message.error(result.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}



// 组件挂载时获取数据
onMounted(() => {
  fetchProducts().then(() => {
    updateProductNameOptions()
  })
})
</script>