<template>
  <view class="content-box" :style="{ height: height + 'px' }">
    <view class="tab-container">
      <!-- 标签栏 -->
      <view class="tabs">
        <template v-for="item in tabList">
          <view
            class="tab-item"
            :class="{
              'active-tab-item': currentTab === item.value,
              'active-pr': currentTab === item.value && item.value === 'goods',
              'active-pl': currentTab === item.value && item.value === 'intro',
            }"
            @click.stop="currentTab = item.value"
          >
            <text class="tab-text">{{ item.lable }}</text>
            <image
              class="tab-icon"
              :src="$handleImageUrl('/home/icon_left.png')"
              mode=""
              v-if="currentTab === item.value && item.value === 'goods'"
            ></image>
            <image
              class="tab-icon"
              :src="$handleImageUrl('/home/icon_right.png')"
              mode=""
              v-if="currentTab === item.value && item.value === 'intro'"
            ></image>
          </view>
        </template>
      </view>
    </view>
    <view class="scroll-content" :style="{ height: scrollHeight + 'px' }">
      <!-- 商品 -->
      <template v-if="currentTab === 'goods'">
        <view class="goods-box" :style="{ height: getScrollHeight(cartList) }">
          <view class="goods-left" :style="{ height: '100%' }">
            <scroll-view
              scroll-y="true"
              :scroll-into-view="scrollIntoView"
              :style="{ height: '99%' }"
            >
              <block v-for="(item, CategoryIndex) in ProductCategory">
                <view
                  :id="`Category_${CategoryIndex}`"
                  :class="[
                    'goods-left-item',
                    CategoryIndex === CategoryId_Index
                      ? 'active-left-item'
                      : '',
                  ]"
                  @click.stop="SelectCategory(CategoryIndex)"
                >
                  <text class="left-item-text">{{ item.categoryName }}</text>
                </view>
              </block>
            </scroll-view>
          </view>
          <view class="goods-right" :style="{ height: '100%' }">
            <template v-if="CloseStatus || ExpiresStatus">
              <view class="close-status">
                <image
                  class="close-img"
                  :src="$handleImageUrl('/close-shop.png')"
                  mode="aspectFit"
                />
                <text class="close-text">当前商家已关</text>
              </view>
            </template>
            <template v-else>
              <scroll-view
                scroll-y="true"
                :style="{ height: '100%' }"
                refresher-enabled
                :refresher-triggered="RefresherTriggeredStatus"
                @refresherrefresh="refresherrefresh"
                @scrolltolower="scrolltolower()"
              >
                <block v-for="(item, index) in ProductList" :key="index">
                  <view
                    class="goods-right-item"
                    @click.stop="SelectGoods(item)"
                  >
                    <view class="right-img">
                      <image
                        class="goods-img"
                        :src="item.coverImage + '?x-oss-process=style/w_150'"
                        mode="aspectFill"
                      />
                    </view>
                    <view class="right-content">
                      <view class="content-name two-row">{{ item.title }}</view>
                      <view class="content-sales"
                        >月销 {{ item.showSales }}</view
                      >
                      <view class="content-statistics">
                        <view class="price one-row">
                          <text class="price-tag">￥</text>
                          <text class="price-num">{{ item.minSalePrice }}</text>
                          <text class="primeval-price"
                            >￥{{ item.minMarketPrice }}</text
                          >
                        </view>
                        <GoodsCount
                          @UpdateGoodsNum="getDetails(item.productId)"
                        />
                      </view>
                    </view>
                  </view>
                </block>
                <uv-load-more :status="ProductLoading" />
              </scroll-view>
            </template>
          </view>
        </view>

        <template v-if="cartList.length > 0">
          <CarStatistics :cartList="cartList" />
        </template>
      </template>
      <template v-if="currentTab === 'intro'">
        <view class="store-details">
          <scroll-view class="details-content" scroll-y="true">
            <view class="details-label">
              <text class="iconfont label-icon">&#xe60f;</text>
              <text class="label-text">门店简介</text>
            </view>
            <view class="details-value">{{ shopVo.description || "" }}</view>
            <view class="details-label">
              <text class="iconfont label-icon">&#xe61c;</text>
              <text class="label-text">营业时间：</text>
            </view>
            <view class="details-value">{{ shopVo.businessHours || "" }}</view>
            <view class="details-label">
              <text class="iconfont label-icon">&#xe990;</text>
              <text class="label-text">门店地址：</text>
            </view>
            <view class="details-value">
              <!-- {{ shopVo.provinceName || "" }}
              {{ shopVo.cityName || "" }}
              {{ shopVo.areaName || "" }} -->
              {{ shopVo.address || "" }}
            </view>
          </scroll-view>
        </view>
      </template>
    </view>

    <!-- 规格选择组件 -->
    <skuSelect
      ref="shoppingCartRef"
      :details="goodsDetails"
      @updateShoppingCart="cartListBusinessList(shopVo.businessId)"
    />
  </view>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref, unref, watch } from "vue";
