<template>
  <Theme>
    <view class="wrap">
      <Navbar
        :bgColor="
          scrollTop >= tabInitTop || activeNum == 1
            ? 'var(--light)'
            : 'transparent'
        "
        fixed
      >
        <template #left>
          <view class="nav_left">
            <up-icon name="arrow-left" size="16" color="var(--light)"></up-icon>
          </view>
        </template>
        <template #right>
          <view class="nav_right">
            <view class="nav_item" @click.stop="collectClick">
              <up-icon
                name="star-fill"
                size="16"
                :color="isCollect ? 'var(--primary)' : 'var(--light)'"
              ></up-icon>
            </view>
            <view class="nav_item" @click.stop="shareClick">
              <up-icon name="share" size="16" color="var(--light)"></up-icon>
            </view>
          </view>
        </template>
      </Navbar>

      <view class="content" id="conts" ref="contRef">
        <scroll-view
          scroll-with-animation
          :scroll-into-view="scrollId"
          :scroll-y="true"
          class="scroll-view"
        >
          <view id="scroll_item_0" class="scroll_item0">
            <view id="tabInit" v-if="activeNum == 0">
              <view class="swiper">
                <Swiper
                  :listArr="swiperImgs"
                  autoplay
                  height="100%"
                  circular
                  indicator-dots
                  indicator-active-color="var(--black)"
                  indicator-color="var(--light)"
                  urlName="url"
                  borderRadius="0"
                />
              </view>
            </view>
            <view class="info_wrapper">
              <view class="price_wrapper">
                <view class="texts">
                  <rich-text
                    :nodes="MoneyAbouthtml(detail.price, true)"
                  ></rich-text>
                  <text class="original-price" v-if="detail.originalprice"
                    >{{ symbol.symbol }}{{ detail.originalprice }}</text
                  >
                </view>

                <view class="sale_right" v-if="detail.sale">
                  <trans _t="总销量" /> {{ detail.sale }}
                </view>
              </view>
              <view class="info_name">{{
                detail.title || detail.goodsName
              }}</view>
            </view>
          </view>
          <view id="scroll_item_1" class="scroll_item1" v-if="activeNum == 0">
            <view
              class="detail_wrapper"
              v-if="detail.propArr && detail.propArr.length"
            >
              <view class="module_title">
                <trans _t="规格参数" />
              </view>
              <Norm :item="detail.propArr" />
            </view>
            <view class="detail_wrapper" v-if="detail.desc">
              <view class="module_title">
                <trans _t="产品详情" />
              </view>
              <view class="desc_imgs">
                <rich-text class="desc_cont" :nodes="detail.desc"></rich-text>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="footer_btns">
          <view class="btn_wrapper">
            <view class="btn btn_add" @click="add('add')">
              <trans _t="加入购物车" />
            </view>
            <view class="btn btn_buy" @click="add('buy')">
              <trans _t="立即购买" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <quantityPopup :detail="detail" ref="quantityRef" />
  </Theme>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import Navbar from "@/components/navbar";
import { SELLER_GOODS_INFO } from "@/api";
import { onLoad, onPageScroll } from "@dcloudio/uni-app";
import { t } from "@/locale";
import {
  useShopStore,
  useSystemStore,
  useTabbarStore,
  useCacheStore,
} from "@/store";
import Swiper from "@/components/swiper";
import {
  systemInfo,
  openUrl,
  refresh,
  query,
  MoneyAbouthtml,
  Toast,
  TimeOut,
  urlStrToArr,
} from "@/utils";
import Tab from "@/components/tabs";
import ImageGrid from "@/components/ImageGrid.vue";
import selectSpec from "@/pages/shop/components/select_spec";
import Norm from "@/pages/shop/components/norm";
import quantityPopup from "./components/quantity_popup";

const useShop = useShopStore();
const useSystem = useSystemStore();
const useTabbar = useTabbarStore();
const useCache = useCacheStore();

const goodsId = ref(0);
const detail = ref({});
const activeNum = ref(0);
const isCollect = ref(false);
const selectRef = ref(null);
const quantityRef = ref(null);

