<template>
  <view class="container">
    <view id="page-top">
      <view class="product">
        <view class="u-bg-fff pb40">
          <view class="pic">
            <swiper
              class="swiper"
              indicator-dots="true"
              :autoplay="true"
              interval="2000"
              duration="1500"
              circular="true"
            >
              <swiper-item v-if="dataForm.videoUrl">
                <j-video
                  class="jvideo"
                  :url="dataForm.videoUrl"
                  width="750rpx"
                  height="620rpx"
                ></j-video>
              </swiper-item>
              <swiper-item v-for="(item, index) in imglist" :key="index">
                <image :src="item" mode="aspectFill"></image>
              </swiper-item>
            </swiper>

            <view class="p-price">
              <view class="pd24 u-flex-center" style="align-items: baseline">
                <view class="u-FFF u-font36">
                  <rich-text
                    :nodes="$mUtil.priceBigSmallTwo(dataForm.minPrice)"
                  ></rich-text>
                </view>
                <text class="discount u-font24 u-ml20 u-del"
                  >￥{{ dataForm.maxSalePrice }}</text
                >
              </view>
              <view class="p-ab u-flex-center">
                <view class="triangle-bottomright"></view>
                <view class="seckill u-text-center u-font28">
                  <!-- active_state 0：未开始 * 1：进行中 * 2：已结束 -->

                  <view class="u-bold" v-if="dataForm.activeTimeState == 1"
                    >距结束</view
                  >

                  <view
                    class="u-bold"
                    v-if="
                      dataForm.activeTimeState == 0 ||
                      dataForm.activeTimeState == 2
                    "
                    >已结束</view
                  >
                  <view v-if="dataForm.activeTimeState != 2">
                    <uv-count-down
                      :time="remainingTime"
                      format="HH:mm:ss"
                    ></uv-count-down>
                  </view>
                </view>
              </view>
            </view>

            <view class="mt10 u-plr30">
              <view>
                <view
                  v-if="shop.platformShop"
                  class="tipsStatus"
                  style="vertical-align: middle"
                  >自营</view
                >
                <text class="u-font34 u-bold u-1A1A1A">{{
                  dataForm.title
                }}</text>
              </view>
              <view class="u-font24 u-mt15 u-999">
                <text
                  >已售
                  <text class="u-FF0000">{{ dataForm.resultSaleNum }}</text
                  >件，仅剩<text class="u-FF0000">{{
                    dataForm.residueStockTotal
                  }}</text
                  >件</text
                >
              </view>
              <!--优惠-->
            </view>
          </view>
        </view>

        <view class="u-bg-fff u-mt10">
          <view class="u-plr30 u-flex-center-sb pt-pb35">
            <view class="u-flex-center" @click="goShop">
              <view>
                <image class="u-avatar104" :src="shop.image"></image>
              </view>
              <view class="u-ml25">
                <view class="u-font28 u-1A1A1A u-bold"
                  >{{ shop.businessName }}
                </view>
                <view class="u-999 u-font24 u-mt5 u-text2">
                  <text
                    class="iconfont"
                    style="color: #fa6138"
                    @click.stop="goLocal"
                    >&#xe990;</text
                  >
                  {{ shop.provinceName }}{{ shop.cityName }}{{ shop.areaName
                  }}{{ shop.address }}
                </view>
              </view>
            </view>
            <view class="iconfont" @click="goShop">&#xe6c7;</view>
          </view>
        </view>
      </view>

      <view class="u-bg-fff u-mt10">
        <view
          class="tab u-flex-center-sa u-font30 u-1A1A1A u-border-one-one"
          :style="[{ top: `calc(${statusBarHeight}px + 44px)` }]"
        >
          <view
            @tap="change(0)"
            class="pb30"
            :class="{ active: isChecked == 0 }"
            >商品详情</view
          >
          <view
            @tap="change(1)"
            class="pb30"
            :class="{ active: isChecked == 1 }"
            >用户评论({{ commentListLength }})</view
          >
        </view>
        <view class="u-mt10">
          <!--商品详情-->
          <view v-if="isChecked == 0">
            <view class="richText ql-editor-box">
              <uv-parse
                class="custom-parse"
                :content="productObj.content"
              ></uv-parse>
            </view>
          </view>

          <!--评论-->
          <view class="u-plr30" v-else>
            <comment :value="commentList"></comment>
          </view>
        </view>
      </view>
    </view>
    <view style="height: 170rpx; background-color: white"></view>
    <view class="bottom-btn u-bg-fff">
      <view class="pt-pb30 u-plr30 u-flex-center-sb">
        <button
          open-type="share"
          class="u-text-center"
          style="line-height: normal; margin-left: 25rpx"
        >
          <view class="iconfont2 u-font44 u-999">&#xe684;</view>
          <view class="u-font28 u-1A1A1A">分享</view>
        </button>

        <!--秒杀按钮-->
        <view class="seckill-btn" v-if="dataForm.activeTimeState == 0">
          <button v-if="ispay" class="u-btn-two u-DCCDA4" @click="notStarted()">
            立即购买
          </button>
        </view>
        <view class="seckill-btn" v-if="dataForm.activeTimeState == 1">
          <button
            v-if="ispay"
            class="u-btn-two u-DCCDA4"
            @click="buy(1, dataForm.id)"
          >
            立即购买
          </button>
        </view>
        <view class="seckill-btn" v-if="dataForm.activeTimeState == 2">
          <button
            v-if="ispay"
            class="u-btn-two u-DCCDA4"
            @click="itSover(1, dataForm.id)"
          >
            立即购买
          </button>
        </view>
      </view>
    </view>

    <!--规格-->
    <uv-popup mode="bottom" ref="specOpenRef" round="30rpx">
      <view class="u-bg-fff spec">
        <view class="u-plr30 flex-sb u-border-one-one pb30">
          <view class="u-flex-center">
            <image
              class="u-goods200"
              :src="skuObj.cover ? skuObj.cover : cover"
            ></image>
            <view class="u-ml20">
              <view class="u-999 u-font24 u-flex-center">
                <view class="u-00BF5A u-font36">
                  <rich-text
                    :nodes="$mUtil.priceBigSmall(skuObj.salePrice || 0)"
                  ></rich-text>
                </view>

                <text class="u-del u-ml15"
                  >￥{{ skuObj.originalSalePrice || 0 }}
                </text>
              </view>
              <view class="u-font22 u-999 u-mt5"
                >活动库存 {{ skuObj.stock }} 件
              </view>
              <view class="u-1A1A1A u-mt25"
                >{{ skuObj.skuSetName ? skuObj.skuSetName : "请选择" }}
              </view>
            </view>
          </view>
          <!-- <view class="iconfont u-999 closeIcon" @click="specOpenRef.close()"
            >&#xe612;</view
          > -->
          <view class="closeIcon" @click.stop="specOpenRef.close()">
            <uv-icon name="close-circle" color="#999999" size="36rpx"></uv-icon>
          </view>
        </view>

        <view>
          <scroll-view scroll-y style="max-height: 30vh">
            <view class="">
              <view
                class="u-mt30"
                v-for="(item, index) in skuTab"
                :key="item.head.id"
              >
                <view class="u-plr30">{{ item.head.name }}</view>
                <view class="u-mt20 u-border-one-one pb30">
                  <view class="u-plr30 u-flex u-flex-warp">
                    <view
                      class="spec-item"
                      :class="childrenItem.flag ? 'activeColor' : ''"
                      @click="chonseSku(index, childrenItem.id)"
                      v-for="childrenItem in item.values"
                      :key="childrenItem.id"
                      >{{ childrenItem.name }}</view
                    >
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>

          <view class="u-plr30 u-mt30">
            <view class="u-flex-center-sb">
              <view>购买数量</view>
              <view class="u-flex-center">
                <uv-number-box
                  v-model="addNumber"
                  disabledInput
                ></uv-number-box>
              </view>
            </view>
            <view class="specOpen-btn">
              <view>
                <button class="u-btn-two" @click="btnBuy(1)">
                  {{ btnName }}
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
    <!--页面加载动画-->
    <ldLoading isFullScreen :active="loading"></ldLoading>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onShareAppMessage, onShow, onLoad } from "@dcloudio/uni-app";
