<script setup lang="ts">
import {
  appMerchantDishDetailGet,
  appCollectCollectPost,
  type MerchantDishVo,
  appMerchantCartAddCartPost,
  type MerchantCartVo,
  appMerchantCartListByMerchantIdPost,
  appMerchantDetailMerchantIdGet,
  type MerchantVo
} from "@/service";
import { debounce } from 'throttle-debounce'
const { t } = useI18n();
import { useScrollThreshold } from "@/hooks/useScrollThreshold";
import Config from "@/config";
import {useConfigStore, useUserStore} from "@/store";
import DishesSkeleton from "./components/dishes-skeleton.vue";
import {CollectionType} from "@/constant/enums";
import {getDistanceInMiles} from "@/utils/utils";
const configStore = useConfigStore();
const userStore = useUserStore();

// 响应式数据
const loading = ref(true); // 加载状态
const selectedSauce = ref([]); // 默认选择第一个

function isSoldOutStock(stockLike: unknown) {
  const n = Number(stockLike)
  return !Number.isNaN(n) && n <= 0
}

function showSoldOutToast() {
  uni.showToast({
    title: t('common.prompt.soldOut'),
    icon: 'none'
  })
}

const selectSauce = (item, id: string) => {
  if(!item.selectedIds) {
    item.selectedIds = [];
  }
  if(item.selectedIds.includes(id)) {
    // 如果已选中，则取消选择
    item.selectedIds = item.selectedIds.filter(selectedId => selectedId !== id)
  } else {
    // 单选逻辑：清空之前的选择，只保留当前选择
    item.selectedIds = [id]
  }
};

function handleSubmit() {
  console.log('加入购物车', dishDetailData.value)
  console.log('加入购物车', dishDetailData.value.merchantSideDishVoList)
  if (isSoldOutStock(dishDetailData.value?.stock)) {
    showSoldOutToast()
    return
  }
  // 查看所有必选的配菜是否已经选择了
  try {
    for(const item of dishDetailData.value.merchantSideDishVoList) {
      if(+item.isRequired === 1) {
        if(!item.selectedIds || item.selectedIds.length === 0) {
          uni.showToast({
            title: `${t('common.placeholder.pleaseSelect')} ${item.sideDishName}`,
            icon: 'none'
          })
          return;
        }
      }
    }
    const merchantCartSideDishBoList = dishDetailData.value.merchantSideDishVoList
      .filter(item => {
        // 只包含必选配菜或已选择的非必选配菜
        return +item.isRequired === 1 || (item.selectedIds && item.selectedIds.length > 0)
      })
      .map(item => ({
        sideDishId: item.id, // 配菜ID
        sideDishItemId: item.selectedIds[0] // 配菜子项ID（取第一个选中项）
      }));
    console.log('点击加入购物车', merchantCartSideDishBoList)


    appMerchantCartAddCartPost({
      body: {
        merchantId: storeId.value,
        dishId: dishDetailData.value.id, // 菜品ID
        count: 1,
        merchantCartSideDishBoList,
      }
    }).then(res=>  {
      uni.showToast({
        title: t('toast.addCartSuccess'),
        icon: 'none'
      })

      getCartInfo()
    })
  } catch (error) {
    console.log('点击加入购物车', error)
  }
}

const addCart = debounce(1000, handleSubmit, {
  atBegin: true, // 立即触发
});

const showStatusBar = useScrollThreshold();
onPageScroll((e) => {
  uni.$emit("page-scroll", e);
});

function navigateBack() {
  uni.navigateBack({
    delta: 1,
  });
}

const storeId = ref('')
onLoad((options: any) => {
  loading.value = true;
  if(options.id&&options.id!='undefined') {
    getDishDetail(options.id)
  }
  if(options.storeId&&options.storeId!='undefined') {
    storeId.value = options.storeId
    getCartInfo()
    getStoreDetail()
  }
})

// 获取菜品详情
const dishDetailData = ref<MerchantDishVo>(null);
function getDishDetail(id: string) {
  appMerchantDishDetailGet({
    params: {
      dishId: id
    }
  }).then((res: any)=> {
    console.log('获取菜品详情', res)
    dishDetailData.value = res.data;
  }).finally(()=> {
    loading.value = false;
  })
}