import { onShow } from "@dcloudio/uni-app";
import GoodsCount from "./GoodsCount.vue";
import CarStatistics from "./CarStatistics.vue";
import { getShopProductCategoryApi, getShopProductApi } from "@/api/home.ts";
import { productInfo, cartListBusinessList_Api } from "@/api/shop.js";

const Props = defineProps({
  shopVo: {
    type: Object,
    default: () => {},
  },
  height: {
    type: Number,
    default: 0,
  },
});
const shoppingCartRef = ref(null); // 多规格选择组件
const goodsDetails = ref({});
const scrollHeight = ref(0);

watch(
  () => Props.height,
  (newH) => {
    let num = Math.floor(newH) - uni.upx2px(85);
    scrollHeight.value = num && num > 0 ? num : 0;
  },
  { immediate: true }
);
const getScrollHeight = (cartList) => {
  const isShowCar = cartList.length > 0 ? true : false;
  let h = isShowCar ? scrollHeight.value - uni.upx2px(130) : scrollHeight.value;
  h = h - uni.upx2px(30);
  return (h > 0 ? h : 0) + "px";
};

const cartList = ref([]); // 当前店铺购物车列表数据
// 获取当前店铺购物车列表数据
const cartListBusinessList = (businessId) => {
  cartListBusinessList_Api(businessId)
    .then((res) => {
      if (res.code == 200 && res.data) {
        cartList.value = res.data || [];
      }
    })
    .catch((err) => {
      cartList.value = [];
    });
};

const tabList = [
  {
    lable: "商品",
    value: "goods",
  },
  {
    lable: "商家简介",
    value: "intro",
  },
];
const currentTab = ref<"goods" | "intro">("goods");

const CarInfo = ref(0);
const isCarStatistics = ref(false); // 是否显示购物车统计
// const UpdateCarCount = (item) => {

// 	getDetails(item.productId)
// 	// CarInfo.value = e
// 	// console.log('CarInfo = ', CarInfo.value)
// 	return
// 	isCarStatistics.value = !!unref(CarInfo)

// }
// 获取商品详情
const getDetails = (id) => {
  productInfo(id).then((res) => {
    if (res.code == 200 && res.data) {
      goodsDetails.value = res.data;
      nextTick(() => {
        shoppingCartRef.value.open("加入购物车", goodsDetails.value);
      });
    }
  });
};

const ProductCategory = ref([]); //商品分类
const ShopId = ref(null); // 店铺ID
const CategoryId_Index = ref(0);
const scrollIntoView = ref("a"); // 分类滚动位置
watch(
  () => CategoryId_Index.value,
  () => {
    scrollIntoView.value = `Category_${CategoryId_Index.value}`;
  },
  { immediate: true }
);
/**
 * 获取商品分类
 * businessId:店铺ID
 */
const getShopProductCategory = async (businessId: string) => {
  try {
    ShopId.value = businessId;
    const { data } = await getShopProductCategoryApi(businessId);
    ProductCategory.value = data || [];
    CategoryId_Index.value = 0;
  } catch (error) {
    //TODO handle the exception
  } finally {
    if (unref(ProductCategory).length == 0) {
      ProductLoading.value = "nomore"; // 如果没有数据，则设置加载更多
    } else {
      getShopProduct(CategoryId_Index.value);
    }
  }
};
const SelectCategory = (index) => {
  if (CategoryId_Index.value === index) return;
  CategoryId_Index.value = index;
  getShopProduct(CategoryId_Index.value);
};

/**
 * 获取商品
 */
