import { pinia } from "@/pinia"
import { getOrdersByOpenIdApi, getOrdersByQyUserIdApi } from "@@/apis/shop"
import type { ShopOrderEntity, ShopOrderGoodsEntity, Goods } from "@@/apis/shop/type"

export interface Order extends ShopOrderEntity {
  goodsList: Array<OrderGoods>
}

export interface OrderGoods {
  goodsInfo: Goods
  orderGoods: ShopOrderGoodsEntity
}

export const useOrderStore = defineStore("order", () => {
  const orders = ref<Order[]>([])
  const orderGoods = ref<ShopOrderGoodsEntity[]>([])
  const goods = ref<Goods[]>([])

  const getOrders = async (corpid: string, openid: string, qyUserId: number, hasReturn: number) => {
    try {
      const { data } = qyUserId ? 
      await getOrdersByQyUserIdApi(qyUserId, hasReturn) 
      : await getOrdersByOpenIdApi(corpid, openid, hasReturn);
      
      // 重组订单结构
      orders.value = data.orders.map(order => ({
        ...order,
        goodsList: data.orderGoods
          .filter(og => og.orderId === order.orderId)
          .map(og => ({
            orderGoods: og,
            goodsInfo: data.goods.find(g => g.goodsId === og.goodsId)!
          }))
      }))
      .sort((a, b) => b.orderId - a.orderId)
      
      // 保留原始数据结构
      orderGoods.value = data.orderGoods
      goods.value = data.goods
    } catch (error) {
      console.error("获取订单数据失败:", error)
    }
  }

  return { orders, orderGoods, goods, getOrders }
})

export function useOrderStoreOutside() {
  return useOrderStore(pinia)
}