// 收藏菜品
function handleDishCollectionClick() {
  debouncedEmit(dishDetailData.value.isCollect, dishDetailData.value.id, CollectionType.DISH, ()=> {
    dishDetailData.value.isCollect = !dishDetailData.value.isCollect
  })
}
// 防抖处理函数
const debouncedEmit = debounce(1300, (isCollected: boolean, id: string, type: CollectionType, callback: ()=> void) => {
  // 收藏接口
  appCollectCollectPost({
    body: {
      targetId: id,
      targetType: type
    }
  }).then(res=> {
    callback()
  })
}, {
  atBegin: true, // 立即触发
})

function handleShare() {
  uni.shareWithSystem({
    summary: '',
    href: `${Config.shareLink}pages-store/pages/store/dishes?id=${dishDetailData.value.id}&storeId=${storeId.value}`,
    success(){
      // 分享完成，请注意此时不一定是成功分享
    },
    fail(){
      // 分享失败
    }
  })
}

const totalPrice = computed(() => {
  if (!dishDetailData.value) return 0;

  let basePrice = Number(dishDetailData.value.discountPrice) || 0;
  let sidePrice = 0;

  if (dishDetailData.value.merchantSideDishVoList) {
    dishDetailData.value.merchantSideDishVoList.forEach(item => {
      if (item.selectedIds && item.selectedIds.length > 0) {
        const selectedId = item.selectedIds[0]; // 单选逻辑，只取一个
        const selected = item.merchantSideDishItemVoList.find(s => s.id === selectedId);
        if (selected) {
          sidePrice += Number(selected.price) || 0;
        }
      }
    });
  }

  return (basePrice + sidePrice).toFixed(2);
});

const isSoldOut = computed(() => isSoldOutStock(dishDetailData.value?.stock))

const cartDataList = ref<MerchantCartVo[]>([])
function getCartInfo() {
  if(!userStore.isLogin) return
  appMerchantCartListByMerchantIdPost({
    params: {
      merchantId: storeId.value,
    }
  }).then((res: any)=> {
    console.log('购物车列表', res)
    cartDataList.value = res.data
  })
}

function navigateToCart() {
  // uni.navigateTo({
  //   url: '/pages-user/pages/cart/store-cart?storeId=' + storeId.value + '&storeName=' + storeDetail.value.merchantName,
  // });
  uni.navigateTo({
    url:
        '/pages-user/pages/cart/store-cart'
        + '?storeId=' + storeId.value
        + '&storeName=' + encodeURIComponent(storeDetail.value.merchantName),
  })
}

// 获取商家详情信息
const storeDetail = ref<MerchantVo>({})
function getStoreDetail() {
  appMerchantDetailMerchantIdGet({
    params: {
      merchantId: storeId.value,
    }
  }).then((res: any) => {
    console.log('商家详情', res)
    storeDetail.value = res.data as MerchantVo
  }).catch((error) => {
    console.error('获取商家详情失败:', error);
  })
}
</script>

