<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">
            <!-- #ifdef H5 -->
            <view class="nav_item" @click.stop="copyPageUrl">
              <i class="icon-font icon-link"></i>
            </view>
            <!-- #endif -->
            <view class="nav_item" @click.stop="collectClick">
              <up-icon
                name="star-fill"
                size="16"
                :color="isCollect ? 'var(--primary)' : 'var(--light)'"
              ></up-icon>
            </view>
            <!-- #ifdef APP-PLUS -->
            <view class="nav_item" @click.stop="copyPageUrl">
              <image src="../../static/share.png" class="img"></image>
            </view>
            <!-- #endif -->
          </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 class="collect" @click.stop="collectClick">
                <i class="icon-font" :class="isCollect ? 'icon-collected' : 'icon-not-collected'"></i>
              </view>
              <view class="swiper_text" @click.stop="search">
                <i class="icon-font icon-search"></i>
                <trans _t="搜索类似产品" />
              </view> -->
              </view>
            </view>
            <view class="info_wrapper">
              <view class="price_wrapper">
                <rich-text
                  class="texts"
                  :nodes="MoneyAbouthtml(detail.price, true)"
                ></rich-text>
                <view class="sale_right" v-if="detail.saleCount">
                  <trans _t="总销量" /> {{ detail.saleCount }}
                </view>
              </view>
              <view class="info_name">{{ detail.title }}</view>
              <!-- <view class="active_wrapper">
                <view class="active_item" v-for="item, index in activeList" :key="index" @click="activeClick(index)">
                  <i class="icon-font" :class="item.icon"></i>
                  <trans :_t="item.text" />
                </view>
              </view> -->
            </view>
            <view
              class="tab"
              id="tab"
              :style="{ top: top + 44 + 'px' }"
              :class="{ active_tab: scrollTop >= tabInitTop || activeNum == 1 }"
            >
              <Tab :active="activeNum" :tabList="tabList" @confirm="tabClick" />
            </view>
            <view class="service_wrapper" v-if="activeNum == 0">
              <view class="spec_title">
                <trans _t="购买记录" />
              </view>
              <view class="spec_info">
                <view class="spec_item">
                  <trans _t="销售量" class="spec_label" />
                  <text class="spec_value">--</text>
                </view>
                <view class="spec_item">
                  <trans _t="平均送达时间" class="spec_label" />
                  <text class="spec_value">--</text>
                </view>
                <view class="spec_item">
                  <trans _t="重量（克）" class="spec_label" />
                  <text class="spec_value">--</text>
                </view>
                <view class="spec_item">
                  <trans _t="尺寸" class="spec_label" />
                  <text class="spec_value">--</text>
                </view>
              </view>
            </view>
          </view>
          <view id="scroll_item_1" class="scroll_item1" v-if="activeNum == 0">
            <!-- <view class="shpp_wrapper" @click="endShop">
              <view class="shop_info">
                <view class="info_left">
                  <image
                    :src="`../../static/shop/icon_${channels}.png`"
                    class="info_icon"
                  ></image>
                  {{ detail.nick || "" }}
                </view>
                <view class="btn">
                  <trans _t="进入商店" />
                </view>
              </view>
            </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>
                <!-- <image :src="item" mode="widthFix" class="_img" v-for="item, index in detail.desc_img" :key="index">
                </image> -->
              </view>
            </view>
            <view
              class="detail_wrapper"
              v-if="detail.propArr && detail.propArr.length"
            >
              <view class="module_title">
                <trans _t="规格参数" />
              </view>
              <Norm :item="detail.propArr" />
            </view>
          </view>
          <view id="scroll_item_2" class="scroll_item2" v-if="activeNum == 1">
            <view class="title">
              <trans _t="用户评论" />
            </view>
            <template v-if="detail.commentLists && detail.commentLists.length">
              <view
                v-for="(item, index) in detail.commentLists"
                :key="index"
                class="comment_item"
              >
                <view class="comment_text">{{ item.content }}</view>
                <ImageGrid
                  :images="urlStrToArr(item.images)"
                  isSeeLarge
                  v-if="item.images && item.images.length"
                />
              </view>
            </template>
            <trans _t="无数据" class="tips" v-else />
          </view>
          <!-- <view id="scroll_item_2" class="scroll_item2">
            <view class="title">
              <trans _t="你可能会喜欢" />
            </view>
          </view> -->
        </scroll-view>
        <view class="footer_btns">
          <!-- <view class="icon_wrapper">
            <view class="icon_item">
              <i class="icon-font icon-discord"></i>
            </view>
            <trans _t="加入" />
          </view> -->
          <view class="btn_wrapper">
            <view class="btn btn_add" @click="add('add')">
              <trans _t="加入购物车" />
            </view>
            <view class="btn btn_buy" @click="add('buy')" v-if="isFrees == 0">
              <trans _t="立即购买" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <selectSpec
      :sku="detail.sku"
      :channel="channels"
      :goods_id="goods_ids"
      :props_spec="detail.props_spec"
      :pic_url="detail.pic_url"
      :price="detail.price"
      :isFree="isFrees"
      ref="selectRef"
    />
    <floatButton bottom="120px" right="0" @onConfirm="goShop" />

    <ShareDialog ref="shareDialogRef"></ShareDialog>

    <RightCartDrawer ref="cartDrawerRef" />
  </Theme>