import { seckillActivityProductInfo_Api } from "@/api/seckill.js";
import {
  getBusinessInfoId_Api,
  productInfo,
  shopOrderCommentPage,
} from "@/api/shop.js";

import comment from "@/components/ld-comment/ld-comment.vue";
import utils from "@/util/index.js";

const specOpenRef = ref(null);
// 手机状态栏高度
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight);

const imglist = ref([]); // 详情图片数组
const isChecked = ref(0);
const btnName = ref("");
const dataForm = ref({}); // 商品详情
const shop = ref({}); // 店铺信息
const cover = ref("");
const loading = ref(true);
const skuTab = ref([]); // sku 二位数组
const skuObj = ref({}); // sku 对象
const hasId = ref("");
const addNumber = ref(1);
const commentList = ref([]);
const commentListLength = ref(0);
const productObj = ref({});
const remainingTime = ref(0); // 剩余时间
const ispay = ref(true);

// 生命周期
onShow(() => {});

onLoad((options) => {
  // 当用户进来有缓存店铺

  // 店铺推荐（商品）
  if (options.id) {
    getDetailInfo(options.id);
  }
  if (options.shareId) {
    recordSave(options.shareId, options.id);
  }
});

onShareAppMessage(() => {
  let user = uni.getStorageSync("personal");
  if (res.from === "button") {
    // 来自页面内分享按钮
    console.log(res.target);
  }

  return {
    title: dataForm.value.title,
    imageUrl: dataForm.value.cover,
    path: `/pages/product/goods/seckillGoods?id=${
      dataForm.value.id
    }&share=1&shareId=${user.id || ""}`,
  };
});