<template>
  <view
      class="animate-in fade-in animate-ease-out animate-duration-300"
      v-show="loading"
  >
    <!-- 骨架屏 -->
    <DishesSkeleton />
  </view>
  <view
      class="animate-in fade-in animate-ease-in animate-duration-300"
      v-show="!loading"
  >
    <!-- 页面内容 -->
    <view class="dish-detail">
      <!-- 顶部图片区域 -->
      <status-bar />
      <view class="h-562rpx">
        <wd-swiper height="562rpx" :show-controls="false" :list="dishDetailData?.dishImage.split(',')" autoplay></wd-swiper>
        <!-- 状态栏 -->
        <view
            class="fixed top-0 left-0 z-9 w-full transition-all pt-6rpx"
            :class="[showStatusBar ? 'bg-#fff' : '']"
        >
          <status-bar />
          <view class="flex-center-sb px-30rpx">
            <image
                @click="navigateBack"
                src="@img/chef/1327.png"
                mode="aspectFill"
                class="w-48rpx h-48rpx relative z-1"
            />
            <view class="flex items-center">
              <view @click.stop="handleDishCollectionClick" class="w-68rpx h-68rpx mr-20rpx">
                <image
                    v-if="!dishDetailData?.isCollect"
                    src="@img-store/1334.png"
                    mode="aspectFill"
                    class="w-full h-full"
                />
                <image
                    v-else
                    src="@img-store/1337.png"
                    mode="aspectFill"
                    class="w-full h-full"
                />
              </view>
              <image
                  @click="handleShare"
                  src="@img-store/1336.png"
                  mode="aspectFill"
                  class="w-68rpx h-68rpx relative z-1"
              />
            </view>
          </view>
        </view>
      </view>



      <!-- 菜品信息区域 -->
      <view class="dish-info">
        <!-- 菜品标题 -->
        <text class="dish-title">{{ dishDetailData?.dishName }}</text>

        <!-- 菜品描述 -->
        <text class="dish-description">
          {{ dishDetailData?.dishDescription }}
        </text>

        <!-- 价格信息 -->
        <view class="price-section">
          <view class="flex items-center gap-12rpx">
            <text class="current-price">US${{ dishDetailData?.discountPrice }}</text>
            <text class="original-price">US${{ dishDetailData?.originalPrice }}</text>
            <view v-if="Number(dishDetailData?.memberPrice) > 0" class="member-price-tag center">
              <text class="member-price-text">{{ t('pages-store.store.members') }}: ${{ dishDetailData?.memberPrice }}</text>
            </view>
          </view>

          <view class="text-#333 text-30rpx font-500">
            <template v-if="dishDetailData?.stock !== undefined && dishDetailData?.stock !== null">
              {{ t('common.stock') }}: {{ Number(dishDetailData?.stock || 0).toFixed(0) }}
            </template>
          </view>
        </view>
      </view>

      <!-- 分隔线 -->
      <view class="divider mb-36rpx"></view>

      <!-- 选择调料区域 -->
      <view class="pb-188rpx">
        <template v-for="item in dishDetailData?.merchantSideDishVoList">
          <view class="px-30rpx flex-center-sb mb-22rpx">
            <view class="sauce-info">
              <text class="sauce-title">{{ item.sideDishName }}</text>
              <text class="sauce-subtitle mt-12rpx">{{ t('pages-store.store.choose') }}</text>
            </view>
            <view
                v-if="+item.isRequired === 1"
                class="required-tag h-64rpx center shrink-0"
                :class="[
            item.selectedIds && item.selectedIds.length !== 0
              ? 'bg-#00A76D/10 text-#00A76D font-500 !px-16rpx'
              : 'bg-#f2f2f2 text-#333',
          ]"
            >
              <image
                  v-if="item.selectedIds && item.selectedIds.length !== 0"
                  src="@img-store/1338.png"
                  mode="aspectFill"
                  class="w-28rpx h-28rpx shrink-0 mr-4rpx"
              />
              <text class="text-26rpx lh-26rpx">{{ t('pages-store.store.required') }}</text>
            </view>
          </view>
          <!-- 调料选项列表 -->
          <view class="mb-30rpx">
            <view
                v-for="(sauce, index) in item.merchantSideDishItemVoList"
                :key="index"
                class="sauce-option p-30rpx"
                @click="selectSauce(item, sauce.id)"
            >
              <text class="sauce-name">{{ sauce.name }}</text>

              <view class="flex items-center">
                <text class="text-#00A76D mr-10rpx">+${{ sauce.price }}</text>
                <!-- 单选按钮 -->
                <image
                    :src="
              item.selectedIds && item.selectedIds.includes(sauce.id)
                ? '/static/images/chef/133.png'
                : '/static/images/chef/134.png'
            "
                    class="w-48rpx h-48rpx shrink-0"
                    mode="aspectFit"
                />
              </view>
            </view>
          </view>
        </template>
      </view>

      <view class="!fixed bottom-0 left-0 right-0 px-30rpx">
        <view @click="isSoldOut ? showSoldOutToast() : undefined">
          <wd-button
              custom-class="!h-98rpx !text-30rpx !text-#fff !lh-98rpx !rounded-16rpx"
              block
              :disabled="isSoldOut"
              @click="addCart"
          >{{ t('pages-store.store.addToCart') }} • US${{ totalPrice }}
          </wd-button>
        </view>
        <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
      </view>
    </view>



    <view v-if="cartDataList.length > 0" @click="navigateToCart" class="fixed z-9 bottom-138rpx left-50% translate-x--50% px-26rpx h-88rpx bg-#14181B rounded-44rpx center text-28rpx text-#fff font-500">
      <image src="@img/chef/125.png" class="w-28rpx h-28rpx shrink-0"></image>
      <view class="ml-10rpx whitespace-nowrap line-clamp-1">{{ storeDetail.merchantName }}</view>
      <view class="w-8rpx h-8rpx rounded-50% bg-white mx-8rpx"></view>
      <text>{{ cartDataList.length }}</text>
    </view>
  </view>