const Pages = ref({
  pageNum: 0,
  pageSize: 10,
});
const CloseStatus = ref(false); // 是否闭店
const ProductList = ref([]); // 商品列表
const ProductCategoryId = ref(0); // 平台分类ID
const ProductLoading = ref<"loadmore" | "loading" | "nomore">("loading"); //
const getShopProduct = (CategoryIndex) => {
  // console.log('ProductCategory = ', unref(ProductCategory))
  if (unref(ProductCategory).length == 0) return;
  // 已闭店
  if (unref(CloseStatus)) return;
  // 获取当前分类的ID（平台分类ID）
  const CategoryId = unref(ProductCategory)[CategoryIndex].categoryId;
  if (!CategoryId && CategoryId !== 0) return;
  // 新激活的分类，初始化数据
  if (CategoryId !== unref(ProductCategoryId)) {
    Pages.value.pageNum = 0;
    ProductList.value = [];
  }
  ProductLoading.value = "loading";
  nextTick(() => {
    // 记录当前选择的分类对应的平台分类ID
    ProductCategoryId.value = CategoryId;
    Pages.value.pageNum += 1;
    try {
      const Parmas = {
        ...unref(Pages),
        ProductCategoryId: unref(ProductCategoryId),
        businessId: unref(ShopId),
        productUseType: 0
      };
      setTimeout(async () => {
        const { rows, total } = await getShopProductApi(Parmas);
        console.log("total = ", total);
        // 当前获取结果对应的平台分类ID与记录的一致时，（防止多次连续请求导致数据错乱）
        if (Parmas.ProductCategoryId === unref(ProductCategoryId)) {
          ProductList.value = ProductList.value.concat(rows || []);
          if (unref(ProductList).length < total) {
            ProductLoading.value = "loadmore";
          } else {
            ProductLoading.value = "nomore";
          }
        }
      }, 100);
    } catch (error) {
      if (Parmas.ProductCategoryId === unref(ProductCategoryId)) {
        ProductLoading.value = "nomore";
      }
    } finally {
    }
  });
};
const ExpiresStatus = ref(false);
watch(
  () => Props.shopVo,
  (newVo) => {
    const { businessId, closeStatus, expiresStatus } = Props.shopVo || {};
    CloseStatus.value = closeStatus;
    ExpiresStatus.value = expiresStatus;
    if (businessId) {
      getShopProductCategory(businessId);
      cartListBusinessList(businessId);
    }
  },
  { immediate: true, deep: true }
);

const RefresherTriggeredStatus = ref<Boolean>(false); // 下拉刷新状态
// 下拉刷新 ， 选中上一级分类
const refresherrefresh = () => {
  if (ProductLoading.value === "loading") return;
  RefresherTriggeredStatus.value = false;
  if (RefresherTriggeredStatus.value) return;
  RefresherTriggeredStatus.value = true;
  nextTick(() => {
    RefresherTriggeredStatus.value = false;
    if (unref(CategoryId_Index) > 0) {
      CategoryId_Index.value -= 1;
      getShopProduct(unref(CategoryId_Index));
    }
  });
};
// 滚动到底部
const scrolltolower = () => {
  if (ProductLoading.value === "loading") return;
  // 存在更多数据
  if (unref(ProductLoading) === "loadmore") {
    getShopProduct(unref(CategoryId_Index));
  } else if (unref(ProductCategory).length - 1 > unref(CategoryId_Index)) {
    CategoryId_Index.value += 1;
    getShopProduct(unref(CategoryId_Index));
  }
};

const SelectGoods = (item) => {
  console.log("item = ", item);
  // uni.setStorageSync('businessId', item.businessId);
  uni.navigateTo({
    url: `/pages/shop/goodsDetails?id=${item.productId}&businessId=${item.businessId}`,
  });
};

// const GoodsScroll = (e) => {
// 	console.log('GoodsScroll = ',e)
// }
// // 滚动到头部
// const scrolltoupper = () => {
// 	if (ProductLoading.value === 'loading') return;
// 	if (unref(CategoryId_Index) > 0) {
// 		CategoryId_Index.value -= 1;
// 		getShopProduct(unref(CategoryId_Index))
// 	}
// }

defineExpose({ cartListBusinessList });

</script>