</template>
<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import Navbar from "@/components/navbar";
import { SHOP_DETAIL, SHOP_SEARCH_SIMILAR, SHOP_USER_COLLECT } 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 Norm from "./components/norm";
import floatButton from "@/components/floatButton";
import Tab from "@/components/tabs";
import selectSpec from "./components/select_spec";
import ShareDialog from "@/components/ShareDialog.vue";
import RightCartDrawer from "./components/RightCartDrawer.vue";
import ImageGrid from "@/components/ImageGrid.vue";

const cartDrawerRef = ref(null);

const useShop = useShopStore();
const useSystem = useSystemStore();
const useTabbar = useTabbarStore();
const useCache = useCacheStore();
const channels = ref(0);
const goods_ids = ref(0);
const searchText = ref("");
const optionsList = ref(["拍照", "相册"]);
const popoverRef = ref(null);
const selectRef = ref(null);
const shareDialogRef = ref(null);
const detail = ref({});
const searchValue = ref("");
const activeNum = ref(0);
const cartNum = computed(() => useShop.getCartNum);
const isFrees = ref(0);

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 height0 = ref(0);
const height1 = ref(0);
const height2 = ref(0);
const similarArr = ref([]);
const activeList = [
  {
    icon: "icon-link",
    text: "产品链接",
  },
  {
    icon: "icon-refresh",
    text: "刷新",
  },
  {
    icon: "icon-share",
    text: "分享",
  },
];

const swiperImgs = computed(() => (detail.value.item_imgs || []).slice(0, 6));

