<script setup lang="ts">
import {appMerchantCartDeleteByMerchantIdPost, appMerchantCartListMerchantPost, appMerchantCartDeleteCartPost, appMerchantCartCalculateSavingsPost, appMerchantCartListByMerchantIdPost} from "@/service";

const { t } = useI18n();
import { useMessage } from "wot-design-uni";
import RemoveCart from "./components/remove-cart.vue";
import CartSkeleton from "./components/cart-skeleton.vue";
const message = useMessage();

const removeCartRef = ref<InstanceType<typeof RemoveCart>>();

// 购物车商品接口
interface CartItem {
  id: string;
  dishId: string;
  merchantId: string;
  count: number;
  merchantDishVo: any;
  sideDishList: any[];
  checked: boolean;
}

// 购物车店铺接口
interface CartMerchant {
  id: string;
  merchantName: string;
  logo: string;
  merchantAddress: string;
  cartTotalPrice: number;
  merchantCartVoList: CartItem[];
  allChecked: boolean; // 店铺内商品是否全选
}

const dataList = ref<CartMerchant[]>([]);

// 全选状态
const allChecked = ref(false);

// 计算所有选中的商品
const selectedCartItems = computed(() => {
  const items: CartItem[] = [];
  dataList.value.forEach(merchant => {
    merchant.merchantCartVoList.forEach(item => {
      if (item.checked) {
        items.push(item);
      }
    });
  });
  return items;
});

// 计算选中商品总数
const selectedCount = computed(() => selectedCartItems.value.length);

// 价格统计数据
const priceData = ref<{
  totalPayPrice: string | number;
  savings: string | number;
  totalQuantity?: number;
}>({
  totalPayPrice: 0,
  savings: 0
});

// 价格计算中的状态
const calculatingPrice = ref(false);

// 监听选中商品变化，调用价格统计接口
watch(() => selectedCartItems.value.map(item => item.id), (newIds, oldIds) => {
  // 只有当选中的商品ID列表发生变化时才调用接口
  if (newIds.length > 0) {
    calculatePrice();
  } else {
    priceData.value = {
      totalPayPrice: 0,
      savings: 0
    };
    calculatingPrice.value = false;
  }
}, { deep: true });

// 调用价格统计接口
const calculatePrice = () => {
  calculatingPrice.value = true;
  const cartIds = selectedCartItems.value.map(item => item.id);
  appMerchantCartCalculateSavingsPost({
    body: cartIds
  }).then(res => {
    console.log('价格统计', res);
    priceData.value = res.data;
  }).catch(err => {
    console.error('价格统计失败', err);
  }).finally(() => {
    calculatingPrice.value = false;
  });
};

// 全选/取消全选
const toggleAllCheck = () => {
  // wd-checkbox 已经自动切换了 allChecked.value 的值
  dataList.value.forEach(merchant => {
    merchant.allChecked = allChecked.value;
    merchant.merchantCartVoList.forEach(item => {
      item.checked = allChecked.value;
    });
  });
};

// 切换店铺内所有商品选中状态
const toggleMerchantCheck = (merchant: CartMerchant) => {
  // wd-checkbox 已经自动切换了 merchant.allChecked 的值
  merchant.merchantCartVoList.forEach(item => {
    item.checked = merchant.allChecked;
  });
  updateAllCheckedState();
};

// 切换单个商品选中状态
const toggleItemCheck = (merchant: CartMerchant, item: CartItem) => {
  // wd-checkbox 已经自动切换了 item.checked 的值，不需要手动切换
  // 更新店铺全选状态
  merchant.allChecked = merchant.merchantCartVoList.every(i => i.checked);
  updateAllCheckedState();
};