// 方法
const notStarted = () => {
  uni.$uv.toast("活动尚未开始");
};

const itSover = () => {
  uni.$uv.toast("活动已结束");
};

const goLocal = () => {
  uni.openLocation({
    latitude: Number(shop.value.txLatitude),
    longitude: Number(shop.value.txLongitude),
    name: shop.value.name,
    address: shop.value.address,
    success: function () {
      console.log("success");
    },
  });
};

const goShop = () => {
  uni.navigateTo({
    url: "/pages/shop/index?businessId=" + dataForm.value.businessId,
  });
};

const recordSave = (shareUserId, productId) => {
  return;
  $http
    .post("/share/record/save", {
      shareUserId: shareUserId,
      productId: productId,
    })
    .then((res) => {});
};

const getDetailInfo = (id) => {
  seckillActivityProductInfo_Api(id).then((res) => {
    loading.value = false;
    if (res && res.code == 200) {
      dataForm.value = res.data;

      if (res.data.activeTimeState == 1) {
        remainingTime.value = res.data.finishTime * 1000 - new Date().getTime();
        // console.log("remainingTime.value", remainingTime.value);
      }
      productInfo(dataForm.value.productId).then((ret) => {
        if (ret && ret.code == 200) {
          productObj.value = ret.data;
          imglist.value = ret.data.images;
          skuTab.value = ret.data.skuTable.map((item) => {
            if (item.values) {
              item.values[0].flag = true;
            }
            return item;
          });
        }
      });

      getBusinessInfoId_Api(dataForm.value.businessId).then((ret) => {
        if (ret.data && ret.code == 200) {
          shop.value = ret.data;
        }
      });

      // return
      shopOrderCommentPage({
        productId: dataForm.value.productId,
        page: 1,
        pageSize: 10,
      }).then((res) => {
        if (res && res.code == 200) {
          commentList.value = res.list;
          commentListLength.value =
            res.list && res.list.length ? res.list.length : 0;
        }
      });
    }
  });
};

const change = (i) => {
  isChecked.value = i;
};

const buy = (i, id) => {
  chonseSku();
  btnName.value = "立即购买";
  specOpenRef.value.open();
};