const isCollect = ref(false);
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 leftClick = () => {
//   uni.navigateTo({ url: '/pages/setting/language_currency' })
// }

const activeClick = (index) => {
  if (index == 0) return openUrl(detail.value.detail_url);
  if (index == 1)
    return refresh(
      `/pages/shop/productDetail?channel=${channels}&goods_id=${goods_ids}`
    );
};

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

const endShop = () => {
  uni.navigateTo({
    url: `/pages/shop/merchants?channel=${channels.value}&shop_id=${detail.value.shop_id}&seller_id=${detail.value.seller_id}&title=${detail.value.nick}`,
  });
};

const collectClick = () => {
  setCollect();
};

const copyPageUrl = () => {
  let url = "";
  // #ifdef H5
  url = window.location.href;
  // #endif

  // #ifdef APP-PLUS
  url = `https://vavabuy.net/#/pages/shop/productDetail?channel=${channels.value}&goods_id=${goods_ids.value}&search=${searchText.value}`;

  console.log("url", url);
  // #endif
  uni.setClipboardData({
    data: url,
    success: () => {
      Toast(t("链接已复制"));
    },
  });
};

// App 端分享
const handleAppShare = () => {
  shareDialogRef.value && shareDialogRef.value.open();
};

const search = () => {};

const goShop = () => {
  cartDrawerRef.value && cartDrawerRef.value.open();
};

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 searchConfirm = (value) => {
  uni.navigateTo({ url: `/pages/index/products?searchText=${value}` });
};

const getDetail = async () => {
  const params = {
    channel: channels.value,
    goods_id: goods_ids.value,
  };
  const shopDetail = useCache.getShopDetail({
    ...params,
    search: searchText.value,
  });
  if (shopDetail) {
    detail.value = shopDetail;
    isCollect.value = shopDetail.isCollect ? true : false;
    return;
  }
  try {
    const res = await SHOP_DETAIL(params);
    detail.value = res.data;
    isCollect.value = res.data.isCollect ? true : false;
    useCache.setDetail({
      ...params,
      detail: res.data,
      search: searchText.value,
    });
    // nextTick(() => {
    // getSimilar(res.data.sample_id);
    // })
  } catch (error) {
    if (error.ret == 0) {
      Toast(t("商品已下架")).then(() => {
        TimeOut(() => {
          uni.navigateBack();
          // uni.navigateTo({ url: "/pages/index/products?channel=1" });
        });
      });
    }
  }
};

const setCollect = async () => {
  try {
    const res = await SHOP_USER_COLLECT({
      channel: channels.value,
      type: "good",
      goods_id: goods_ids.value,
      seller_id: detail.value.seller_id,
      title: detail.value.title,
      pic_url: detail.value.pic_url,
      price: detail.value.price,
    });
    nextTick(() => {
      isCollect.value = res.data.collect ? true : false;
      useCache.changeShopCollect({
        channel: channels.value,
        goods_id: goods_ids.value,
        isCollect: res.data.collect,
      });
    });
  } catch (error) {
    Toast(error.msg);
  }
};

const getSimilar = async (sample_id) => {
  try {
    const res = await SHOP_SEARCH_SIMILAR({
      sample_id,
      goods_id: goods_ids.value,
    });
  } catch (error) {}
};

onPageScroll((e) => {
  scrollTop.value = e.scrollTop;
  // if (!height0.value) {
  //   getHeight("scroll_item_0");
  // }
  // if (!height1.value) {
  //   getHeight("scroll_item_1");
  // }
  // const contTop = (e.scrollTop + 44 + top + initTab.value).toFixed(2) - 0;
  // const height0Top = height0.value.toFixed(2) - 0;
  // const height1Top = height1.value.toFixed(2) - 0;
  // if ((e.scrollTop == 0 || e.scrollTop > 0) && contTop < height0Top) {
  //   activeNum.value = 0;
  // } else if (
  //   (contTop == height0Top || contTop > height0Top) &&
  //   contTop < height1Top
  // ) {
  //   activeNum.value = 1;
  // } else {
  //   activeNum.value = 2;
  // }
});

onLoad((options) => {
  const { channel = 0, goods_id = 0, search = "", isFree = 0 } = options;
  channels.value = channel;
  goods_ids.value = goods_id;
  searchText.value = search;
  isFrees.value = isFree;
});

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;

  // /deep/ .u-navbar__content {
  //   .u-navbar__content__left,
  //   .u-navbar__content__right {
  //     position: unset;
  //     padding: 0;
  //   }
  // }

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

  .nav_center {
    flex: 1;

    .icon-camera {
      color: #adb8cc;
      font-size: 56rpx;
    }
  }

  .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;

      .icon-font {
        .size();
      }

      .img {
        width: 26rpx;
        height: 26rpx;
        display: block;
      }
    }
  }

  .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;

        .collect {
          position: absolute;
          right: 12px;
          top: 12px;
          width: 32px;
          height: 32px;
          background-color: #dfe3eb;
          border-radius: 4px;
          box-shadow: 0 0.8px 8px #0000001a;
          z-index: 10;
          opacity: 0.8;
          .flex_center();

          .icon-font {
            .size(20px);
            color: var(--primary);
          }
        }

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

        .swiper_text {
          position: absolute;
          right: 12px;
          bottom: 12px;
          z-index: 10;
          background-color: #dfe3eb;
          border-radius: 64rpx;
          box-shadow: 0 0.8px 8px #0000001a;
          z-index: 10;
          opacity: 0.8;
          padding: 0 16rpx;
          color: var(--primary);
          height: 64rpx;
          .flex_center();
          min-width: 240rpx;
          .size(24rpx);
          font-weight: 700;

          .icon-search {
            .size();
          }
        }
      }

      .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 {
            margin-left: 8rpx;

            .icon {
              margin-right: 6rpx;
            }

            .icon2 {
              margin: 0 8rpx;
            }

            /deep/ div {
              .ver(baseline);

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

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

        .active_wrapper {
          height: 40rpx;
          margin-top: 24rpx;
          .ver();
          column-gap: 16rpx;

          .active_item {
            color: var(--primary);
            .size(24rpx);
            .ver();

            .icon-font {
              margin-right: 8rpx;
              .size();
            }
          }
        }
      }

      .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 {
      .shpp_wrapper,
      .detail_wrapper {
        background-color: var(--light);
        padding: 24rpx;
        margin-top: 24rpx;
      }

      .shpp_wrapper {
        .shop_info {
          .flex_position(space-between);

          .info_left {
            max-width: 520rpx;
            .ver();
            .size(28rpx);
            color: var(--text);
            font-weight: 700;
            line-height: 40rpx;

            .info_icon {
              width: 48rpx;
              height: 48rpx;
              display: block;
              margin-right: 8rpx;
            }
          }

          .btn {
            border-radius: 48rpx;
            padding: 12rpx 30rpx;
            color: var(--black);
            border: 1px solid var(--black);
            .size(24rpx);
          }
        }
      }

      .detail_wrapper {
        .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%;
          }
        }
      }
    }

    .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;
      // height: 124rpx;
      // .flex_position(space-between);
      padding: 12rpx 24rpx;
      // column-gap: 64rpx;
      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;
      .icon_wrapper {
        .flex_center();
        flex-direction: column;
        color: var(--text);
        .size(24rpx);
        line-height: 40rpx;

        .icon_item {
          background: #425bf8;
          border-radius: 16rpx;
          width: 48rpx;
          height: 48rpx;
          .flex_center();

          .icon-discord {
            color: var(--light);
            .size(40rpx);
          }
        }
      }

      .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>