<template>
  <view class="page-wrap">
    <!-- 顶部按钮 -->
    <!-- <image :style="{'top': `${statusBarHeight}px`}" class="back-btn" src="https://ld.726p.com/ldyx_static/imgs/btn-back.png" @click="onClickToBack" /> -->

    <!-- S 轮播图 -->
    <view class="swiper-wrap">
      <u-swiper
        :list="swiperList"
        height="750"
        mode="round"
        bg-color="transparent"
      />
    </view>
    <view class="commission-price-view" v-if="user_level > 1 && goodsItem.commission_price > 0" @click="onClickCommission">猎豆优选专享，下单或分享可获{{goodsItem.commission_price}}元</view>
    <!-- E 轮播图 -->

    <!-- S 商品信息 -->
    <view class="info-wrap con-block">
      <view class="tp-wrap">
        <view class="lt-wrap">
    	  <text class="price-title">{{goodsItem.is_coupon == 1 && goodsItem.coupon_price > 0 ? '券后价' : '' }} ¥</text>
          <text class="price">{{ goodsItem.discount_price }}</text>
          <text class="price-old">￥{{ goodsItem.price }}</text>
        </view>
        <view class="rt-wrap">
    		<view class="salesVolume" v-if="goodsItem.volume > 100">
    			月销:{{ $NumberHandle({value:goodsItem.volume,comma:true}) }}+
    		</view>
        </view>
      </view>
      <view class="bm-wrap">
        <image class="shop-icon" v-if="goodsItem.shop_type == 0" src="https://ld.726p.com/ldyx_static/imgs/icon-tb.png" />
        <image class="shop-icon" v-else-if="goodsItem.shop_type == 1" src="https://ld.726p.com/ldyx_static/imgs/icon-tmall.png" />
        {{ goodsItem.title }}
      </view>
      <view class="quan-block" v-if="goodsItem.is_coupon == 1 && goodsItem.coupon_price > 0" @click="copyTKL">
      	<view class="quan-info">
      		<view class="quan-info-1">
      			优惠券 ¥<text class="quan-price">{{goodsItem.coupon_price}}</text>
      		</view>
    		<view class="quan-time">{{goodsItem.coupon_start_time && goodsItem.coupon_start_time.slice(0,16)}} ~ {{goodsItem.coupon_end_time && goodsItem.coupon_end_time.slice(0,16)}}</view>
      	</view>
    	<view class="quan-button">复制淘口令</view>
      </view>
    </view>
    <!-- E 商品信息 -->

    <!-- S 店铺信息 -->
    <view class="shop-wrap con-block">
      <view class="lt-wrap">
        <image class="shop-img" :src="goodsItem.shop.pic_path" />
      </view>
      <view class="rt-wrap">
        <view class="tp-wrap">
          <text class="shop-name">{{ goodsItem.shop.title }}</text>
          <view class="enter-wrap">
          </view>
        </view>
        <view class="point-wrap">
          <text>宝贝描述 {{ goodsItem.shop.item_score }}</text>
          <text>服务态度 {{ goodsItem.shop.service_score }}</text>
          <text>发货速度 {{ goodsItem.shop.delivery_score }}</text>
        </view>
      </view>
    </view>
    <!-- E 店铺信息 -->

    <!-- S 相关推荐 -->
    <view class="recommend-wrap con-block">
    	<view class="block-title">相关推荐</view>
      <view class="goods-list-wrap">
        <view v-for="item in recommendList" :key="item.goods_id" class="goods-item-wrap" @click="onClickGoodsItem(item)">
          <image class="goods-img" :src="item.img" />
          <view v-if="user_level > 1 && item.commission_price > 0" class="goods-commission">预估佣金 ￥{{ item.commission_price }}</view>
          <view class="goods-title">{{ item.title }}</view>
          <view class="goods-price">
            <text class="price">￥{{ item.discount_price }}</text>
            <text class="price-old">￥{{ item.price }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- E 相关推荐 -->

    <!-- S 宝贝详情 -->
    <view class="detail-wrap con-block">
    	<view class="block-title">宝贝详情</view>
      <view class="content">
        <image class="price-img" src="https://gw.alicdn.com/tfs/TB1k9XsQpXXXXXLXpXXXXXXXXXX-750-368.png" mode="widthFix"/>
      </view>
    </view>
    <!-- E 宝贝详情 -->

    <!-- S 猜你喜欢 -->
    <view class="guess-wrap con-block">
    	<view class="block-title">猜你喜欢</view>
      <!-- S 双排商品列表 -->
      <view class="goods-list-double-wrap">
        <block v-for="goodsItem in guessList">
      	  <verticalGood class="verticalGoodItem" v-if="goodsItem" :key="goodsItem.goods_id" :goodsItem="goodsItem" path="goodsItemRecommendAction"></verticalGood>
        </block>
      </view>
      <!-- E 双排商品列表 -->
    </view>
    <!-- E 猜你喜欢 -->

    <!-- 底部按钮 -->
	<view class="open-tb-btn-view" :style="{ 'bottom': isIphoneX ? '120rpx' : '100rpx' }">
		<image v-if="isIOS" @click="goTb" class="open-tb-btn" src="https://ld.726p.com/ldyx_static/imgs/open-tb-btn.png" mode="widthFix"></image>
		<view v-else class="copy-tkl" @click="copyTKL">复制淘口令</view>
	</view>
	<!-- 回到顶部 -->
	<u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script>
  const app = getApp()
  const $router = app.globalData.$router
	import verticalGood from '@/components/verticalGood.vue'
  export default {
	  components:{
		  verticalGood
	  },
    data() {
      return {
		isIOS: app.globalData.isIOS,
        isIphoneX: app.globalData.isIphoneX,
        statusBarHeight: app.globalData.statusBarHeight,
        swiperList: [], // 轮播图列表(image指定图片路径，也可以通过name属性自定义)
        recommendList: [], // 相关推荐列表

        guessList: [], // 猜你喜欢列表
        guessListPage: 1,
        guessListHasNext: true,

        goods_id: '', // 商品id
        goodsParams: {}, // 商品参数（用于获取商品详情的相关参数 前一页面传入）
        goodsItem: { // 商品详情数据
          discount_price: '',
          price: '',
          volume: '',
          title: '',
          coupon_price: '',
          shop: {
            pic_path: '',
            title: '',
            delivery_score: '',
            item_score: '',
            service_score: '',
          },
        },
        isLogin: false, // 是否已登录
        user_level: uni.getStorageSync('userInfo') ?
                    uni.getStorageSync('userInfo').user_level : '', // 当前用户等级
		scrollTop: 0,
		tkl: ''
      };
    },
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
    onLoad(options) {
      const { user_id = '', goods_id = '', coupon_price = '', discount_price = '', price = '', is_coupon = '', commission_rate = '', is_high_commission = '', coupon_end_time = '', coupon_start_time = '' } = options

      // 接收前一页面传入的商品参数
      this.goods_id = decodeURIComponent(goods_id)
      this.goodsParams = {
		user_id: decodeURIComponent(user_id),
        goods_id: decodeURIComponent(goods_id),
        coupon_price: decodeURIComponent(coupon_price),
        discount_price: decodeURIComponent(discount_price),
        price: decodeURIComponent(price),
        is_coupon: decodeURIComponent(is_coupon),
        commission_rate: decodeURIComponent(commission_rate),
        is_high_commission: decodeURIComponent(is_high_commission),
        coupon_end_time: decodeURIComponent(coupon_end_time),
        coupon_start_time: decodeURIComponent(coupon_start_time),
      }

      // 获取商品详情数据
      this.handleGetgoodsItem()
      // 获取相关推荐列表
      this.handleGetRecommendList()
      // 获取猜你喜欢列表
      this.handleGetGuessList()
      // 获取用户登录状态
      this.handleGetUserIsLogin()
      // 用户浏览信息上报
      // this.handleUserReport()
	  // 商品分享获取数据接口
	  this.handleGetPosterInfo()
    },
    // 上滑触底事件
    onReachBottom() {
      this.handleGetGuessList()
    },
    methods: {
		//去淘宝
		goTb(){
			let tklCode = this.tkl;
			let params = tklCode.split('https://m.tb.cn')[1].split(' ')[0].split('/')[1];
			const a = document.createElement('a');
			a.style.display = 'none';
			// a.href = `https://b.mashort.cn${params}`; // 可唤起
			a.href = `https://s.tb.cn/${params}` // 可唤起
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
		},
      // 用户浏览信息上报
      // async handleUserReport() {
      //   if (!this.isLogin) return false
      //   const { goods_id, is_coupon, coupon_price, price, discount_price, commission_rate, coupon_end_time, coupon_start_time } = this.goodsParams
      //   try {
      //     const url = this.$api.goodsItem_record
      //     const params = { goods_id, is_coupon, coupon_price, price, discount_price, commission_rate, coupon_end_time, coupon_start_time }
      //     await this.$postJSON(url, params)
      //   } catch (error) {
      //     console.log('error => ', error)
      //   }
      // },
      // 获取用户登录状态
      handleGetUserIsLogin() {
        const userInfo = uni.getStorageSync('userInfo') || ''
        const user_id = uni.getStorageSync('user_id') || ''
        if (userInfo && user_id) {
          this.isLogin = true
        } else {
          this.isLogin = false
        }
      },
      // 获取猜你喜欢列表
      async handleGetGuessList() {
        const { guessListPage, guessListHasNext, goods_id } = this
        if (!guessListHasNext) return false
        try {
          uni.showLoading({ title: '加载中...', mask: true })
          const url = this.$api.goods_recommendlist
		  const params = { page: guessListPage, goods_id, user_id: this.goodsParams.user_id }
          const { data: res = {} } = await this.$postJSON(url, params)
          if (res && res.errno == 0 && Array.isArray(res.rst.data)) {
            this.guessListHasNext = res.rst.pageInfo.hasNext
            this.guessListHasNext && this.guessListPage++
            this.guessList = [...this.guessList, ...res.rst.data]
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
          }
        } catch (error) {
          console.log('error => ', error)
        } finally {
          uni.hideLoading()
        }
      },
      // 获取相关推荐列表
      async handleGetRecommendList() {
        try {
          uni.showLoading({ title: '加载中...', mask: true })
          const url = this.$api.goods_recommendtop
          const params = { goods_id: this.goods_id ,user_id: this.goodsParams.user_id}
          const { data: res = {} } = await this.$postJSON(url, params)
          if (res && res.errno == 0 && Array.isArray(res.rst.data)) {
            this.recommendList = [...res.rst.data]
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
          }
        } catch (error) {
          console.log('error => ', error)
        } finally {
          uni.hideLoading()
        }
      },
      // 获取商品详情数据
      async handleGetgoodsItem() {
        const { user_id, goods_id, coupon_price, discount_price, price, is_coupon, commission_rate } = this.goodsParams
        try {
          uni.showLoading({ title: '加载中...', mask: true })
          const url = this.$api.goods_detail
          const params = { goods_id, coupon_price, discount_price, price, is_coupon, commission_rate ,user_id}
          const { data: res = {} } = await this.$postJSON(url, params)
          if (res && res.errno == 0 && res.rst.data) {
            this.goodsItem = { ...res.rst.data }
            this.swiperList = res.rst.data.small_img.map(item => ({
              image: item
            }))
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
          }
        } catch (error) {
          console.log('error => ', error)
        } finally {
          uni.hideLoading()
        }
      },
      // 监听点击"返回"
      onClickToBack() {
        uni.navigateBack()
      },
      // 监听跳转详情
      onClickGoodsItem(goodsItem) {
		  try{ app.categoryNew_countBuy({type:0,path:'goodsItemTopRecommendAction'}) }catch(e){} ; // 数据上报
        const { img = '', goods_id = '', coupon_price = '', discount_price = '', price = '', is_coupon = '', commission_rate = '', is_high_commission = '', coupon_end_time = '', coupon_start_time = '' } = goodsItem
        const pages = getCurrentPages()
        const currentPageLength = pages.length
        // 微信小程序 页面栈限制 最多10页
        if (currentPageLength < 10) {
          uni.navigateTo({
            url: `/pages/subPackages/home/goodsDetail?img=${encodeURIComponent(img)}&goods_id=${encodeURIComponent(goods_id)}&coupon_price=${encodeURIComponent(coupon_price)}&discount_price=${encodeURIComponent(discount_price)}&price=${encodeURIComponent(price)}&is_coupon=${encodeURIComponent(is_coupon)}&commission_rate=${encodeURIComponent(commission_rate)}&is_high_commission=${encodeURIComponent(is_high_commission)}&coupon_end_time=${encodeURIComponent(coupon_end_time)}&coupon_start_time=${encodeURIComponent(coupon_start_time)}`
          })
        } else {
          uni.redirectTo({
            url: `/pages/subPackages/home/goodsDetail?img=${encodeURIComponent(img)}&goods_id=${encodeURIComponent(goods_id)}&coupon_price=${encodeURIComponent(coupon_price)}&discount_price=${encodeURIComponent(discount_price)}&price=${encodeURIComponent(price)}&is_coupon=${encodeURIComponent(is_coupon)}&commission_rate=${encodeURIComponent(commission_rate)}&is_high_commission=${encodeURIComponent(is_high_commission)}&coupon_end_time=${encodeURIComponent(coupon_end_time)}&coupon_start_time=${encodeURIComponent(coupon_start_time)}`
          })
        }
      },
      // 监听点击收藏
      onClickSetFavorites() {
        if (!this.isLogin) { // 未登录 => 去登录
          $router.navigateTo({
            url: '/pages/subPackages/login/loginPhone'
          })
        } else {
          this.handleSetFavorites()
        }
      },
      async handleSetFavorites() {
        const { user_id, goods_id, is_coupon, discount_price, price, coupon_price, commission_rate, coupon_end_time, coupon_start_time } = this.goodsParams
        try {
          uni.showLoading({ title: '加载中...', mask: true })
          const url = this.$api.goodsItem_addFavorites
          const params = { goods_id, is_coupon, discount_price, price, coupon_price, commission_rate, coupon_end_time, coupon_start_time, user_id }
          const { data: res } = await this.$postJSON(url, params)
          if (res && res.errno == 0) {
            // 设置成功 => 更新状态
            this.handleGetgoodsItem()
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
          }
        } catch (error) {
          console.log('error => ', error)
        } finally {
          uni.hideLoading()
        }
      },
      // 监听点击“反佣金”
      onClickCommission() {
        $router.navigateTo({
          url: `/pages/subPackages/my/tqjs`
        })
      },
	  copyTKL(){
		  this.$copyEvent( {text: this.tkl} )
	  },
	  // 获取分享商品海报的参数信息
	  async handleGetPosterInfo() {
	    const { goods_id, is_coupon, user_id} = this.goodsParams
	      try {
	        const url = this.$api.goodsItem_getTKL;
	        const params = { goods_id, is_coupon, user_id }
	        const { data: res } = await this.$postJSON(url, params)
	        if (res && res.errno == 0 && res.rst.data) {
				this.tkl = res.rst.data;
	        } else {
	        }
	      } catch (error) {
	      }
	  },
    },
  }
</script>

<style lang="scss" scoped>
@import '@/static/style/goodsDetail.scss';
.open-tb-btn-view{
	width: 360rpx;
	position: fixed;
	left: 0;
	right: 0;
	bottom: 100rpx;
	margin: auto;
}
.open-tb-btn{
	width: 100%;
	height: 100%;
}
.copy-tkl{
	background: #fb5b05;
	line-height: 80rpx;
	text-align: center;
	border-radius: 80rpx;
	font-size: 32rpx;
	color: #ffffff;
	font-weight: bold;
}
</style>
