import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Order, OrderQueryParams, OrderStatus } from '../../types/order'



export const useOrderStore = defineStore('order', () => {
  // 状态
  const orders = ref<Order[]>([])
  const currentOrder = ref<Order | null>(null)
  const loading = ref(false)
  const totalCount = ref(0)
  const queryParams = ref<OrderQueryParams>({
    page: 1,
    pageSize: 10,
    keyword: '',
    status: undefined,
    orderType: undefined,
    startDate: '',
    endDate: ''
  })

  // 获取订单列表
  const fetchOrders = async (params?: OrderQueryParams) => {
    loading.value = true
    try {
      // 模拟数据
      const mockOrders: Order[] = [
        {
          id: 1,
          orderNo: 'ORDER202401150001',
          userId: 101,
          username: 'user1',
          merchantId: 1,
          shopName: '鲜花坊',
          orderType: 'flower',
          productName: '玫瑰花束',
          quantity: 1,
          unitPrice: 198.00,
          totalAmount: 198.00,
          status: 'completed',
          createTime: '2024-01-15 10:30:00',
          completeTime: '2024-01-15 14:00:00',
          recipientName: '李四',
          recipientPhone: '13900139000',
          deliveryAddress: '北京市朝阳区',
          message: '生日快乐！'
        },
        {
          id: 2,
          orderNo: 'ORDER202401140001',
          userId: 102,
          username: 'user2',
          merchantId: 2,
          shopName: '快乐农场',
          orderType: 'animal',
          productName: '小羊认领',
          quantity: 1,
          unitPrice: 299.00,
          totalAmount: 299.00,
          status: 'pending',
          createTime: '2024-01-14 16:20:00',
          recipientName: '王五',
          recipientPhone: '13800138001',
          deliveryAddress: '上海市浦东新区'
        }
      ]
      
      orders.value = mockOrders
      totalCount.value = mockOrders.length
      
      if (params) {
        queryParams.value = { ...queryParams.value, ...params }
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取订单详情
  const fetchOrderDetail = async (orderId: number) => {
    loading.value = true
    try {
      // 模拟数据
      const mockOrder: Order = {
        id: orderId,
        orderNo: `ORDER20240115${orderId.toString().padStart(4, '0')}`,
        userId: 100 + orderId,
        username: `user${orderId}`,
        merchantId: orderId,
        shopName: `商家${orderId}`,
        orderType: 'flower',
        productName: '商品',
        quantity: 1,
        unitPrice: 100.00,
        totalAmount: 100.00,
        status: 'pending',
        createTime: '2024-01-15 10:00:00',
        recipientName: '收件人',
        recipientPhone: '13800138000',
        deliveryAddress: '地址'
      }
      
      currentOrder.value = mockOrder
      return mockOrder
    } catch (error) {
      console.error('获取订单详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新订单状态
  const updateOrderStatus = async (orderId: number, status: OrderStatus) => {
    try {
      // 模拟状态更新
      const order = orders.value.find((o: Order) => o.id === orderId)
      if (order) {
        order.status = status
        if (status === 'completed') {
          order.completeTime = new Date().toISOString()
        }
      }
      
      if (currentOrder.value && currentOrder.value.id === orderId) {
        currentOrder.value.status = status
        if (status === 'completed') {
          currentOrder.value.completeTime = new Date().toISOString()
        }
      }
      
      return true
    } catch (error) {
      console.error('更新订单状态失败:', error)
      throw error
    }
  }

  // 搜索订单
  const searchOrders = async (keyword: string) => {
    queryParams.value.keyword = keyword
    return fetchOrders(queryParams.value)
  }

  // 重置查询参数
  const resetQueryParams = () => {
    queryParams.value = {
      page: 1,
      pageSize: 10,
      keyword: '',
      status: undefined,
      orderType: undefined,
      startDate: '',
      endDate: ''
    }
  }

  // 获取订单统计
  const getOrderStatistics = async () => {
    try {
      // 模拟统计数据
      return {
        totalOrders: 1256,
        pendingOrders: 45,
        completedOrders: 987,
        cancelledOrders: 224,
        totalRevenue: 156800.50,
        averageOrderValue: 124.68,
        dailyOrderCount: 89,
        orderTypeDistribution: {
          flower: 456,
          animal: 312,
          activity: 288,
          travel: 200
        },
        statusDistribution: {
          pending: 45,
          paid: 156,
          shipped: 89,
          completed: 987,
          cancelled: 224
        }
      }
    } catch (error) {
      console.error('获取订单统计失败:', error)
      throw error
    }
  }

  // 导出订单数据
  const exportOrders = async () => {
    try {
      // 模拟导出功能
      const csvContent = orders.value.map(order => 
        `${order.orderNo},${order.username},${order.shopName},${order.productName},${order.totalAmount},${order.status}`
      ).join('\n')
      
      return csvContent
    } catch (error) {
      console.error('导出订单数据失败:', error)
      throw error
    }
  }

  return {
    orders,
    currentOrder,
    loading,
    totalCount,
    queryParams,
    fetchOrders,
    fetchOrderDetail,
    updateOrderStatus,
    searchOrders,
    resetQueryParams,
    getOrderStatistics,
    exportOrders
  }
})