<template>
  <div class="flower-management">
    <a-card title="花卉管理" :bordered="false">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关键词">
            <a-input v-model:value="searchForm.keyword" placeholder="请输入花卉名称" allow-clear />
          </a-form-item>
          <a-form-item label="类型">
            <a-select v-model:value="searchForm.type" placeholder="请选择类型" allow-clear style="width: 120px">
              <a-select-option value="鲜花">鲜花</a-select-option>
              <a-select-option value="盆栽">盆栽</a-select-option>
              <a-select-option value="绿植">绿植</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" allow-clear style="width: 120px">
              <a-select-option value="active">上架</a-select-option>
              <a-select-option value="inactive">下架</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="() => handleSearch()">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <a-button type="primary" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新增花卉
        </a-button>
        <a-button style="margin-left: 8px" @click="handleExport">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <a-table
          :columns="columns"
          :data-source="flowerStore.flowers"
          :loading="flowerStore.loading"
          :pagination="pagination"
          row-key="id"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'image'">
              <a-image
                :width="60"
                :height="60"
                :src="record.image"
                :fallback="imageFallback"
                style="border-radius: 4px"
              />
            </template>
            <template v-else-if="column.dataIndex === 'price'">
              <span>¥{{ record.price }}</span>
            </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 === 'actions'">
              <a-space>
                <a-button size="small" @click="handleEdit(record)">编辑</a-button>
                <a-button size="small" @click="handleView(record)">查看</a-button>
                <a-popconfirm
                  title="确定要删除这个花卉吗？"
                  @confirm="handleDelete(record.id)"
                >
                  <a-button size="small" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 创建/编辑模态框 -->
    <FlowerModal
      :open="modalVisible"
      :current-record="currentRecord"
      :mode="modalMode"
      @cancel="handleModalCancel"
      @submit="handleModalSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useFlowerStore } from '@/stores/modules/flower'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import FlowerModal from './components/FlowerModal.vue'
import type { TablePaginationConfig } from 'ant-design-vue'

interface SearchForm {
  keyword: string
  type: string
  status: string
}

interface FlowerRecord {
  id: number
  name: string
  type: string
  variety: string
  price: number
  image: string
  status: string
  stock: number
  merchantId: number
  merchantName: string
  description: string
  createdAt: string
  updatedAt: string
}

const flowerStore = useFlowerStore()
const searchForm = reactive<SearchForm>({
  keyword: '',
  type: '',
  status: ''
})
const modalVisible = ref(false)
const modalMode = ref<'create' | 'edit' | 'view'>('create')
const currentRecord = ref<FlowerRecord | null>(null)

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60
  },
  {
    title: '图片',
    dataIndex: 'image',
    key: 'image',
    width: 80
  },
  {
    title: '花卉名称',
    dataIndex: 'name',
    key: 'name',
    width: 120
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 80
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions',
    width: 200
  }
]

// 分页配置
const pagination = computed<TablePaginationConfig>(() => ({
  total: 100, // 临时硬编码，实际应该从store获取
  current: 1,
  pageSize: 20,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
  pageSizeOptions: ['10', '20', '50', '100']
}))

const imageFallback = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiBmaWxsPSIjRjVGNUY1Ii8+CjxwYXRoIGQ9Ik0zMiAyMEM0MC44MzY2IDIwIDQ4IDI3LjE2MzQgNDggMzZDNDggNDQuODM2NiA0MC44MzY2IDUyIDMyIDUyQzIzLjE2MzQgNTIgMTYgNDQuODM2NiAxNiAzNkMxNiAyNy4xNjM0IDIzLjE2MzQgMjAgMzIgMjBaIiBmaWxsPSIjRDlEOUQ5Ii8+Cjx0ZXh0IHg9IjMyIiB5PSI0MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjEyIiBmaWxsPSIjOTk5OTk5Ij7lm77niYc8L3RleHQ+Cjwvc3ZnPgo='

// 事件处理方法
const handleSearch = () => {
  console.log('搜索花卉:', searchForm)
  // TODO: 实现搜索逻辑
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  searchForm.status = ''
  console.log('重置搜索条件')
  // TODO: 重新加载数据
}

const handleCreate = () => {
  modalMode.value = 'create'
  currentRecord.value = null
  modalVisible.value = true
}

const handleEdit = (record: FlowerRecord) => {
  modalMode.value = 'edit'
  currentRecord.value = record
  modalVisible.value = true
}

const handleView = (record: FlowerRecord) => {
  modalMode.value = 'view'
  currentRecord.value = record
  modalVisible.value = true
}

const handleDelete = async (id: number) => {
  try {
    // TODO: 调用删除API
    console.log('删除花卉:', id)
    message.success('删除成功')
  } catch (error) {
    message.error('删除失败')
  }
}

const handleExport = () => {
  console.log('导出花卉数据')
  // TODO: 实现导出功能
  message.info('导出功能开发中...')
}

const handleModalCancel = () => {
  modalVisible.value = false
  currentRecord.value = null
}

const handleModalSubmit = async (data: any) => {
  try {
    if (modalMode.value === 'create') {
      // TODO: 调用创建API
      console.log('创建花卉:', data)
      message.success('创建成功')
    } else if (modalMode.value === 'edit') {
      // TODO: 调用更新API
      console.log('更新花卉:', data)
      message.success('更新成功')
    }
    modalVisible.value = false
    currentRecord.value = null
    // TODO: 重新加载数据
  } catch (error) {
    message.error('操作失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  // TODO: 加载花卉数据
  console.log('加载花卉数据')
})
</script>

<style scoped>
.flower-management {
  padding: 24px;
}

.search-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.action-section {
  margin-bottom: 16px;
}

.table-section {
  background: white;
  border-radius: 6px;
}
</style>