// 处理选中的
const chonseSku = (index, id) => {
  if (index != null) {
    skuTab.value[index].values.forEach((res) => {
      res.flag = false;
      if (res.id == id) {
        res.flag = true;
      }
    });
  }
  let choseId = [];
  skuTab.value.forEach((res) => {
    res.values.forEach((Key) => {
      if (Key.flag) {
        choseId.push(Key.id);
      }
    });
  });
  let totalId = choseId.sort((a, b) => a - b).join("_");
  totalId = "_" + totalId + "_";
  hasId.value = totalId;
  if (productObj.value.singleSku) {
    if(dataForm.value.productSkuSetList.length>0) skuObj.value = dataForm.value.productSkuSetList[0];
  } else {
    dataForm.value.productSkuSetList.forEach((res) => {
      if (res.skuHashCode == totalId) {
        skuObj.value = res;
      }
    });
  }
};

const btnBuys = () => {
  if (!skuObj.value.id && hasId.value == "") {
    uni.$uv.toast("请选中 sku");
    return false;
  }

  if (
    Number(addNumber.value) > dataForm.value.limitBuyNum &&
    dataForm.value.limitBuyNum != 0
  ) {
    uni.$uv.toast("商品限购" + dataForm.value.limitBuyNum + "件");
    return false;
  }
  if (
    dataForm.value.productSkuSetList.length > 0 &&
    Number(skuObj.value.stock) < Number(addNumber.value)
  ) {
    uni.$uv.toast("商品库存只有" + skuObj.value.stock + "件");
    return false;
  }
  // psotJson();
};

const psotJson = () => {
  let dataJson = {};
  let childArr = [];
  let parendArr = [];
  skuObj.value;

  childArr.push({
    userCartId: 0,
    activityGoodsId: skuObj.value.activityGoodsId,
    productId: dataForm.value.productId,
    num: addNumber.value,
    skuHashCode: skuObj.value.skuHashCode,
  });
  parendArr.push({
    businessId: shop.value.id,
    sourceBusinessId: shop.value.id,
    activityId: dataForm.value.seckillId,
    sponsorActivityId: 0,
    userRemark: "",
    items: childArr,
  });
  dataJson = {
    isCart: false,
    receiptId: null,
    shipment_mode: 0,
    shopOrders: parendArr,
    marketingType: 1,
  };
  uni.setStorageSync("dataJson", dataJson);
  uni.navigateTo({
    url: "../surePay/surePaySechill",
  });
};

const btnBuy = (i) => {
  if (!utils.isLoginTo(true)) {
    btnBuys();
  }
};
</script>

<style lang="scss" scoped>
.pd24 {
  padding: 24rpx;
}

.pd20 {
  padding: 20rpx;
}

.pt20-pb14 {
  padding-top: 20rpx;
  padding-bottom: 14rpx;
}

.pt28-pb18 {
  padding-top: 28rpx;
  padding-bottom: 18rpx;
}

.pb30 {
  padding-bottom: 30rpx;
}

.pb40 {
  padding-bottom: 40rpx;
}

.pb50 {
  padding-bottom: 50rpx;
}

.pt-pb30 {
  padding-top: 30rpx;
  padding-bottom: 30rpx;
}

.pt-pb35 {
  padding-top: 35rpx;
  padding-bottom: 35rpx;
}

.ml54 {
  margin-left: 54rpx;
}

.ml138 {
  margin-left: 138rpx;
}

.br-rd10 {
  border-radius: 10rpx;
}

.br-rd20 {
  border-radius: 20rpx;
}

.stb-btn {
  padding: 8rpx 18rpx;
  border-radius: 10rpx;
}

.br-FF0000 {
  border: 1rpx solid #fa6138;
  border-radius: 24rpx;
  padding: 6rpx 12rpx;
}

.bg-FFF6EE {
  background-color: #fff6ee;
}

.mt80 {
  margin-top: 80rpx;
}

.mt10 {
  margin-top: 10rpx;
}

.product {
  // padding-bottom: 150rpx;
}

.pic {
  width: 100%;
  position: relative;

  .swiper {
    // height: 620rpx;
    height: 100vw;

    video {
      width: 100%;
      // height: 620rpx;
      height: 100vw;
    }

    image {
      width: 100%;
      // height: 620rpx;
      height: 100vw;
    }
  }

  .p-price {
    width: 100%;
    // position: absolute;
    top: 460rpx;
    // background: linear-gradient(90deg,#20a733, #0a824b);
    background: #fa6138;
    border-radius: 20rpx 20rpx 0px 0px;
    position: relative;
    top: -16rpx;

    .discount {
      color: #ffffff;
    }
  }
}

