<template>
  <div class="mall-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <a-page-header title="商城管理" sub-title="商品和订单管理">
        <template #extra>
          <a-button type="primary" @click="showAddModal('product')">
            <ShopOutlined /> 新增商品
          </a-button>
          <a-button @click="showAddModal('order')">
            <ShoppingCartOutlined /> 新增订单
          </a-button>
        </template>
      </a-page-header>
    </div>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-cards">
      <a-col :span="6">
        <a-card>
          <a-statistic title="商品总数" :value="stats.totalProducts" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="订单总数" :value="stats.totalOrders" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic 
            title="销售额" 
            :value="stats.totalSales" 
            suffix="万元" 
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="今日订单" :value="stats.todayOrders" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 标签页 -->
    <a-tabs v-model:activeKey="activeTab" class="mall-tabs">
      <a-tab-pane key="products" tab="商品管理">
        <!-- 商品搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="productSearchForm">
            <a-form-item label="商品名称">
              <a-input v-model:value="productSearchForm.name" placeholder="请输入商品名称" />
            </a-form-item>
            <a-form-item label="商品分类">
              <a-select v-model:value="productSearchForm.category" placeholder="请选择分类" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="beef">牛肉制品</a-select-option>
                <a-select-option value="dairy">乳制品</a-select-option>
                <a-select-option value="snacks">特产零食</a-select-option>
                <a-select-option value="equipment">养殖设备</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="商品状态">
              <a-select v-model:value="productSearchForm.status" placeholder="请选择状态" style="width: 120px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="active">上架</a-select-option>
                <a-select-option value="inactive">下架</a-select-option>
                <a-select-option value="draft">草稿</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchProducts">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetProductSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 商品列表 -->
        <a-card>
          <a-table 
            :columns="productColumns" 
            :data-source="products" 
            :loading="productLoading"
            :pagination="productPagination"
            @change="handleProductTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'image'">
                <a-image
                  :width="50"
                  :height="50"
                  :src="record.image_url || '/placeholder.jpg'"
                  :preview="true"
                />
              </template>
              <template v-if="column.key === 'category'">
                <a-tag color="blue">
                  {{ getProductCategoryText(record.category) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag :color="getProductStatusColor(record.status)">
                  {{ getProductStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'featured'">
                <a-tag :color="record.featured ? 'gold' : 'default'">
                  {{ record.featured ? '推荐' : '普通' }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewProductDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    size="small" 
                    type="primary"
                    @click="editProduct(record)"
                  >
                    编辑
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="orders" tab="订单管理">
        <!-- 订单搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="orderSearchForm">
            <a-form-item label="订单编号">
              <a-input v-model:value="orderSearchForm.orderNumber" placeholder="请输入订单编号" />
            </a-form-item>
            <a-form-item label="买家姓名">
              <a-input v-model:value="orderSearchForm.buyerName" placeholder="请输入买家姓名" />
            </a-form-item>
            <a-form-item label="订单状态">
              <a-select v-model:value="orderSearchForm.status" placeholder="请选择状态" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="pending">待付款</a-select-option>
                <a-select-option value="paid">已付款</a-select-option>
                <a-select-option value="shipped">已发货</a-select-option>
                <a-select-option value="delivered">已送达</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchOrders">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetOrderSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 订单列表 -->
        <a-card>
          <a-table 
            :columns="orderColumns" 
            :data-source="orders" 
            :loading="orderLoading"
            :pagination="orderPagination"
            @change="handleOrderTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getOrderStatusColor(record.status)">
                  {{ getOrderStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewOrderDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.status === 'pending'" 
                    size="small" 
                    type="primary"
                    @click="confirmOrder(record)"
                  >
                    确认订单
                  </a-button>
                  <a-button 
                    v-if="record.status === 'paid'" 
                    size="small" 
                    @click="shipOrder(record)"
                  >
                    发货
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="reviews" tab="评价管理">
        <!-- 评价搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="reviewSearchForm">
            <a-form-item label="商品名称">
              <a-input v-model:value="reviewSearchForm.productName" placeholder="请输入商品名称" />
            </a-form-item>
            <a-form-item label="评分">
              <a-select v-model:value="reviewSearchForm.rating" placeholder="请选择评分" style="width: 120px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="5">5星</a-select-option>
                <a-select-option value="4">4星</a-select-option>
                <a-select-option value="3">3星</a-select-option>
                <a-select-option value="2">2星</a-select-option>
                <a-select-option value="1">1星</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchReviews">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetReviewSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 评价列表 -->
        <a-card>
          <a-table 
            :columns="reviewColumns" 
            :data-source="reviews" 
            :loading="reviewLoading"
            :pagination="reviewPagination"
            @change="handleReviewTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'rating'">
                <a-rate :value="record.rating" disabled />
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewReviewDetail(record)">
                    详情
                  </a-button>
                  <a-button size="small" @click="replyReview(record)">
                    回复
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { mallAPI } from '@/services/api.js';
import { 
  ShopOutlined, 
  ShoppingCartOutlined,
  SearchOutlined 
} from '@ant-design/icons-vue';

export default {
  name: 'MallManagement',
  components: {
    ShopOutlined,
    ShoppingCartOutlined,
    SearchOutlined
  },
  setup() {
    const activeTab = ref('products');
    const productLoading = ref(false);
    const orderLoading = ref(false);
    const reviewLoading = ref(false);
    
    // 统计数据
    const stats = reactive({
      totalProducts: 456,
      totalOrders: 1289,
      totalSales: 3650,
      todayOrders: 28
    });

    // 商品数据
    const products = ref([]);
    const productSearchForm = reactive({
      name: '',
      category: '',
      status: ''
    });
    const productPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 订单数据
    const orders = ref([]);
    const orderSearchForm = reactive({
      orderNumber: '',
      buyerName: '',
      status: ''
    });
    const orderPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 评价数据
    const reviews = ref([]);
    const reviewSearchForm = reactive({
      productName: '',
      rating: ''
    });
    const reviewPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 商品表格列
    const productColumns = [
      { title: '商品图片', key: 'image', width: 80 },
      { title: '商品名称', dataIndex: 'name', key: 'name' },
      { title: '分类', dataIndex: 'category', key: 'category' },
      { title: '价格(元)', dataIndex: 'price', key: 'price' },
      { title: '库存', dataIndex: 'stock', key: 'stock' },
      { title: '状态', dataIndex: 'status', key: 'status' },
      { title: '推荐', dataIndex: 'featured', key: 'featured' },
      { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 订单表格列
    const orderColumns = [
      { title: '订单编号', dataIndex: 'order_number', key: 'order_number', width: 150 },
      { title: '买家', dataIndex: 'buyer_name', key: 'buyer_name' },
      { title: '商品名称', dataIndex: 'product_name', key: 'product_name' },
      { title: '数量', dataIndex: 'quantity', key: 'quantity' },
      { title: '总金额(元)', dataIndex: 'total_amount', key: 'total_amount' },
      { title: '订单状态', dataIndex: 'status', key: 'status' },
      { title: '下单时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 180 }
    ];

    // 评价表格列
    const reviewColumns = [
      { title: '商品名称', dataIndex: 'product_name', key: 'product_name' },
      { title: '评价人', dataIndex: 'reviewer_name', key: 'reviewer_name' },
      { title: '评分', dataIndex: 'rating', key: 'rating' },
      { title: '评价内容', dataIndex: 'content', key: 'content' },
      { title: '评价时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 加载商品数据
    const loadProducts = async () => {
      productLoading.value = true;
      try {
        const params = {
          page: productPagination.current,
          limit: productPagination.pageSize,
          ...productSearchForm
        };
        const response = await mallAPI.getProducts(params);
        if (response.success) {
          products.value = response.data.products || [];
          productPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        message.error('获取商品列表失败');
      } finally {
        productLoading.value = false;
      }
    };

    // 加载订单数据
    const loadOrders = async () => {
      orderLoading.value = true;
      try {
        const params = {
          page: orderPagination.current,
          limit: orderPagination.pageSize,
          ...orderSearchForm
        };
        const response = await mallAPI.getOrders(params);
        if (response.success) {
          orders.value = response.data.orders || [];
          orderPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        message.error('获取订单列表失败');
      } finally {
        orderLoading.value = false;
      }
    };

    // 加载评价数据
    const loadReviews = async () => {
      reviewLoading.value = true;
      try {
        const params = {
          page: reviewPagination.current,
          limit: reviewPagination.pageSize,
          ...reviewSearchForm
        };
        const response = await mallAPI.getReviews(params);
        if (response.success) {
          reviews.value = response.data.reviews || [];
          reviewPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取评价列表失败:', error);
        message.error('获取评价列表失败');
      } finally {
        reviewLoading.value = false;
      }
    };

    // 商品分类文本
    const getProductCategoryText = (category) => {
      const texts = {
        'beef': '牛肉制品',
        'dairy': '乳制品',
        'snacks': '特产零食',
        'equipment': '养殖设备'
      };
      return texts[category] || category;
    };

    // 商品状态颜色
    const getProductStatusColor = (status) => {
      const colors = {
        'active': 'green',
        'inactive': 'red',
        'draft': 'orange'
      };
      return colors[status] || 'default';
    };

    // 商品状态文本
    const getProductStatusText = (status) => {
      const texts = {
        'active': '上架',
        'inactive': '下架',
        'draft': '草稿'
      };
      return texts[status] || status;
    };

    // 订单状态颜色
    const getOrderStatusColor = (status) => {
      const colors = {
        'pending': 'orange',
        'paid': 'blue',
        'shipped': 'purple',
        'delivered': 'cyan',
        'completed': 'green',
        'cancelled': 'red'
      };
      return colors[status] || 'default';
    };

    // 订单状态文本
    const getOrderStatusText = (status) => {
      const texts = {
        'pending': '待付款',
        'paid': '已付款',
        'shipped': '已发货',
        'delivered': '已送达',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return texts[status] || status;
    };

    // 搜索商品
    const searchProducts = () => {
      productPagination.current = 1;
      loadProducts();
    };

    // 重置商品搜索
    const resetProductSearch = () => {
      Object.assign(productSearchForm, {
        name: '',
        category: '',
        status: ''
      });
      searchProducts();
    };

    // 搜索订单
    const searchOrders = () => {
      orderPagination.current = 1;
      loadOrders();
    };

    // 重置订单搜索
    const resetOrderSearch = () => {
      Object.assign(orderSearchForm, {
        orderNumber: '',
        buyerName: '',
        status: ''
      });
      searchOrders();
    };

    // 搜索评价
    const searchReviews = () => {
      reviewPagination.current = 1;
      loadReviews();
    };

    // 重置评价搜索
    const resetReviewSearch = () => {
      Object.assign(reviewSearchForm, {
        productName: '',
        rating: ''
      });
      searchReviews();
    };

    // 表格变化处理
    const handleProductTableChange = (pagination) => {
      productPagination.current = pagination.current;
      productPagination.pageSize = pagination.pageSize;
      loadProducts();
    };

    const handleOrderTableChange = (pagination) => {
      orderPagination.current = pagination.current;
      orderPagination.pageSize = pagination.pageSize;
      loadOrders();
    };

    const handleReviewTableChange = (pagination) => {
      reviewPagination.current = pagination.current;
      reviewPagination.pageSize = pagination.pageSize;
      loadReviews();
    };

    // 显示添加模态框
    const showAddModal = (type) => {
      message.info(`添加${type === 'product' ? '商品' : '订单'}功能开发中`);
    };

    // 查看详情
    const viewProductDetail = (record) => {
      message.info(`查看商品详情: ${record.name}`);
    };

    const viewOrderDetail = (record) => {
      message.info(`查看订单详情: ${record.order_number}`);
    };

    const viewReviewDetail = (record) => {
      message.info(`查看评价详情: ${record.product_name}`);
    };

    // 其他操作
    const editProduct = (record) => {
      message.info(`编辑商品: ${record.name}`);
    };

    const confirmOrder = (record) => {
      message.info(`确认订单: ${record.order_number}`);
    };

    const shipOrder = (record) => {
      message.info(`发货订单: ${record.order_number}`);
    };

    const replyReview = (record) => {
      message.info(`回复评价: ${record.product_name}`);
    };

    onMounted(() => {
      loadProducts();
      loadOrders();
      loadReviews();
    });

    return {
      activeTab,
      stats,
      products,
      productLoading,
      productSearchForm,
      productPagination,
      productColumns,
      orders,
      orderLoading,
      orderSearchForm,
      orderPagination,
      orderColumns,
      reviews,
      reviewLoading,
      reviewSearchForm,
      reviewPagination,
      reviewColumns,
      loadProducts,
      loadOrders,
      loadReviews,
      getProductCategoryText,
      getProductStatusColor,
      getProductStatusText,
      getOrderStatusColor,
      getOrderStatusText,
      searchProducts,
      resetProductSearch,
      searchOrders,
      resetOrderSearch,
      searchReviews,
      resetReviewSearch,
      handleProductTableChange,
      handleOrderTableChange,
      handleReviewTableChange,
      showAddModal,
      viewProductDetail,
      viewOrderDetail,
      viewReviewDetail,
      editProduct,
      confirmOrder,
      shipOrder,
      replyReview
    };
  }
};
</script>

<style scoped>
.mall-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  margin-bottom: 16px;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-cards .ant-card {
  text-align: center;
}

.mall-tabs {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.search-card .ant-form {
  margin-bottom: 0;
}
</style>