const tabInitTop = ref(0);
const initTab = ref(0);
const scrollTop = ref(0);
const tabList = ["详情", "评论"];
const contRef = ref(null);
const scrollId = ref("scroll_item_0");

const swiperImgs = computed(() => {
  if (detail.value.item_imgs && detail.value.item_imgs.length) {
    return detail.value.item_imgs.slice(0, 6);
  }
  if (detail.value.picurl) {
    return [{ url: detail.value.picurl }];
  }
  return [];
});

const currency = computed(() => useSystem.getCurrency);
const symbol = computed(() => useSystem.getSymbol);

const top = systemInfo().statusBarHeight || 0;

const tabClick = (item, index) => {
  activeNum.value = index;
  getHeight("scroll_item_" + index);
  let newTop =
    index == 0
      ? 0
      : index == 1
      ? height0.value - 44 - top - initTab.value
      : height0.value + height1.value - 44 - top - initTab.value;
  uni.pageScrollTo({
    scrollTop: newTop,
    duration: 300,
  });
};

const height0 = ref(0);
const height1 = ref(0);

const getHeight = async (id) => {
  let ids = "#" + id;
  try {
    const res = await query(ids);
    if (id == "scroll_item_0" && !height0.value) {
      height0.value = res.height;
    }
    if (id == "scroll_item_1" && !height1.value) {
      height1.value = res.height;
    }
  } catch (error) {}
};

const collectClick = () => {
  // TODO: 实现收藏功能
  Toast("收藏功能待实现");
};

const shareClick = () => {
  // TODO: 实现分享功能
  Toast("分享功能待实现");
};

const add = (type) => {
  quantityRef.value && quantityRef.value.open(type);
};

const getDetail = async () => {
  const params = {
    id: goodsId.value,
  };

  try {
    const res = await SELLER_GOODS_INFO(params);
    detail.value = res.data;
    isCollect.value = res.data.isCollect ? true : false;

    if (res.data.skudesc) {
      detail.value.propArr = parseSkuDesc(res.data.skudesc);
    }
  } catch (error) {
    Toast(error.msg);
  }
};

// 解析skudesc字段，转换为规格参数数组
const parseSkuDesc = (skudesc) => {
  if (!skudesc) return [];

  const specs = skudesc.split(";");
  const propArr = [];

  specs.forEach((spec) => {
    if (spec.trim()) {
      const [name, value] = spec.split(":");
      if (name && value) {
        propArr.push({
          name: name.trim(),
          value: value.trim(),
        });
      }
    }
  });

  return propArr;
};

onPageScroll((e) => {
  scrollTop.value = e.scrollTop;
});

onLoad((options) => {
  const { id = 0 } = options;
  goodsId.value = id;
});

onMounted(() => {
  nextTick(async () => {
    getDetail();
    const scrollItem0 = await query("#tabInit");
    tabInitTop.value = scrollItem0.height;
    const scrollTab = await query("#tab");
    initTab.value = scrollTab.height;
  });
});
</script>

