<template>
  <view>
    <view class="u-skeleton">
      <block v-if="isFirstLoading">
        <view class="w-750rpx h-750rpx u-skeleton-rect"></view>
        <view class="px-24rpx">
          <view class="w-600rpx h-44rpx u-skeleton-rect mt-20rpx"></view>
          <view class="w-333rpx h-36rpx u-skeleton-rect mt-20rpx"></view>  
          <view class="flex justify-between items-center">
            <view class="w-142rpx h-44rpx u-skeleton-rect mt-20rpx"></view>
          </view>
        </view>
      </block>

      <block>
        <template v-if="!isNull">
          <!-- <cu-swiper v-if="!playShow" indicator-pos="bottomRight" mode="number" height="750" border-radius="0" :list="bannerList">
           <template slot-scope="scope">
              <view class="w-full h-full relative">
                <image
                  v-if="scope.data.type == 'video'"
                  class="w-90rpx h-90rpx translate-center z-40"
                  src="/static/images/icon_play.png"
                  @tap="playVideo"
                />
                <image class="w-full h-full" :src="`${scope.data.image}?x-oss-process=image/resize,w_750/quality,q_90`" mode="aspectFill" />
              </view>
            </template>
          </cu-swiper> -->
          <!--  -->
          <block v-if="!playShow">
            <swiper class="swipers h-750rpx" circular="true" autoplay="true" indicator-dots="true"
              indicator-color="#ffffff" indicator-active-color="#82848a">
              <swiper-item class="flex justify-center w-full h-full" v-for="(item, index) in bannerList" :key="index">
                <view class="w-full h-full relative">
                  <image v-if="item.type == 'video'" class="w-90rpx h-90rpx translate-center z-40"
                    src="/static/images/icon_play.png" @tap="playVideo" />
                  <image class="w-full h-full" :src="`${item.image}?x-oss-process=image/resize,w_750/quality,q_90`"
                    mode="aspectFill" />
                </view>
              </swiper-item>
            </swiper>
          </block>
          <!--  -->
          <view class="relative" v-else>
            <video class="w-750rpx h-750rpx" :enable-progress-gesture="false" id="myVideo" v-if="media.length"
              :src="`${media[0]}`" controls>
              <cover-image @click="pauseVideo" class="absolute right-30rpx top-30rpx w-60rpx h-60rpx"
                src="/static/images/app/app_update_close.png"></cover-image>
            </video>
          </view>

          <!--  -->
          <view class="bg-white px-41rpx boder-b pb-30rpx">
            <view class="text-txBase text-lg pt-base">{{ detail.name }}</view>
            <view class="flex items-center mt-10rpx" v-if="!isPoints">
              <!-- <view class="text-md text-txGray">{{ detail.subtitle }}</view> -->
              <view class="px-13rpx bg-primary bg-opacity-20 text-md rounded-10rpx text-primary"
                v-if="detail.sales_value">成长值:{{ detail.sales_value }}</view>
            </view>
            <view class="flex items-center justify-between">
              <view class="text-txBase text-md flex items-center">
                <view class="text-txSvip" v-if="isPoints">{{ priceText }}</view>
                <view v-else>{{ priceText }}</view>
                <block v-if="showShrough == 'true'">
                  <view class="fontFam line-through text-txGray ml-40rpx text-20rpx">￥{{ detail.market_price }}</view>
                </block>
              </view>
              <view class="flex items-center mt-base">
                <!-- <image class="w-36rpx h-36rpx" src="/static/images/user/collection.png" mode=""></image> -->
                <u-icon :color="products.is_collected ? '#FC8720' : ''" size="36"
                  :name="products.is_collected ? 'star-fill' : 'star'" @tap="onCollection"></u-icon>
                <view class="text-txBase text-md ml-10rpx leading-0">收藏</view>
              </view>
            </view>
            <view class="flex items-center -mt-10rpx" v-if="!isPoints">
              <view class="text-lg -mt-5rpx text-txSvip">￥{{ detail.vip_price }}</view>
              <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
            </view>
          </view>
          <!--  -->
          <view class="flex items-center justify-between bg-white px-41rpx py-32rpx" @tap="showSpecFun(0)"
            v-if="specs.length && !isPoints">
            <view class="flex items-center text-txBase text-md">
              <view class="font-extrabold">选择</view>
              <view class="ml-base">{{ activeSkuText }}</view>
            </view>
            <view>
              <u-icon name="arrow-right" color="#808080" size="32"></u-icon>
            </view>
          </view>

          <!-- 拼团 begin -->
          <!-- <view class="px-45rpx mt-20rpx bg-white">
            <view class="flex justify-between py-20rpx">
              <view>2人在拼单，可直接参与</view>
              <view>更多</view>
            </view>
            <u-line></u-line>
            <view class="flex items-center h-110rpx">
              <view class="rounded-full w-90rpx h-90rpx bg-rose-100"></view>
              <view class="ml-30rpx flex-1">名字</view>
              <view class="text-center w-200rpx">
                <view class="text-24rpx">
                  <text>差</text>
                  <text class="text-hex-e81300 text-30rpx">1</text>
                  <text>人成团</text>
                </view>
                <view class="text-20rpx text-gray-400 mt-10rpx">还剩23:00:00</view>
              </view>
              <view>
                <view class="bg-hex-e81300 rounded-8rpx px-40rpx h-60rpx leading-60rpx text-white text-30rpx">去拼团</view>
              </view>
            </view>
            <u-line></u-line>
            <view class="flex items-center h-110rpx">
              <view class="rounded-full w-90rpx h-90rpx bg-rose-100"></view>
              <view class="ml-30rpx flex-1">名字</view>
              <view class="text-center w-200rpx">
                <view class="text-24rpx">
                  <text>差</text>
                  <text class="text-hex-e81300 text-30rpx">1</text>
                  <text>人成团</text>
                </view>
                <view class="text-20rpx text-gray-400 mt-10rpx">还剩23:00:00</view>
              </view>
              <view>
                <view class="bg-hex-e81300 rounded-8rpx px-40rpx h-60rpx leading-60rpx text-white text-30rpx">去拼团</view>
              </view>
            </view>
          </view> -->
          <!-- <view class="px-45rpx mt-20rpx bg-white">
            <view class="flex py-20rpx">
              <view>我的拼团</view>
              <view class="ml-60rpx">还差2人成团</view>
            </view>
            <view class="flex pb-20rpx items-center">
              <view class="flex rtl">
                <view class="rounded-full w-90rpx h-90rpx bg-hex-cacaca border border-4rpx border-white box-content flex items-center justify-center">
                  <u-icon name="plus" color="#ffffff" size="40"></u-icon>
                </view>
                <view class="rounded-full w-90rpx h-90rpx bg-rose-100 -ml-30rpx border border-4rpx border-white box-content"></view>
                <view class="rounded-full w-90rpx h-90rpx bg-rose-100 -ml-30rpx border border-4rpx border-white box-content"></view>
                <view class="rounded-full w-90rpx h-90rpx bg-rose-100 border border-4rpx border-white box-content"></view>
              </view>
              <view class="flex-1"></view>
              <view class="">
                <view class="bg-hex-e81300 rounded-8rpx px-40rpx h-60rpx leading-60rpx text-white text-30rpx">邀请好友</view>
              </view>
            </view>
          </view> -->
          <!-- 拼团 end -->
          <!-- 砍价 begin-->
          <view class="px-45rpx mt-20rpx bg-white" v-if="detail.is_bargaing">
            <view class="flex py-20rpx"> 邀请好友助力 </view>
            <view class="flex pb-20rpx items-center">
              <view class="flex rtl">
                <view
                  class="rounded-full w-90rpx h-90rpx bg-hex-cacaca border border-4rpx border-hex-fff box-content flex items-center justify-center">
                  <u-icon name="plus" color="#ffffff" size="40"></u-icon>
                </view>
                <view class="rounded-full w-90rpx h-90rpx bg-rose-100 border border-4rpx border-hex-fff box-content"
                  v-for="(item, index) in bargainLogs" :key="index"
                  :class="{ '-ml-30rpx': index != bargainLogs.length - 1 }">
                  <u-avatar :size="90" :src="item.avatar"></u-avatar>
                </view>
              </view>
              <view class="flex-1"></view>
              <view class="">
                <view class="bg-hex-e81300 rounded-8rpx px-40rpx h-60rpx leading-60rpx text-white text-30rpx"
                  @click="$u.routeAuth('/pages/bargain/invite', { skuId: skuId })">邀请好友</view>
              </view>
            </view>
          </view>
          <!-- 砍价 end -->
          <!-- 特点 -->
          <!-- v-if="features.length" -->
          <view v-if="features.length" class="px-30rpx bg-white">
            <view class="pt-32rpx flex">
              <view class="flex-none text-32rpx">服务：</view>
              <ul class="">
                <li class="float-left mr-8rpx" v-for="(item, index) in features" :key="index">
                  <image class="w-28rpx h-28rpx float-left my-4rpx mr-6rpx" :src="item.icon" alt="" srcset="" />
                  {{ item.name }}
                </li>
              </ul>
              <view class="flex-1 flex flex-wrap">
                <view class="flex items-start ml-10rpx" v-for="(item, index) in features" :key="index"> </view>
              </view>
            </view>
            <!-- <swiper class="h-78rpx" :indicator-dots="false" :autoplay="true" vertical>
              <swiper-item v-for="(item, index) in features" :key="index">
                <view class="flex items-center h-full px-46rpx">
                  <image class="w-32rpx h-32rpx" :src="item.icon" mode=""></image>
                  <view class="text-md text-txGray ml-10rpx">{{ item.name }}</view>
                </view>
              </swiper-item>
            </swiper> -->
          </view>

          <view class="h-32rpx bg-white"></view>
          <!-- 评价 -->
          <!-- <view class="bg-white">
        <view class="boder-b flex items-center justify-between py-32rpx px-41rpx text-txBase text-md">
          <view class="font-extrabold">评价（109）</view>
          <view class="flex items-center" @tap="jump('/comment/comment')">
            <view class="text-txGray mr-10rpx">查看全部</view>
            <u-icon name="arrow-right" color="#808080" size="32"></u-icon>
          </view>
        </view>
        <view v-for="(item, index) in 1" :key="index">
          <comment :index="index" :length="3"></comment>
        </view>
      </view> -->
          <!--  -->
          <view class="flex items-center justify-center py-32rpx">
            <view class="w-25rpx h-1rpx bg-txBase"></view>
            <view class="text-xl font-extrabold text-txBase mx-10rpx">商品详情</view>
            <view class="w-25rpx h-1rpx bg-txBase"></view>
          </view>
          <!-- 富文本 -->
          <view class="bg-white">
            <view class="p-base" v-if="attrs.length">
              <u-table align="left" bg-color="transparent">
                <block v-for="(item, index) in attrs" :key="index">
                  <u-tr class="u-tr">
                    <u-td class="u-td">{{ item.name }}</u-td>
                  </u-tr>
                  <u-tr class="u-tr" v-for="(item1, index2) in item.attrs" :key="index2">
                    <u-td width="160rpx" class="u-td">{{ item1.name }}</u-td>
                    <u-td class="u-td">{{ item1.value }}</u-td>
                  </u-tr>
                </block>
              </u-table>
            </view>
            <u-parse :html="detailHtml" style="font-size:0;width: 100%;" :tagStyle="style"></u-parse>
          </view>
          <!-- 购物须知 -->
          <view class="mt-base bg-white">
            <!-- <view class="w-710rpx m-auto bg-txBorder px-base pb-base rounded-10rpx"> -->
            <!-- <view class="text-lg text-txBase font-extrabold pt-10rpx">购物须知</view> -->
            <view class="mt-10rpx text-md text-txGray">
              <u-parse :html="detail.buynote"></u-parse>
            </view>
            <!-- </view> -->
          </view>

          <!-- 分割 -->
          <view class="h-140rpx"></view>
          <!-- 底部导航栏 -->
          <view class="flex items-center fixed right-0 left-0 bottom-0 bottom w-full bg-white shadow cu-bar tabbar">
            <block v-if="isPoints">
              <view class="mx-base bg-bgSubtitle rounded-lg w-full h-66rpx text-center leading-66rpx text-md text-white"
                @click="onDHClick">兑换</view>
            </block>

            <block v-else>
              <view class="w-300rpx flex justify-around ml-20rpx">
                <view class="flex items-center justify-center h-full flex-col flex-1"
                  @tap="$u.routeAuth('/pages/auxiliary_cart/index')">
                  <view class="relative w-48rpx h-48rpx flex justify-center items-center">
                    <image class="w-full h-full" src="/static/images/cart/short-cart.png" mode="scaleToFill" />
                    <view v-if="cartList.length"
                      class="absolute -right-24rpx -top-10rpx leading-36rpx text-sm text-bgSubtitle bg-white text-center w-36rpx h-36rpx border border-b border-txBorder border-txbordergSubtitle rounded-full">
                      {{ cartList.length }}
                    </view>
                  </view>
                  <view class="text-26rpx mt-10rpx">购物车</view>
                </view>
                <!-- #ifndef  MP-WEIXIN -->
                <view class="flex items-center justify-center flex-col h-full flex-1"
                  @tap="$u.route(`/pages/web_view/index?url=${service}`)">
                  <view class="w-48rpx h-48rpx flex justify-center items-center">
                    <u-icon name="kefu-ermai" color="#000" size="48"></u-icon>
                  </view>
                  <view class="text-26rpx mt-10rpx">客服</view>
                </view>
                <!-- #endif -->
                <!-- #ifdef  MP-WEIXIN -->
                <button open-type="contact" hover-class="none"
                  class="cu-btn flex items-center justify-center flex-col h-full flex-1">
                  <view class="w-48rpx h-48rpx flex justify-center items-center">
                    <u-icon name="kefu-ermai" color="#000" size="48"></u-icon>
                  </view>
                  <view class="text-26rpx mt-10rpx">客服</view>
                </button>
                <!-- #endif -->
                <!-- #ifdef  MP-WEIXIN -->
                <!-- 增加需求--分享 -->
                <view @tap="getShare" class="flex items-center justify-center flex-col h-full">
                  <view class="w-48rpx h-48rpx flex justify-center items-center">
                    <u-icon name="share" color="#000" size="48"></u-icon>
                  </view>
                  <view class="text-26rpx mt-10rpx">分享</view>
                </view>
                <!-- #endif -->
              </view>

              <view class="flex items-center justify-center flex-1">
                <view class="bg-primary rounded-lg w-180rpx h-66rpx text-center leading-66rpx text-md text-white"
                  @tap="showSpecFun(1)">加入购物车</view>
                <view
                  class="ml-base bg-bgSubtitle rounded-lg w-180rpx h-66rpx text-center leading-66rpx text-md text-white"
                  @tap="showSpecFun(2)">立即购买</view>
              </view>
            </block>
          </view>
        </template>
        <template v-else>
          <view class="pt-140rpx text-center">
            <view class="">该商品已下架或不存在，去逛逛别的吧~</view>
          </view>
        </template>
      </block>
    </view>

    <u-skeleton :loading="isFirstLoading" :animation="true" bgColor="#FFF"></u-skeleton>

    <spec-popup :loading="loading" :specs="specs" :sku="detail" v-model="show" :quota-used="number"
      :show-cart="popupType == 1 || popupType == 0" :show-buy="popupType == 2 || popupType == 0"
      :show-confirm="popupType == 3" @stepper-change="onChangeNumber" @sku-selected="onChangeSku" @buy-clicked="onBuy"
      @add-cart="onAddCart">
    </spec-popup>
    <!-- 分享弹窗 -->
    <sharePopup v-model="shareShow" :goods="detail" :goodsImage="goodsImage"></sharePopup>
  </view>