// 更新全选状态
const updateAllCheckedState = () => {
  const allItems = dataList.value.flatMap(m => m.merchantCartVoList);
  allChecked.value = allItems.length > 0 && allItems.every(item => item.checked);
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 查看购物车
const viewCart = (item: any) => {
  uni.navigateTo({
    url:
        '/pages-user/pages/cart/store-cart'
        + '?storeId=' + item.id
        + '&storeName=' + encodeURIComponent(item.merchantName)
        + '&type=index',
  })
};

// 查看店铺
const viewStore = (storeId: string) => {
  uni.navigateTo({
    url: `/pages-store/pages/store/index?id=${storeId}`,
  });
};

// 删除店铺
const removeStoreId = ref('')
const deleteStore = (item: any) => {
  removeCartRef.value?.onOpen();
  removeStoreId.value = item.id
};
function confirmRemove() {
  appMerchantCartDeleteByMerchantIdPost({
    params: {
      merchantId: removeStoreId.value
    }
  }).then(res=> {
    getCartList()
    uni.showToast({
      icon: 'none',
      title: '删除成功'
    })
  })
}

// 批量结算
const batchCheckout = () => {
  if (selectedCount.value === 0) {
    uni.showToast({
      icon: 'none',
      title: '请选择要结算的商品'
    });
    return;
  }
  
  // 如果价格正在计算中，提示用户等待
  if (calculatingPrice.value) {
    uni.showToast({
      icon: 'none',
      title: '价格计算中，请稍候...'
    });
    return;
  }
  
  // 收集所有选中商品的购物车ID
  const cartIds = selectedCartItems.value.map(item => item.id);
  
  // 跳转到批量结算页面
  uni.navigateTo({
    url: `/pages-store/pages/order/checkout?cartIds=${cartIds.join(',')}&type=batch`
  });
};

// 前往首页
const goToHome = () => {
  uni.switchTab({
    url: "/pages/home/index",
  });
};

// 骨架屏加载状态
const loading = ref(true);
onMounted(() => {
  loading.value = true;
  getCartList()
});

async function getCartList() {
  try {
    // 1. 先获取店铺列表
    const res = await appMerchantCartListMerchantPost({});
    console.log('购物车店铺列表', res);
    
    if (!res.data || res.data.length === 0) {
      dataList.value = [];
      return;
    }
    
    // 2. 对每个店铺查询完整的商品信息
    const merchantPromises = res.data.map(async (merchant: any) => {
      try {
        const cartRes = await appMerchantCartListByMerchantIdPost({
          params: {
            merchantId: merchant.id
          }
        });
        console.log(`店铺 ${merchant.merchantName} 的商品列表`, cartRes);
        
        return {
          ...merchant,
          allChecked: false,
          merchantCartVoList: (cartRes.data || []).map((item: any) => ({
            ...item,
            checked: false
          }))
        };
      } catch (error) {
        console.error(`获取店铺 ${merchant.id} 商品失败`, error);
        return {
          ...merchant,
          allChecked: false,
          merchantCartVoList: []
        };
      }
    });
    
    // 3. 等待所有店铺的商品信息加载完成
    dataList.value = await Promise.all(merchantPromises);
    console.log('最终购物车数据', dataList.value);
    
  } catch (error) {
    console.error('获取购物车列表失败', error);
    dataList.value = [];
  } finally {
    loading.value = false;
  }
}
</script>
<template>
  <z-paging
    bg-color="#fff"
  >
    <template #top>
      <navbar />
      <!-- 标题 -->
      <view class="px-30rpx mt-20rpx text-46rpx lh-46rpx font-bold text-#333">
        {{ t('pages-user.cart.title') }}
      </view>
    </template>
    <!-- 骨架屏 -->
    <view
      class="animate-in fade-in animate-ease-out animate-duration-300"
      v-show="loading"
    >
      <cart-skeleton />
    </view>
    <view
      class="animate-in fade-in animate-ease-in animate-duration-300"
      v-show="!loading"
    >
      <!-- 购物车列表 -->
      <view class="px-20rpx mt-54rpx pb-200rpx">
        <template v-if="dataList.length > 0">
          <view
            v-for="(merchant, index) in dataList"
            :key="merchant.id"
            class="mb-30rpx"
          >
            <!-- 店铺信息卡片 -->
            <view class="rounded-24rpx border-2rpx border-solid border-[#E8E8E8] overflow-hidden">
              <!-- 店铺头部 -->
              <view class="p-30rpx flex items-center border-bottom border-[#E8E8E8]">
                <!-- 店铺全选框 -->
                <view class="mr-20rpx flex-shrink-0">
                  <wd-checkbox 
                    v-model="merchant.allChecked"
                    shape="circle"
                    @change="toggleMerchantCheck(merchant)"
                  />
                </view>

                <!-- 店铺图片 -->
                <view
                  class="w-55rpx h-55rpx rounded-full overflow-hidden bg-[#D8D8D8] flex-shrink-0"
                  @click="viewStore(merchant.id)"
                >
                  <image
                    :src="merchant.logo"
                    class="w-full h-full"
                    mode="aspectFill"
                  />
                </view>

                <!-- 店铺名称 -->
                <view class="ml-20rpx flex-1" @click="viewStore(merchant.id)">
                  <view class="text-30rpx text-[#333333] font-500">{{
                      merchant.merchantName
                  }}</view>
                </view>

                <!-- 删除按钮 -->
                <view
                  class="w-60rpx h-60rpx rounded-full bg-[#F2F2F2] flex items-center justify-center flex-shrink-0"
                  @click="deleteStore(merchant)"
                >
                  <image src="@img/chef/1278.png" class="w-60rpx h-60rpx"></image>
                </view>
              </view>

              <!-- 商品列表 -->
              <view class="px-30rpx">
                <view
                  v-for="(item, itemIndex) in merchant.merchantCartVoList"
                  :key="item.id"
                  class="py-30rpx flex items-start items-center"
                  :class="itemIndex < merchant.merchantCartVoList.length - 1 ? 'border-bottom border-[#F2F2F2]' : ''"
                >
                  <!-- 商品多选框 -->
                  <view class="mr-20rpx mt-20rpx flex-shrink-0">
                    <wd-checkbox 
                      v-model="item.checked"
                      shape="circle"
                      @change="toggleItemCheck(merchant, item)"
                    />
                  </view>

                  <!-- 商品图片 -->
                  <image
                    :src="item.merchantDishVo?.dishImage?.split(',')[0]"
                    mode="aspectFill"
                    class="w-136rpx h-136rpx shrink-0 rounded-16rpx"
                  ></image>

                  <!-- 商品信息 -->
                  <view class="ml-20rpx flex-1">
                    <view class="text-[#333333] text-28rpx lh-40rpx font-500 line-clamp-2">{{
                        item.merchantDishVo?.dishName
                    }}</view>
                    
                    <!-- 配菜信息 -->
                    <view class="text-[#7D7D7D] text-22rpx lh-28rpx mt-10rpx" v-if="item.sideDishList?.length > 0">
                      <template v-for="dish in item.sideDishList">
                        <text class="mr-6rpx">
                          {{ dish?.merchantSideDishItemVo?.name || '' }}
                        </text>
                        <text v-if="dish?.merchantSideDishItemVo?.price" class="text-#00A76D mr-10rpx">+${{ dish?.merchantSideDishItemVo?.price }}</text>
                      </template>
                    </view>

                    <!-- 价格和数量 -->
                    <view class="flex items-center justify-between mt-16rpx">
                      <view class="flex items-center">
                        <text class="text-[#333333] text-30rpx font-500"
                        >${{ item.merchantDishVo?.discountPrice }}</text>
                        <text
                          v-if="item.merchantDishVo?.originalPrice && item.merchantDishVo?.originalPrice !== item.merchantDishVo?.discountPrice"
                          class="text-[#7D7D7D] text-24rpx line-through ml-10rpx"
                        >${{ item.merchantDishVo?.originalPrice }}</text>
                      </view>
                      <view class="text-[#7D7D7D] text-24rpx">
                        x{{ item.count }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <!-- 查看购物车按钮 -->
              <!-- <view class="px-30rpx pb-30rpx">
                <view
                  class="h-88rpx rounded-16rpx bg-[#14181B] flex items-center justify-center"
                  @click="viewCart(merchant)"
                >
                  <text class="text-30rpx text-white font-500"
                    >{{ t('pages-user.cart.viewCart') }}</text
                  >
                </view>
              </view> -->
            </view>
          </view>
        </template>

        <!-- 空购物车状态 -->
        <template v-else>
          <view class="flex flex-col items-center justify-center py-100rpx">
            <image src="@img/chef/100.png" class="w-318rpx h-318rpx"></image>
            <text class="text-32rpx text-[#7D7D7D]">Your cart is empty</text>
            <view
              class="mt-60rpx w-400rpx h-88rpx rounded-16rpx bg-[#14181B] flex items-center justify-center"
              @click="goToHome"
            >
              <text class="text-30rpx text-white">Explore Restaurants</text>
            </view>
          </view>
        </template>
      </view>
    </view>
  </z-paging>

  <!-- 底部结算栏 - 使用 page-meta 配合 fixed 定位 -->
  <view 
    v-if="dataList.length > 0"
    class="cart-footer"
  >
    <view class="cart-footer-content">
      <!-- 全选 -->
      <view class="flex items-center">
        <wd-checkbox 
          v-model="allChecked"
          shape="circle"
          @change="toggleAllCheck"
        >
          全选
        </wd-checkbox>
      </view>

      <!-- 合计和结算 -->
      <view class="flex items-center">
        <view class="mr-30rpx text-right">
          <text class="text-24rpx text-[#999]">合计: </text>
          <text class="text-36rpx text-[#FF4D4F] font-bold">
            ${{ priceData.totalPayPrice || '0.00' }}
          </text>
        </view>
        <view 
          class="h-80rpx px-50rpx rounded-40rpx flex items-center justify-center"
          :class="selectedCount > 0 && !calculatingPrice ? 'bg-#14181B' : 'bg-#E8E8E8'"
          @click="batchCheckout"
        >
          <text 
            class="text-30rpx font-500"
            :class="selectedCount > 0 && !calculatingPrice ? 'text-white' : 'text-#999'"
          >
            <text v-if="calculatingPrice">计算中...</text>
            <text v-else>结算<text v-if="selectedCount > 0">({{ selectedCount }})</text></text>
          </text>
        </view>
      </view>
    </view>
  </view>

  <remove-cart @confirm="confirmRemove" ref="removeCartRef" />
</template>
<style scoped>
page {
  background-color: #fff;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  border-top: 1rpx solid #E8E8E8;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.cart-footer-content {
  height: 120rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
