import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getOrders, getOrderById, createOrder, updateOrderStatus, cancelOrder, shipOrder, completeOrder } from '@/api/orders'

export const useOrderStore = defineStore('orders', () => {
  // 状态
  const orders = ref([])
  const currentOrder = ref(null)
  const loading = ref(false)
  const pagination = ref({
    page: 0,
    size: 10,
    total: 0,
    totalPages: 0
  })

  // 获取订单列表
  const fetchOrders = async (params = {}) => {
    try {
      loading.value = true
      console.log('OrderStore: 开始获取订单，参数:', params)
      
      const response = await getOrders(params)
      console.log('OrderStore: API原始响应:', response)
      
      if (response.success) {
        orders.value = response.data.content || response.data
        pagination.value = {
          page: response.data.number || 0,
          size: response.data.size || 10,
          total: response.data.totalElements || response.data.length,
          totalPages: response.data.totalPages || 1
        }
        console.log('OrderStore: 处理后的订单数据:', orders.value)
        console.log('OrderStore: 分页信息:', pagination.value)
      } else {
        console.error('OrderStore: API返回失败:', response.message)
      }
      return response
    } catch (error) {
      console.error('OrderStore: 获取订单异常:', error)
      return { success: false, message: '获取订单列表失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取订单详情
  const fetchOrderById = async (id) => {
    try {
      loading.value = true
      const response = await getOrderById(id)
      
      if (response.success) {
        currentOrder.value = response.data
      }
      return response
    } catch (error) {
      console.error('Fetch order error:', error)
      return { success: false, message: '获取订单详情失败' }
    } finally {
      loading.value = false
    }
  }

  // 创建订单
  const createNewOrder = async (orderData) => {
    try {
      loading.value = true
      const response = await createOrder(orderData)
      
      if (response.success) {
        // 刷新订单列表
        await fetchOrders()
      }
      return response
    } catch (error) {
      console.error('Create order error:', error)
      return { success: false, message: '创建订单失败' }
    } finally {
      loading.value = false
    }
  }

  // 更新订单状态
  const updateOrder = async (id, status, notes) => {
    try {
      loading.value = true
      const response = await updateOrderStatus(id, status, notes)
      
      if (response.success) {
        // 更新本地订单状态
        const order = orders.value.find(o => o.id === id)
        if (order) {
          order.status = status
          order.updatedAt = new Date().toISOString()
        }
        
        // 更新当前订单
        if (currentOrder.value && currentOrder.value.id === id) {
          currentOrder.value.status = status
          currentOrder.value.updatedAt = new Date().toISOString()
        }
      }
      return response
    } catch (error) {
      console.error('Update order error:', error)
      return { success: false, message: '更新订单状态失败' }
    } finally {
      loading.value = false
    }
  }

  // 取消订单
  const cancelOrderById = async (id, reason) => {
    try {
      loading.value = true
      const response = await cancelOrder(id, reason)
      
      if (response.success) {
        // 更新本地订单状态
        const order = orders.value.find(o => o.id === id)
        if (order) {
          order.status = 'CANCELLED'
          order.cancelledAt = new Date().toISOString()
        }
        
        // 更新当前订单
        if (currentOrder.value && currentOrder.value.id === id) {
          currentOrder.value.status = 'CANCELLED'
          currentOrder.value.cancelledAt = new Date().toISOString()
        }
      }
      return response
    } catch (error) {
      console.error('Cancel order error:', error)
      return { success: false, message: '取消订单失败' }
    } finally {
      loading.value = false
    }
  }

  // 发货
  const shipOrderById = async (id, trackingNumber) => {
    try {
      loading.value = true
      const response = await shipOrder(id, trackingNumber)
      
      if (response.success) {
        // 更新本地订单状态
        const order = orders.value.find(o => o.id === id)
        if (order) {
          order.status = 'SHIPPED'
          order.shippedAt = new Date().toISOString()
        }
        
        // 更新当前订单
        if (currentOrder.value && currentOrder.value.id === id) {
          currentOrder.value.status = 'SHIPPED'
          currentOrder.value.shippedAt = new Date().toISOString()
        }
      }
      return response
    } catch (error) {
      console.error('Ship order error:', error)
      return { success: false, message: '发货失败' }
    } finally {
      loading.value = false
    }
  }

  // 完成订单
  const completeOrderById = async (id) => {
    try {
      loading.value = true
      const response = await completeOrder(id)
      
      if (response.success) {
        // 更新本地订单状态
        const order = orders.value.find(o => o.id === id)
        if (order) {
          order.status = 'COMPLETED'
          order.deliveredAt = new Date().toISOString()
        }
        
        // 更新当前订单
        if (currentOrder.value && currentOrder.value.id === id) {
          currentOrder.value.status = 'COMPLETED'
          currentOrder.value.deliveredAt = new Date().toISOString()
        }
      }
      return response
    } catch (error) {
      console.error('Complete order error:', error)
      return { success: false, message: '完成订单失败' }
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    orders,
    currentOrder,
    loading,
    pagination,
    // 方法
    fetchOrders,
    fetchOrderById,
    createNewOrder,
    updateOrder,
    cancelOrderById,
    shipOrderById,
    completeOrderById
  }
})



