<template>
  <div class="good-detail" v-if="skuName.id">
    <!-- tab切换 -->
    <div  class="good-tab" :style="{background:rgba}" v-if="flag" >
      <div class="tab-item" @click="switchTab('商品')"  >
        <div :class="{'getColor':tabActive==='商品'}" >商品</div>
        <div class="line" v-show=" tabActive==='商品' "></div>
      </div>
      <div class="tab-item"  @click="switchTab('详情')" >
        <div :class="{'getColor':tabActive==='详情'}" >详情</div>
        <div class="line" v-show=" tabActive==='详情' " ></div>
      </div>
    </div>
    <!-- 商品图片 -->
    <swiper class="good-img-swiper" indicator-dots indicator-color="rgba(0,0,0, .1)" indicator-active-color="#4EB331">
      <swiper-item class="good-img-item">
        <img-lazy-load :src="skuName.img" ></img-lazy-load>
      </swiper-item>
      <swiper-item class="good-img-item" v-if="skuName.img2">
        <img-lazy-load :src="skuName.img2" ></img-lazy-load>
      </swiper-item>
    </swiper>
    <!-- 商品图片 750 -->
    <div id="pd20" >
      <!-- 商品名称 -->
      <div class="good-name">
        {{skuName.name}}
      </div>
      <div v-if="isShowShop" :class="skuName.stock>0 ? 'gray' : 'red'"> {{stock()}}</div>
      <!-- 商品名称 -->
      <!-- 价格 -->
      <div class="good-price" v-if="isShowShop">
        <div class="cur-price">{{$filters.toFixed2(skuName.curPrice)}}</div>
        <div class="ori-price" v-if="skuName.oriPrice">{{$filters.toFixed2(skuName.oriPrice)}}</div>
        <div class="act-type-wrapper">
          <div class="act-type" v-if="skuName.actType">{{actTypeArr[skuName.actType]}}</div>
        </div>
      </div>
      <!-- 门店名 -->
      
      <!-- #ifndef MP-TOUTIAO -->
      <div class="store-name">
        <div class="icon-store"></div>
        <div class="name-text">{{skuName.storeName}}</div>
      </div>
      <!-- #endif -->

	  <!-- #ifdef MP-TOUTIAO -->
    <div class="storeOrFocus">
        <!-- 门店名 -->
        <div class="store-name">
          <div class="icon-store"></div>
          <div class="name-text">{{skuName.storeName}}</div>
        </div>
        <!-- 关注抖音号 -->
        <!-- <div class="focus" @click="focusDY">
          <img src="http://image.jxc4.com/image/6bcf5851be886e47aed26adadbe0856e.png" v-if="!isFocus" class="focus-img">  
          <img src="http://image.jxc4.com/image/9dba0325ddaed85f16f2199efa71bf96.png" v-else class="focus-img">  
          未关注抖音号
          <div class="focus-text">
            关注抖音
          </div>
        </div> -->
      </div>
      <!-- <button open-type="openProfile" user="2329254189">京西菜市</button> -->
      <!-- <follow-service followed-id="2329254189" desc="关注我，了解更多"></follow-service> -->
	  <!-- #endif -->
    </div>
    
    <!-- 详情介绍 -->
    <div class="good-detail-introduce" >
      <div class="good-detail-title" >
        <div class="icon-border"></div>
        <div class="title" >详情介绍</div>
      </div>
      <!-- <img-lazy-load v-if="skuName.descImg" :src="skuName.descImg" mode="widthFix" clip="imageView2/2/w/750"></img-lazy-load> -->
      <!-- v-if="skuName.descImg && isShowShop"  -->
      <image class="desc-img" v-if="skuName.descImg && isShow"	mode="widthFix" :src="$filters.urlToHttps(skuName.descImg,'img750type2') " ></image>
      <div class="no-introduce" v-else>暂无详情</div>
    </div>
    <!-- 底部加入购入车操作条 -->
    <!-- isShow ||  isShare === 'share' -->
    <div class="bottom-bar"  v-if="isShow ||  isShare === 'share'">
      <bottom-bar
        :skuName="skuName"
        :isShare="isShare"
        @handleSkuNamePlus="handleSkuNamePlus"
        @handleSkuNameMinus="handleSkuNameMinus"
        @handleSkuNameChange="handleSkuNameChange"
      ></bottom-bar>
    </div> 
    <!-- loading -->
    <zy-loading></zy-loading>
  </div>
</template>

<script>
import { mapGetters,mapActions } from "vuex";
import ZyLoading from '@/components/Loading/loading'
import {msgData, actTypeArr} from '@/config.js'
import ImgLazyLoad from '@/components/commonCmp/img-lazy/img-lazy'
import BottomBar from './shopCar-bottom-bar/shopCar-bottom-bar.vue'