<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  background-color: var(--bg);
  min-height: 100vh;

  .nav_left {
    background: rgba(0, 0, 0, 0.6);
    border-radius: 10rpx;
    width: 50rpx;
    height: 50rpx;
    .flex_center();
  }

  .nav_right {
    .flex_center();
    gap: 12rpx;

    .nav_item {
      width: 50rpx;
      height: 50rpx;
      .flex_center();
      background: rgba(0, 0, 0, 0.6);
      color: var(--light);
      border-radius: 10rpx;
    }
  }

  .tab {
    z-index: 11;
    background-color: var(--light);
    &.active_tab {
      position: fixed;
      top: 44px;
      left: 0;
      right: 0;
    }
  }

  .content {
    padding-bottom: 148rpx;
    margin-top: -44px;

    .scroll_item0 {
      /deep/ .swiper_list {
        object-fit: cover;
        aspect-ratio: 1 / 1;
      }

      .swiper {
        position: relative;

        /deep/ .uni-swiper-dots-horizontal {
          bottom: 40px;
        }
      }

      .info_wrapper {
        background-color: var(--light);
        padding: 24rpx;
        border-radius: 60rpx 60rpx 0 0;
        margin-top: -30px;
        position: relative;

        .price_wrapper {
          .hor(space-between);
          align-items: center;
          height: 60rpx;
          font-weight: bold;
          color: var(--red);
          .size(40rpx);
          margin-bottom: 24rpx;

            .texts {
              display: flex;
              align-items: baseline;
              line-height: 1;
              margin-left: 8rpx;

            /deep/ div {
              .ver(baseline);

              .decimal {
                .size(24rpx);
              }
            }
            .original-price {
              margin-left: 6rpx;
              font-size: 24rpx;
              color: var(--bor-color1);
              text-decoration: line-through;
            }
          }

          .sale_right {
            .size(22rpx);
            color: var(--text);
          }
        }

        .info_name {
          .size(28rpx);
          line-height: 48rpx;
          font-weight: 700;
          color: var(--text);
        }
      }

      .service_wrapper {
        padding: 24rpx;
        background-color: var(--inputBg);

        .spec_title {
          .size(28rpx);
          font-weight: 700;
          color: var(--text);
          line-height: 60rpx;
        }

        .spec_info {
          border-radius: 16rpx;
          display: grid;
          gap: 10rpx;
          grid-template-columns: repeat(2, 1fr);
          margin-top: 16rpx;
          padding: 16rpx 0;
          color: var(--text-02);
          .size(24rpx);

          .spec_item {
            .ver();

            .spec_value {
              align-items: center;
              color: var(--text);
              display: inline-flex;
              font-weight: 500;
              margin-left: 12px;
            }
          }
        }
      }
    }

    .scroll_item1 {
      .detail_wrapper {
        background-color: var(--light);
        padding: 24rpx;
        margin-top: 24rpx;

        .module_title {
          .size(28rpx);
          font-weight: 700;
          line-height: 60rpx;
          color: var(--text);
        }

        .desc_imgs {
          .desc_cont {
            /deep/ div {
              div {
                width: 100% !important;

                div {
                  width: 100% !important;
                }
              }

              img {
                max-width: 100% !important;
                width: 100%;
                height: auto;
                display: block;
              }
            }
          }

          /deep/ img {
            max-width: 100%;
          }
        }

        .spec_list {
          .spec_item {
            display: flex;
            justify-content: space-between;
            padding: 16rpx 0;
            border-bottom: 1px solid var(--border);

            .spec_label {
              color: var(--text-02);
              .size(24rpx);
            }

            .spec_value {
              color: var(--text);
              .size(24rpx);
              font-weight: 500;
            }
          }
        }
      }
    }

    .scroll_item2 {
      padding: 24rpx 16rpx;

      .title {
        font-weight: 700;
        line-height: 60rpx;
        .size(28rpx);
      }

      .comment_item {
        width: 100%;
        margin-top: 16rpx;
        padding: 12rpx;
        border: 1px solid var(--border);
        border-radius: 10rpx;
        .comment_text {
          margin-top: 6rpx;
          color: var(--text);
        }
      }

      .tips {
        text-align: center;
        font-size: 28rpx;
        color: #333;
      }
    }

    .footer_btns {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 10;
      padding: 12rpx 24rpx;
      background-color: var(--light);
      .flex_center();
      padding-bottom: calc(12rpx + env(safe-area-inset-bottom));
      padding-bottom: calc(12rpx + constant(safe-area-inset-bottom));
      box-sizing: border-box;

      .btn_wrapper {
        flex: 1;
        .ver();
        column-gap: 64rpx;

        .btn {
          flex: 1;
          .size(28rpx);
          height: 96rpx;
          line-height: 28rpx;
          padding: 8rpx 16rpx;
          .flex_center();
          border: 2px solid var(--black);
          color: var(--black);
          border-radius: 20rpx;
          font-weight: bold;
        }

        .btn_buy {
          background-color: var(--light);
        }

        .btn_add {
          background-color: var(--black);
          color: var(--light);
        }
      }
    }
  }
}
</style>