</template>

<script>
  import comment from '@/components/comment/comment';
  import sharePopup from './components/share-popup.vue';
  import {
    mapGetters,
    mapActions
  } from 'vuex';
  export default {
    components: {
      comment,
      sharePopup,
    },
    data() {
      return {
        bargainDetail: {},
        showShrough: false, //是否显示店铺直通车才显示删除的市场价格
        // service: process.env.VUE_APP_SERVICE,
        isFirstLoading: true,
        isNull: false,
        loading: false,
        // 商品SPU-ID
        productId: '',
        // 选择的SKU-ID
        skuId: '',
        number: 1,
        products: {},
        show: false,
        popupType: '',
        goodsError: '',
        title: '',
        playShow: false,
        shareShow: false,
        goodsImage: '', //本地图片
        style: {
          p: 'font-size:0',
          span: 'font-size: 0',
          img: 'display:block;min-width:100%'
        }
      };
    },
    computed: {
      ...mapGetters(['cartList']),
      user() {
        return this.$store.getters.user ?? {};
      },
      service() {
        const clien = process.env.VUE_APP_SERVICE;
        const user = this.$store.getters.user ?? {};
        const phone = user?.phone;
        const name = user?.nickname ?? phone ?? '访客';
        return `${clien}?u_cust_name=${name}&u_cust_phone=${phone}&u_cust_id=${phone}`;
      },
      bargainLogs() {
        return this.bargainDetail?.logs?.reverse() ?? [];
      },
      detail() {
        return this.products?.sku ?? {};
      },
      //商品特点
      features() {
        return this.products?.features ?? [];
      },
      //banner图
      images() {
        return this.detail?.images ?? [];
      },
      media() {
        const media = this.detail?.media;
        return media ? [media] : [];
      },
      bannerList() {
        const imgs = this.images.map((e) => {
          return {
            type: 'image',
            image: e,
          };
        });
        const videos = this.media.map((e) => {
          return {
            type: 'video',
            image: this.detail.cover,
            video: e,
          };
        });
        return videos.concat(imgs);
      },

      specs() {
        return this.products?.spu_specs ?? [];
      },
      attrs() {
        return this.detail?.attrs ?? [];
      },
      detailHtml() {
        return this.detail?.description ?? '';
      },
      //已选中sku
      activeSku() {
        const sku = this.specs.reduce((arr, pr) => {
          if (pr.items.some((e) => e.selected)) {
            const item = pr.items.find((e) => e.selected);
            arr.push(item);
          }
          return arr;
        }, []);
        return sku;
      },
      //选中sku文本
      activeSkuText() {
        if (this.activeSku.length) return `${this.activeSku.map((e) => e.name).join(',')};数量：${this.number}`;
        return '请选择规格';
      },
      //是否积分兑换
      isPoints() {
        return this.detail.redeem_points > 0
      },
      priceText() {
        let price = ''
        if (this.detail.sell_price > 0) price += `￥${parseFloat(this.detail.sell_price)}`
        if (this.detail.sell_price > 0 && this.detail.redeem_points > 0) price += '+'
        if (this.detail.redeem_points > 0) price += `${this.detail.redeem_points} 积分`
        return price
      }
    },
    onLoad({
      skuId,
      showShrough
    }) {
      if (showShrough) {
        this.showShrough = showShrough;
      }
      this.productId = skuId;
      this.getProducts();
      this.$store.dispatch('goods/getCartList');
    },
    //微信分享
    onShareAppMessage(res) {
      if (res.from === 'button') {
        // 来自页面内分享按钮
        this.shareShow = false;
      }
      let code = this.user.code ? this.user.code : '';
      let shareObj = {
        title: this.detail.name,
        path: `/pages/product_details/index?skuId=${this.productId}&invite_code=${code}`,
        imageUrl: this.detail.cover,
      };
      return shareObj;
    },
    methods: {
      onDHClick() {
        const params = {
          goods: [{
            sku_id: this.skuId,
            num: 1,
          }, ],
          type: 'points'
        };
        this.$u.routeAuth('/pages/confirm_order/confirm_order?data=' + encodeURIComponent(JSON.stringify(params)));
      },
      //保存为本地图片
      getLocal(path) {
        uni.getImageInfo({
          src: path,
          success: (res) => {
            this.goodsImage = res.path;
          },
          complete: (copy) => {},
        });
      },
      //分享
      getShare() {
        if (!this.isLogin) return this.$u.routeLogin();
        this.shareShow = true;
      },
      //app分享微信下载地址
      shareApp() {
        let code = this.user.code ? this.user.code : '';
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          href: `https://wap.zichunsheng.cn/register?code=${code}`,
          title: this.detail.name,
          summary: '我正在使用积趣自然图书馆，赶紧跟我一起来体验吧！',
          imageUrl: `${this.detail.cover}?x-oss-process=image/resize,w_80/quality,q_90`,
          success: (res) => {},
        });
      },
      playVideo() {
        this.playShow = true;
        setTimeout(() => {
          const v = uni.createVideoContext('myVideo', this);
          v.play();
        }, 100);
      },
      pauseVideo() {
        const v = uni.createVideoContext('myVideo', this);
        v.pause();
        this.playShow = false;
      },
      ...mapActions({
        getCartList: 'goods/getCartList',
      }),
      //动态设置导航标题
      getTitle(title) {
        this.title = title;
        uni.setNavigationBarTitle({
          title: title,
        });
      },

      //购买
      onBuy() {
        const params = {
          goods: [{
            sku_id: this.skuId,
            num: this.number,
          }, ],
        };
        this.show = false;
        this.$u.routeAuth('/pages/confirm_order/confirm_order?data=' + encodeURIComponent(JSON.stringify(params)));
      },
      //添加购物车
      async onAddCart(e) {
        const {
          skuId,
          number
        } = this;
        try {
          await this.$store.dispatch(
            'goods/addCart', {
              skuId,
              number,
            }, {
              custom: {
                loading: true,
              },
            },
          );
          this.$u.toast('添加购物车成功');
          this.show = false;
        } catch (error) {
          // console.log(error);
        }
      },
      //获取商品详情
      async getProducts() {
        try {
          this.loading = true;
          const resData = await this.$api.get(`/v1/product/products/${this.productId}`);
          this.products = resData;
          this.skuId = this.products?.sku.id

          if (resData?.sku?.is_bargaing) {
            this.bargainOrderLog();
          }
          //动态修改导航栏
          this.getTitle(resData.sku.name);
          //保存图片到本地
          this.getLocal(resData.sku.cover);
        } catch (error) {
          if (error != 404) {
            this.isNull = true;
          }
          // console.log(error);
        } finally {
          this.loading = false;
          this.isFirstLoading = false;
        }
      },
      //查看自己邀请的人
      async bargainOrderLog() {
        const data = await this.$api.get(`/v1/bargain-order/sku/${this.skuId}`);
        this.bargainDetail = data;
      },
      showSpecFun(type) {
        if (!this.isLogin) return this.$u.routeLogin();
        this.popupType = type;
        this.show = true;
      },
      //数量改变
      onChangeNumber(e) {
        this.number = e;
      },
      //sku改变
      onChangeSku(e) {
        this.skuId = e.sku_id;
        this.getProdutsku();
      },
      //、
      async getProdutsku() {
        try {
          this.loading = true;
          const resData = await this.$api.get(`/v1/product/sku/${this.skuId}`);
          this.products = resData;

          if (resData?.sku?.is_bargaing) {
            this.bargainOrderLog();
          }
          //动态修改导航栏
          this.getTitle(resData.sku.name);
          //保存图片到本地
          this.getLocal(resData.sku.cover);
        } catch (error) {
          if (error != 404) {
            this.isNull = true;
          }
          // console.log(error);
        } finally {
          this.loading = false;
          this.isFirstLoading = false;
        }
      },
      //、
      //收藏
      onCollection() {
        this.$u.throttle(async () => {
          if (!this.isLogin) return this.$u.routeLogin();
          if (this.products.is_collected) {
            await this.$api.post(`/v1/product/products/${this.skuId}/uncollect`);
            this.products.is_collected = false;
            this.$u.toast('取消收藏');
          } else {
            await this.$api.post(`/v1/product/products/${this.skuId}/collect`);
            this.products.is_collected = true;
            this.$u.toast('收藏成功');
          }
        }, 1000);
      },
      jump(url) {
        uni.navigateTo({
          url: '/pages' + url,
        });
      },
      //关闭弹窗
      close(e) {
        this.show = !e;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .border-hex-fff {
    border: 1px solid #fff !important;
  }

  .share-btn::after {
    border: none;
  }

  .shadow {
    box-shadow: 0px -4rpx 10rpx rgba(0, 0, 0, 0.11);
  }

  .shadowRight {
    box-shadow: 2rpx 0px 5rpx rgba(0, 0, 0, 0.12);
  }

  .badge {
    @apply bg-badge;
  }

  .fontFam {
    /* #ifdef APP-PLUS  */
    font-family: '宋体';
    /* #endif  */
  }
</style>