</template>
<style lang="scss" scoped>
:deep(.wd-swiper__track) {
  border-radius: 0 !important;
}
.dish-detail {
  width: 100%;
  min-height: 100vh;
  background-color: #ffffff;
}

.top-image-container {
  position: relative;
  width: 750rpx;
  height: 562rpx;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.status-bar {
  position: absolute;
  top: 0;
  left: 0;
  width: 750rpx;
  height: 88rpx;
  background: rgba(0, 0, 0, 0.3);
}

.status-content {
  width: 656rpx;
  height: 24rpx;
  margin: 32rpx 47rpx;
  background: #d8d8d8;
  border-radius: 4rpx;
}

.back-button {
  position: absolute;
  top: 104rpx;
  left: 30rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.64);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 28rpx;
  height: 28rpx;
  background: #ffffff;
  clip-path: polygon(60% 0%, 100% 50%, 60% 100%, 40% 75%, 65% 50%, 40% 25%);
}

.share-button {
  position: absolute;
  top: 94rpx;
  right: 30rpx;
  width: 68rpx;
  height: 68rpx;
  background: rgba(0, 0, 0, 0.64);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.share-icon {
  width: 34rpx;
  height: 36rpx;
  background: #ffffff;
  border-radius: 4rpx;
}

.dish-info {
  padding: 40rpx 30rpx 32rpx;
}

.dish-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333333;
  line-height: 40rpx;
  margin-bottom: 16rpx;
  display: block;
}

.dish-description {
  font-size: 24rpx;
  color: #7d7d7d;
  line-height: 28rpx;
  margin-bottom: 12rpx;
  display: block;
}

.price-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.current-price {
  font-size: 32rpx;
  line-height: 32rpx;
  color: #333333;
  font-weight: 500;
}

.member-price-tag {
  height: 42rpx;
  padding-right: 16rpx;
  padding-left: 20rpx;
  background-image: url("/static/images/chef/1282.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.member-price-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #fbe3c3;
}

.original-price {
  font-size: 28rpx;
  color: #999999;
  text-decoration: line-through;
}

.divider {
  height: 10rpx;
  background: #f6f6f6;
}

.sauce-info {
  flex: 1;
}

.sauce-title {
  font-size: 40rpx;
  color: #333333;
  font-weight: bold;
  line-height: 40rpx;
  margin-bottom: 8rpx;
  display: block;
}

.sauce-subtitle {
  font-size: 24rpx;
  color: #7d7d7d;
  line-height: 24rpx;
  display: block;
}

.required-tag {
  border-radius: 8rpx;
  min-width: 150rpx;
  text-align: center;
}

.sauce-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #dfdfdf;
}

.sauce-name {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
  line-height: 32rpx;
}

.radio-button {
  width: 48rpx;
  height: 48rpx;
  border: 2rpx solid #999999;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-button.selected {
  border-color: #333333;
  background: #ffffff;
}

.radio-dot {
  width: 24rpx;
  height: 24rpx;
  background: #333333;
  border-radius: 50%;
}
</style>
<style>
page {
  background-color: #fff;
}
</style>