<style lang="scss" scoped>
.content-box {
  .tabs {
    width: 100%;
    display: flex;
    align-items: center;
    background-color: #fdeee9;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    height: 85rpx;
    box-sizing: border-box;

    .tab-item {
      width: calc(100% - 420rpx);
      //   flex: 1;
      height: 85rpx;
      line-height: 85rpx;
      flex-shrink: 0;
      text-align: center;
      font-size: 34rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #1a1a1a;
      position: relative;
      box-sizing: border-box;
      .tab-icon {
        width: 426rpx;
        height: 94rpx;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
      }
      .tab-text {
        position: relative;
        z-index: 2;
      }
    }
    .tab-item.active-pr {
      padding-right: 64rpx;
    }
    .tab-item.active-pl {
      padding-left: 64rpx;
    //   .tab-icon {
    //     height: 96rpx;
    //   }
    }
    .tab-item.active-tab-item {
      width: 420rpx;
      flex-shrink: 0;
      //   background-color: #fff;
      // clip-path: polygon(0% 0%, 95% 0%, 95.5% 3%, 96% 6%, 96.5% 9%, 94% 12%, 95% 15%, 96% 60%, 97% 70%, 98% 80%, 99% 90%, 100% 100%, 0% 100%);
      // /* 这将创建一个波浪形的效果 */
      // clip-path: path('M0,0 L200,0 L200,80 Q80,65, 180,60 L0,60 Z');
      // clip-path: path("M0 100 Q50 0, 100 100 T200 100 T300 100 V200 H0 Z");
    }
  }

  .scroll-content {
    width: 100%;
    background-color: #fff;
    padding-top: 30rpx;
    box-sizing: border-box;

    .goods-box {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .goods-left {
        width: 160rpx;
        height: 100%;
        background: #f4f4f4;

        .goods-left-item {
          width: 160rpx;
          min-height: 98rpx;
          padding: 25rpx 20rpx;
          box-sizing: border-box;

          .left-item-text {
            display: inline-flex;
            align-items: center;
            width: 100%;
            min-height: 48rpx;
            position: relative;
            font-size: 28rpx;
            font-family: PingFang SC, PingFang SC-Regular;
            font-weight: 400;
            color: #4d4d4d;
            text-align: center;

            &:before {
              content: "";
              position: absolute;
              left: -20rpx;
              top: 0;
              width: 10rpx;
              height: 100%;
              background-color: transparent;
              border-radius: 5rpx;
            }
          }
        }

        .active-left-item {
          background-color: #fff;
          border-radius: 20rpx 0rpx 0rpx 20rpx;

          .left-item-text {
            font-size: 30rpx;
            font-family: PingFang SC, PingFang SC-Bold;
            font-weight: 700;
            color: #1a1a1a;

            &:before {
              background-color: #eb5153;
            }
          }
        }
      }

      .goods-right {
        overflow: hidden;
        width: calc(100% - 160rpx);
        padding: 0 24rpx;
        background-color: #fff;

        .goods-right-item {
          width: 100%;
          padding: 30rpx 0;
          display: flex;
          flex-direction: row;
          align-items: center;

          &:first-child {
            padding-top: 0;
          }

          .right-img {
            flex-shrink: 0;
            width: 200rpx;
            height: 200rpx;

            .goods-img {
              width: 100%;
              height: 100%;
              border-radius: 30rpx;
            }
          }

          .right-content {
            // width: ;
            flex: 1;
            overflow: hidden;
            padding-left: 18rpx;

            .content-name {
              height: 84rpx;
              font-size: 28rpx;
              font-family: PingFang SC, PingFang SC-Bold;
              font-weight: 700;
              text-align: left;
              color: #1a1a1a;
              line-height: 42rpx;
            }

            .content-sales {
              font-size: 24rpx;
              font-family: PingFang SC, PingFang SC-Regular;
              font-weight: 400;
              color: #666666;
            }

            .content-statistics {
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              align-items: baseline;

              .price {
                display: flex;
                flex-direction: row;
                align-items: baseline;
                overflow: hidden;

                .price-tag {
                  font-size: 24rpx;
                  color: #da4f4f;
                }

                .price-num {
                  font-size: 34rpx;
                  color: #da4f4f;
                  // font-family: 汉真广标, 汉真广标-regular;
                }

                .primeval-price {
                  padding-left: 9rpx;
                  font-size: 22rpx;
                  font-family: PingFang SC, PingFang SC-Regular;
                  font-weight: 400;
                  text-decoration: line-through;
                  color: #666666;
                }
              }
            }
          }
        }
      }
    }
  }

  .store-details {
    height: 100%;

    .details-content {
      height: 100%;
      padding: 0 30rpx;
      box-sizing: border-box;

      .details-label {
        color: #1a1a1a;
        line-height: 40rpx;

        .label-icon {
          font-size: 30rpx;
          width: 36rpx;
          display: inline-block;
        }

        .label-text {
          font-size: 28rpx;
          font-family: PingFang SC, PingFang SC-Bold;
          font-weight: 700;
        }
      }

      .details-value {
        font-size: 24rpx;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #666666;
        line-height: 40rpx;
        padding: 10rpx 0 30rpx 36rpx;
        box-sizing: border-box;
      }
    }
  }
}

.close-status {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .close-img {
    width: 257rpx;
    height: 152rpx;
  }

  .close-text {
    padding-top: 3rpx;
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #999999;
  }
}
</style>