.richText {
  padding: 30rpx;

  ::v-deep img {
    margin-top: 0 !important;
  }
}

//秒杀，拼团样式
.p-ab {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}

.stb-list {
  padding-bottom: 10rpx;
}

.triangle-bottomright {
  width: 0;
  height: 0;
  border-bottom: 105rpx solid #dccda4;
  border-left: 60rpx solid transparent;
}

.seckill {
  background-color: #dccda4;
  color: #fa6138;
  padding: 12rpx 15rpx;
  box-sizing: border-box;
  border-radius: 5rpx 20rpx 0px 0px;
  text-align: center;
  // width: 150rpx;
  &:deep(.uv-count-down__text) {
    color: #3775f6;
    font-size: 24rpx;
  }
}

.seckill-btn {
  width: 76%;
}

.br-284534 {
  border-bottom: 1rpx solid rgba($color: #284534, $alpha: 0.3);
}

.gb-te {
  padding-top: 20rpx;
  padding-bottom: 15rpx;
}

.gb-btn {
  padding: 18rpx 80rpx 8rpx;
  line-height: 30rpx;
}

.btn-bg-dccda4 {
  background: #dccda4;
  border-radius: 48rpx 0rpx 0rpx 48rpx;
}

.btn-bg-00321E {
  background: #0b844a;
  border-radius: 0px 48px 48px 0px;
}

.tab {
  position: sticky;
  top: 0;
  background-color: #fff;
  padding-top: 38rpx;
  z-index: 9;

  .pb30 {
    position: relative;

    &::before {
      content: "";
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translateX(-50%);
      width: 0;
      height: 2px;
      background: #fa6138;
      transition: all 0.3s;
    }

    &.active {
      font-size: 30rpx;
      color: #fa6138;
      font-weight: 700;

      &::before {
        width: 100%;
      }
    }
  }
}

.bottom-btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  z-index: 9;
  border-top: 1rpx solid #e6e6e6;

  .cart {
    position: relative;

    .number {
      position: absolute;
      top: -10rpx;
      left: 45rpx;
      padding: 4rpx 8rpx;
      background-color: #ff0000;
      border: 4rpx solid #ffffff;
      border-radius: 40rpx;
    }
  }

  .cart-btn {
    width: 230rpx;
    height: 85rpx;
    background: #dccda4;
    border-radius: 43rpx 0rpx 0rpx 43rpx;
  }

  .buy-btn {
    width: 230rpx;
    height: 85rpx;
    line-height: 85rpx;
    background: #0b844a;
    border-radius: 0rpx 43rpx 43rpx 0rpx;
  }
}

.flex-sb {
  display: flex;
  justify-content: space-between;
}

//弹窗
.spec {
  border-radius: 18rpx 18rpx 0rpx 0rpx;
  padding-top: 30rpx;
  // max-height: 900rpx;
  overflow-y: auto;

  .spec-item {
    background-color: #f6f6f6;
    border: 1px solid #f6f6f6;
    padding: 12rpx 30rpx;
    margin-bottom: 24rpx;
    font-size: 24rpx;
    color: #1a1a1a;
    border-radius: 4px;
  }

  .activeColor {
    background-color: #e1e6e3;
    border: 1px solid #3775f6;
    color: #fa6138;
    border-radius: 4px;
  }

  .spec-item:not(:last-child) {
    margin-right: 24rpx;
  }

  //减号
  .minus {
    width: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
    background: #dedede;
    border-radius: 8rpx 0rpx 0rpx 8rpx;
  }

  .num {
    width: 74rpx;
    height: 46rpx;
    line-height: 46rpx;
    text-align: center;
    border: 1px solid #dedede;
  }

  //加号
  .plus-sign {
    width: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
    background: #dedede;
    border-radius: 0rpx 8rpx 8rpx 0rpx;
  }

  .specOpen-btn {
    margin-top: 68rpx;
    padding-bottom: 34rpx;

    button {
      background-color: #fa6138;
      color: #ffffff;
    }
  }
}
</style>