<template>
  <view class="picker-page">
    <!-- 订单：普通/团购 两个 tab -->
    <view v-if="mode === 'order'" class="tabs">
      <view class="tab" :class="{ active: orderTab === 'normal' }" @tap="switchTab('normal')">普通订单</view>
      <view class="tab" :class="{ active: orderTab === 'group' }" @tap="switchTab('group')">团购订单</view>
    </view>

    <scroll-view class="list" scroll-y>
      <!-- 订单列表 -->
      <block v-if="mode === 'order'">
        <view v-for="(item, idx) in orderList" :key="idx" class="order-card" @tap="pickOrder(item)">
          <view class="order-head">
            <text class="order-no">订单号：{{ item.order_no }}</text>
          </view>
          <view class="order-goods">
            <image v-for="(g, gi) in (item.commodity_order_item_list || []).slice(0, 4)" :key="gi"
              :src="g.commodity_pic" class="goods-thumb" mode="aspectFill" />
          </view>
          <view class="order-foot">
            <text>共{{ item.total_count }}件</text>
            <text class="amount">¥{{ item.total_amount }}</text>
            <view class="send-btn">发送</view>
          </view>
        </view>
        <view v-if="orderList.length === 0" class="empty">暂无订单</view>
      </block>

      <!-- 购物车列表 -->
      <block v-else>
        <view v-for="(g, idx) in cartGoods" :key="idx" class="goods-row" @tap="pickGoods(g)">
          <image :src="g.pic" class="goods-thumb-lg" mode="aspectFill" />
          <view class="goods-info">
            <view class="goods-name">{{ g.name }}</view>
            <view class="goods-price">¥{{ g.price }}</view>
          </view>
          <view class="send-btn">发送</view>
        </view>
        <view v-if="cartGoods.length === 0" class="empty">购物车为空</view>
      </block>
    </scroll-view>
  </view>
</template>

<script>
import { request, picUrl } from '@/utils'
import { apiArr as shopApi } from '@/api/shop'
import { apiArr as afterSaleApi } from '@/api/afterSale'

export default {
  data() {
    return {
      mode: 'order',     // order | goods
      bindId: 0,
      orderTab: 'normal', // normal | group
      orderList: [],
      cartGoods: []
    }
  },
  onLoad(options) {
    this.mode = options.type === 'goods' ? 'goods' : 'order'
    this.bindId = Number(options.bindId) || 0
    uni.setNavigationBarTitle({ title: this.mode === 'goods' ? '选择购物车商品' : '选择订单' })
    if (this.mode === 'goods') {
      this.loadCart()
    } else {
      this.loadOrders()
    }
  },
  methods: {
    switchTab(t) {
      this.orderTab = t
      this.loadOrders()
    },
    // 订单列表：order_cate 1普通 2团购（按 tab 过滤）
    loadOrders() {
      request(afterSaleApi.orderList, 'POST', {
        user_id: uni.getStorageSync('userId')
      }).then(res => {
        const list = res.order_list || []
        list.forEach(item => {
          (item.commodity_order_item_list || []).forEach(g => {
            g.commodity_pic = (g.commodity_pic && g.commodity_pic.startsWith('http')) ? g.commodity_pic : picUrl + g.commodity_pic
          })
        })
        if (this.orderTab === 'group') {
          this.orderList = list.filter(i => i.order_cate == 2)
        } else {
          this.orderList = list.filter(i => i.order_cate == 1 || i.order_cate == 4)
        }
      })
    },
    // 购物车（非团购）
    loadCart() {
      request(shopApi.getCar, 'POST', { is_group_buy: '' }).then(res => {
        const groups = [].concat(res.same_day_cart_list || [], res.normal_cart_list || [])
        const goods = []
        groups.forEach(sup => {
          (sup.commodity_cart_and_goods_model || []).forEach(c => {
            const gi = c.commodity_goods_info || {}
            goods.push({
              goods_id: c.goods_id,
              commodity_id: c.commodity_id,
              name: gi.commodity_name || gi.goods_name || '商品',
              pic: (gi.commodity_pic && gi.commodity_pic.startsWith('http')) ? gi.commodity_pic : picUrl + (gi.commodity_pic || ''),
              price: gi.sales_price || c.price || 0
            })
          })
        })
        this.cartGoods = goods
      })
    },
    // 选中订单 -> 回传订单卡片（type=5）
    pickOrder(item) {
      const firstPic = (item.commodity_order_item_list && item.commodity_order_item_list[0] && item.commodity_order_item_list[0].commodity_pic) || ''
      const card = {
        order_id: item.id,
        order_no: item.order_no,
        amount: item.total_amount,
        count: item.total_count,
        pic: firstPic,
        page: '/packages/myOrders/orderDetails/index', // 点击跳转目标页（完整 item 经 storage 中转，避免 URL 超长）
        item // 完整订单对象，详情页直接用
      }
      uni.$emit('chat:pickCard', { type: 5, card })
      uni.navigateBack()
    },
    // 选中购物车商品 -> 回传商品卡片（type=4）
    pickGoods(g) {
      const card = {
        goods_id: g.goods_id,
        commodity_id: g.commodity_id,
        name: g.name,
        price: g.price,
        pic: g.pic,
        page: '/packages/advertising/goodsDetail/index',
        item: { commodity_id: g.commodity_id, id: g.goods_id, promotional_price: g.price } // goodsDetail 需 commodity_id 查详情、id 定位规格、promotional_price 作展示价
      }
      uni.$emit('chat:pickCard', { type: 4, card })
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.picker-page { display: flex; flex-direction: column; height: 100vh; background: #f5f5f5; }
.tabs { display: flex; background: #fff; }
.tab { flex: 1; text-align: center; padding: 28rpx 0; font-size: 28rpx; color: #666; }
.tab.active { color: #FF370B; font-weight: 600; border-bottom: 4rpx solid #FF370B; }
.list { flex: 1; padding: 20rpx; box-sizing: border-box; }
.order-card { background: #fff; border-radius: 12rpx; padding: 20rpx; margin-bottom: 20rpx; }
.order-head { font-size: 24rpx; color: #999; margin-bottom: 14rpx; }
.order-goods { display: flex; gap: 12rpx; }
.goods-thumb { width: 120rpx; height: 120rpx; border-radius: 8rpx; background: #f0f0f0; }
.order-foot { display: flex; align-items: center; justify-content: flex-end; gap: 20rpx; margin-top: 16rpx; }
.order-foot .amount { color: #FF370B; font-weight: 600; }
.goods-row { display: flex; align-items: center; background: #fff; border-radius: 12rpx; padding: 16rpx; margin-bottom: 16rpx; }
.goods-thumb-lg { width: 140rpx; height: 140rpx; border-radius: 8rpx; background: #f0f0f0; flex-shrink: 0; }
.goods-info { flex: 1; margin-left: 20rpx; min-width: 0; }
.goods-name { font-size: 28rpx; color: #222; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.goods-price { font-size: 30rpx; color: #FF370B; font-weight: 600; margin-top: 12rpx; }
.send-btn { background: linear-gradient(91deg, #FF7658, #FF370B); color: #fff; font-size: 24rpx; padding: 10rpx 28rpx; border-radius: 30rpx; flex-shrink: 0; }
.empty { text-align: center; color: #999; font-size: 26rpx; padding: 80rpx 0; }
</style>