import goodPage from '@/apis/goodPage';
import {store} from "@/store";
export default {
  data () {
    return {
      skuName: {},
      actTypeArr,
      tabActive:'商品',
      topToPic:0,
      rgba:'rgba(255,255,255,0)',
      flag: false,
      isShow:true,   // 审核时，是否显示购物车
      isShare:'',     // 在详情页是否是分享类型
      isFocus: false
    }
  },
  components: {
    ZyLoading, ImgLazyLoad,
    BottomBar
  },
  computed: {
    ...mapGetters({
      isLogin: "login/isLogin",
      isShowShop:"isShowShop",
      storeMap:"indexPage/storeMap",
      storeID:"indexPage/storeID",
    }),
    // #ifdef MP-TOUTIAO
    // businessTime1() {
    //   let time = ''
    //   let str1 = '' + this.storeMap[this.storeID].item.openTime1 % 100
    //   let str2 = '' + this.storeMap[this.storeID].item.closeTime1 % 100
    //   if (str1.length!==2) {
    //     str1 = 0 + str1
    //   }
    //   if (str2.length!==2) {
    //     str2 = 0 + str2
    //   }
    //   time = this.storeMap[this.storeID].item.openTime1/100 + ':' + str1 + '-' + this.storeMap[this.storeID].item.closeTime1/100 + ':' + str2
    //   console.log('打印time',this.storeMap[this.storeID].item.openTime1)
    //   return time
    // },
    // businessTime2() {
    //   let time = ''
    //   if (this.storeMap[this.storeID].item.openTime2 && this.storeMap[this.storeID].item.closeTime2) {
    //     let str1 = '' + this.storeMap[this.storeID].item.openTime2 % 100
    //     let str2 = '' + this.storeMap[this.storeID].item.closeTime2 % 100
    //     if (str1.length!==2) {
    //       str1 = 0 + str1
    //     }
    //     if (str2.length!==2) {
    //       str2 = 0 + str2
    //     }
    //     time = this.storeMap[this.storeID].item.openTime2/100 + ':' + str1 + '-' + this.storeMap[this.storeID].item.closeTime2/100 + ':' + str2
    //   }
      
    //   return time
    // }
    // #endif
  },
  onHide() {
    uni.removeStorageSync('shareInfo')
  },
  async onLoad (query) {
    try {
      this.skuName = await this.getSkuName({skuID:query.skuID})


      // #ifdef APP-PLUS  || MP-TOUTIAO || APP
      this.isShow = this.isShowShop
      // #endif

      // #ifdef MP-TOUTIAO
		  if(this.isLogin){
        uni.checkFollowAwemeState({
          success:(res) => {
            this.isFocus = res.hasFollowed
          }
        })
      }
      if (query.type === 'share' || !this.isLogin) {
        store.commit('indexPage/changeStoreID', [Number(query.storeID)])
        this.isShare = query.type
      } else {
        // console.log('this.isShowShop',this.isShowShop)
        // // this.isShow = this.isShowShop
        // // console.log('商品详情页 onLoad', query.skuID)
        // const skuID = +query.skuID
        // const storeID = +query.storeID
        // this.showLoad()
        // this.skuName = await this.getSkuName(skuID, storeID)
      }
		// #endif

    // // #ifndef MP-TOUTIAO
      // const skuID = +query.skuID
      // const storeID = +query.storeID
      // this.showLoad()
    // // #endif
    
    // // #ifndef MP-TOUTIAO
		//   this.skuName = await this.getSkuName(skuID, storeID)
    // // #endif

    } catch (e) {
      console.error(e)
      this.$alertBack(e, '出错啦')
    } finally {
      this.hideLoad()
    }
  },
  beforeDestroy() {
    // console.log('销毁事件-----------')
    // #ifdef MP-TOUTIAO
    // console.log('this.isShare',this.isShare)
    // if (this.isShare === 'share' && this.isLogin) {
    //   uni.reLaunch({
    //     url: '/pages/index/index'
    //   });
    //   uni.removeStorageSync('shareInfo')  
    // }
    // #endif
  },
  // 分享
  onShareAppMessage (res) {
    console.log('分享事件',res,this.skuName)
    const { name, id, img, curPrice, storeID } = this.skuName
    
    let path = ''
    // #ifndef MP-TOUTIAO
    path = `/pagesGoods/good-detail/index?storeID=${storeID}&skuID=${id}`
    // #endif

    // #ifdef MP-TOUTIAO
     path = `/pagesGoods/good-detail/index?storeID=${storeID}&skuID=${id}&type=share`
    // #endif
    return {
      title: `【￥ ${(curPrice / 100).toFixed(2)}】${name}`,
      path: path,
      imageUrl: img,
      content: name,
      desc: name,
    }
  },
  methods: {
    ...mapActions({
      changeCar: "cartPage/changeCar",
    }),
     // 关注抖音号
    //  focusDY(){
    //   if(this.isLogin){
    //     // let that =this
    //     // 弹框关注抖音号
    //     uni.followAwemeUser({
    //       success: (res) => {
    //         console.log(res,'res',res.followed);
    //         uni.checkFollowAwemeState({
    //           success:(res1) => {
    //             // console.log('是否已关注',res1,'this',this)
    //             this.isFocus = res1.hasFollowed
    //           }
    //         })
    //       },
    //     });
    //   }else{
    //     toast('请登录')
    //     uni.setStorageSync('shareInfo',JSON.stringify([{storeID:this.skuName.storeID},{skuID:this.skuName.id},{type:''}]))
    //     store.commit('login/changeLoginStatus', '')
    //     setTimeout(() => {
    //       uni.switchTab({ url: '/pages/mine/index' })
    //     }, 800);
    //   }

    // },
    // testData() {
    //   this.getRectBox('#pd20')
    // },
    // tab切换
    switchTab(tabText){
      if(tabText===this.tabActive){
        return 
      }else{
        this.tabActive=tabText
      }
      if(tabText==='详情'){
        // uni.pageScrollTo({
        //     scrollTop: 450,
        //     duration: 300,
        //   });
        this.$nextTick(()=>{
           const query = uni.createSelectorQuery().in(this);
          query.select('.good-detail-introduce').boundingClientRect(data => {
            if(data){
                console.log(data.top)
                 uni.pageScrollTo({
                  scrollTop: data.top,   // top实际高度456
                  duration: 300,
                })
              }
          }).exec(
            (res)=>{
              if(!res[0]){
                this.$nextTick(()=>{
                    this.getRectBox(box)
                  })
              }
            }
          )
        })
        
        }else{
          uni.pageScrollTo({
            scrollTop: 0,
            duration: 300,
          });
        }
    },
    // 获取单个商品
    async getSkuName (query) {
      try {
        let res = await goodPage.getStoresSkus({ categoryID:'one',skuID:query.skuID })
        if (res) {
          let skuNames = res.skuNames
          if (skuNames.length === 0) throw msgData.searOneGoodErr
          // console.log(skuNames[0])
          return skuNames[0]
        } else {
          return {}
        }
      } catch (e) {
        throw e
      }
    },
    stock() {
      let num = this.skuName.stock;
      // console.log(this.skuName.name, this.skuName.stock);
      if (num >= 1000) {
        return "库存:1000+";
      } else if (num < 1000 && num > 0) {
        return '库存:'+num;
      } else if (num === 0) {
        return "卖完了";
      }
    },
    // 商品 +
    async handleSkuNamePlus() {
      await this.changeCar({
          skuName:this.skuName,
          count:this.skuName.count + 1
        })
      this.$set(this.skuName, 'count', this.skuName.count + 1)
    },
    // 商品 -
    async handleSkuNameMinus() {
      await this.changeCar({
          skuName:this.skuName,
          count:this.skuName.count - 1
        })
      this.$set(this.skuName, 'count', this.skuName.count - 1)
    },
    async handleSkuNameChange(count) {
      await this.changeCar({
          skuName:this.skuName,
          count:count
        })
      this.$set(this.skuName, 'count', count)
    },
    // 获取页面的高度
    getRectBox(box) {
      let query = ''
      
      // #ifndef MP-ALIPAY
      query = uni.createSelectorQuery().in(this);
      // #endif

      // #ifdef MP-ALIPAY
      query = uni.createSelectorQuery();
      // #endif
      
      query.select(box).boundingClientRect(data => {
          if(data){
             this.topToPic=data.top
          }
      }).exec(
        (res) => {
          if (!res[0]) {
            this.$nextTick(()=>{
              this.getRectBox(box)
            })
          }
      }
      )
    }
  },
  mounted() {
    this.getRectBox('#pd20') 
  },
  // 获取页面滚动的距离
  onPageScroll: function(Object) {
    // console.log(Object.scrollTop);//实时获取到滚动的值
    let opacity=0
    // #ifdef MP-KUAISHOU
    if (this.topToPic === undefined) {
      this.getRectBox('#pd20')
    }
		// #endif
    opacity=Object.scrollTop/this.topToPic
    this.rgba=opacity?'rgba(255,255,255,'+opacity+')':"rgba(255,255,255,0)"
    if(opacity===0){
      this.flag=false
    }else{
      this.flag=true
    }
    if(Object.scrollTop<436){
      this.tabActive='商品'
    }else{
      this.tabActive='详情'
    }
  },
}
</script>

<style lang="scss">
@import './good-detail.scss';
.red {
  color: #fe6263;
  margin: 10rpx 0;
}
.gray {
  color: #999;
  margin: 10rpx 0;
}
</style>
