<template>
<view v-if="allShow">
<!--pages/detail/detail.wxml-->
<view class="banner">
	<swiper class="swiper" @change="swiperChange" :current="current" autoplay="true" circular="true" duration="1000">
		<block v-for="(item, index) in product.images" :key="index">
			<swiper-item autoplay="true">
				<image :src="item + '?x-oss-process=style/w750-auto'" mode="aspectFit"></image>
			</swiper-item>
		</block>
	</swiper>
	<view class="dots dflex">
		<block v-for="(item, index) in product.images" :key="index">
			<view :class="'dot ' + (index == swiperCurrent ? ' active' : '')" :data-current="index" @tap="dotEvent"></view>
		</block>
	</view>
</view>
<!-- <view bindtap="saoma">扫码</view> -->
<!-- <view class="notification_bar" wx:if="{{isNotice}}">
	<swiper class="swiper_container" vertical="true" autoplay="true" circular="false" duration="1000" interval="5000" easing-function="easeInOutCubic" class="bar_box dflex">
		<swiper-item class="bar_con dflex" wx:for="{{contentList}}" wx:key="item">
			<view class="bar dflex">
				<image class="bar_left" src="{{item.pic}}" />
				<text class="bar_text">最新订单来自</text>
				<text class="bar_text">{{item.name}}，</text>
				<text class="bar_text">{{item.time}}</text>
			</view>
		</swiper-item>
	</swiper>
</view> -->
<view class="info bgfff">
	<view class="infos dflex">
		<view class="price dflex" v-if="product.mode==2">
			<text>{{product.integral?product.integral:'0'}}积分</text>
			<text class="money" v-if="product.salePrice">+￥{{product.salePrice?product.salePrice:'0'}}</text>
			<text class="origin" v-if="product.salePrice == product.actualPrice && product.marketPrice > 0">￥{{product.marketPrice}}</text>
		</view>
		<view class=" sellStock" v-if="product.sellStock>0">销量：<text>{{product.sellStock}}</text></view>
		<view class="share" @tap="showShare">
			<image src="/static/pages/images/fxico.png"></image>分享
		</view>
	</view>
	<view class="title">
		<image src="/static/pages/images/jishida.png" class="tag" v-if="product.isTimely === 1&&merchant.isDefault!=1"></image>
		<image src="/product/static/product/image/overseasPurchase.png" class="tag" v-if="product.isOtc===5"></image>
		{{product.title}}
	</view>
	<view class="protext">
		{{product.brandName ? product.brandName : ''}} {{product.brief ?  product.brief : ''}}
	</view>
	<!-- <view class="xiaodian dflex" wx:if="{{hideShop=='true'}}">
		<image src="/pages/images/xdbg1.png" class="xdbg"></image>
		<view class="shouyi flex">
			<text>销售收益</text>
			<view>8.65<text>元</text></view>
		</view>
		<view class="addshop" bindtap="addShop">添加到小店</view>
	</view> -->
</view>

<view class="detinfo mt20 bgfff">
	<!-- <view class="item dflex">
    <label>优惠券</label>
    <view class="quan flex dflex">
      <view class="flex dflex">
        <text>满500减50</text>
        <text>满200减10</text>
      </view>
      <view class="ling dflex">领券<image src="/pages/images/more3.png"></image></view>
    </view>
  </view> -->
	<view class="item dflex">
		<label>配送至</label>
		<view class="flex" @tap="toAddress">
			<view class="address">{{address.address}}{{address.house}}</view>
			<view class="huo"><text>现货</text>
				<!-- 现在下单，预计2小时后送达 -->
			</view>
		</view>
		<image src="/static/pages/images/more2.png" class="more" @tap="toAddress"></image>
	</view>

	<!-- <view class="item dflex">
		<label>服务门店</label>
		<view class="flex" bindtap="updateShop">
			<view class="address">{{merchant.title}}</view>
		</view>
	</view> -->
</view>
<!-- 海外购 -->
<!-- <view class="detinfo mt20 bgfff" wx:if="{{product.isOtc==5}}">
	<view class="item">
		<view class="dflex">
			<label>物流</label>
			<view class="">
				<view class="address">20：00前付款，预计9月30日前送达</view>
			</view>
		</view>
		<view class="dflex logistics">
			<view class="lsicText">
				<image src="/product/image/abroad.png" class="abroad"></image>
				德国进口
			</view>
			<image src="/product/image/you_h.png" class="you"></image>
			<view class="lsicText">
				<image src="/product/image/bonded.png" class="abroad"></image>
				保税店
			</view>
			<image src="/product/image/you.png" class="you"></image>
			<view>
				<image src="/product/image/position.png" class="abroad"></image>
				长沙市
			</view>
		</view>
	</view>
</view> -->
<!--  商品详情等页面 -->
<product-footer id="list" ref="list" :detail="nodes" :imgs="imgs" :proId="product.id" v-if="product.id" :form="form" @scoreTab="scoreTab" @showTab="showTab" @freshen="freshenFun"></product-footer>


<v-share :hide-toast="hideShare" :product="product" :code-url="codeUrl" @onFather="click"></v-share>
<view class="placeholder-view" :style="'height:' + (bottomBlankHeight + 140) + 'rpx'"></view>
<view class="bot fixed bgfff dflex" :style="'padding-bottom: ' + (bottomBlankHeight + 20) + 'rpx'">
	<view class="btnfot">
		<contact-button img-url="/static/pages/images/kfico.png" class-name="botbtn" button-text="客服"></contact-button>
		<navigator class="botbtn" open-type="reLaunch" url="/integralshop/cart/cart?integralshop=1" hover-class="none">
			<image src="/static/pages/images/gwc.png"></image>购物车<text class="message" v-if="product.count > 0">{{product.count}}</text>
		</navigator>
	</view>
	<view class="btnbuy">
		<view :class="'addcart ' + (product.stock >= 1 && product.state == 1 ? '' : 'gray')" @tap="product.stock >= 1 && product.state == 1 ? addShopCart() : ''">加入购物车</view>
		<view class="gmbtn mbglinear" @tap="atOnceBuy" v-if="product.stock >= 1 && product.state == 1">
			{{product.isOtc==1 ?'预约下单': '立即兑换'}}</view>
			<view class="gmbtn mbggray" v-if="product.stock < 1 && product.state == 1">立即兑换</view>
			<!-- <view class="gmbtn kan-guoqi" wx:if="{{product.stock < 1 && product.state == 1}}">
			商品已售罄</view> -->
		<!-- <view class="integral mbggray" >积分不足</view> -->
		<view class="gmbtn mbggray" v-if="product.state == 2">已下架</view>
	</view>
</view>
<view class="xiajia" v-if="product.stock < 1 && product.state == 1">您来晚了，商品已经卖完了</view>
<view class="xiajia" v-if="product.state == 2">您来晚了，商品已经下架</view>

<!-- 商品规格 -->
<block v-if="isShow">
	<product-popup :product="product" :order-type="'11'" :is-cart="isCart" :is-timely="product.isTimely" :merchant="merchant" :merchant-id="merchantId" @hidePopup="hidePopup" @addCartSuccess="addCartSuccess">
	</product-popup>
</block>
<!-- 返回顶部 -->
<view class="contact_index" @tap="goTop">
	<image src="/static/pages/images/backtop.png"></image>顶部
</view>
<!-- 添加到小店成功 -->
<!-- <view class="mask" hidden="{{isHide}}" bindtap="hidePop"></view>
<view class="suc" hidden="{{isHide}}">
	<image src="/pages/images/tjcg1.png" class="tjcg1"></image>
	<image src="/pages/images/tjcg.png" class="tjcg"></image>
	<text>快去我的小店看看吧</text>
	<navigator url="/mine/shop/shop" hover-class="none" class="shop">我的小店</navigator>
	<view class="share-btn dflex">
		<button class="wxfriend dflex" open-type="share">
			<image src="/pages/images/wechat.png"></image>
			微信好友
		</button>
		<view class="wxposter dflex" bindtap="generatePoster">
			<image src="/pages/images/poster.png"></image>
			生成海报
		</view>
	</view>
	<image src="/pages/images/close2.png" class="suc-close" bindtap="hidePop"></image>
</view> -->
</view>
</template>

<script>
const app = getApp();
const req = require("../../utils/request.js");
const utils = require("../../utils/util.js");
var QQMapWX = require("../../utils/qqmap.js");
const route = require("../../utils/route");
import productFooter from "../../components/product_footer/index";
import productPopup from "../../components/product-popup/index";
import vShare from "../../components/share/share";

export default {
  data() {
    return {
      bottomBlankHeight: app.globalData.isIPhoneX ? 68 : 0,
      swiperCurrent: 0,
      bannerUrls: [],
      isShow: false,
      pro: {},
      isCart: false,
      timer: [],
      hideShare: true,
      codeUrl: '',
      contentList: [{
        pic: "/static/pages/images/bar.png",
        name: '好风依旧',
        time: '4秒前'
      }, {
        pic: "/static/pages/images/bar.png",
        name: '杨鑫',
        time: '20秒前'
      }, {
        pic: "/static/pages/images/bar.png",
        name: '杨鑫',
        time: '5秒前'
      }],
      isNotice: false,
      form: {
        page: 1,
        limit: 10
      },
      freshen: true // hideShop: '',//隐藏添加到小店
      // isHide: true,//添加小店成功弹窗
      ,
      current: "",
      merchantId: "",
      hideShop: "",
      merchant: "",
      shopId: "",
      imgs: [],
      product: "",
      nodes: "",
      address: "",
      popup: "",
      tabIndex: "",
	  allShow:false
    };
  },

  components: {
    productFooter,
    productPopup,
    vShare
  },
  props: {},
  onLoad: function (options) {
    let that = this;
    // console.log(options);
    this.query = options;

    if (options.scene) {
      this.scene = options.scene;
      this.merchantId = options.merchantId;
    }

    if (options.merchantId) {
      that.setData({
        merchantId: options.merchantId
      });
    }

    if (options.isShare) {
      req.setStorage('pidCode', options.userId);
    }

    if (options.hideShop) {
      this.setData({
        hideShop: this.query.hideShop
      });
    } else {
      this.setData({
        hideShop: 'true'
      });
    }

    if (options.merchantId && options.merchantId != 'undefined') {
      req.getRequest('/api/merchant/detail', {
        id: options.merchantId
      }, data => {
		  var timestamp = Date.parse(new Date());
		  data.time=timestamp+1*60*1000
		  
        req.setStorage("MERCHANT", data);
        that.setData({
          merchant: data
        });
        // console.log(data, "执行+++++++++++++++++++++");
      });
    } else {
      let merchant = req.getStorage('MERCHANT');
      this.setData({
        merchant: merchant
      });
    } // else{
    //   req.getRequest('/api/merchant/getMerchantList',{}, res => {
    //    res = res.filter(it=>it.isDefault==1)
    //     req.setStorage('MERCHANT', res[0]);
    //     this.data.merchant=res[0]
    //     that.setData({merchant:res[0]})
    //     console.log(this.data.merchant)
    //   })
    // }


    setInterval(() => {
      this.setData({
        isNotice: true
      });
    }, 10000);
  },
  onShow: async function () {
    if (this.freshen) {
      await this.loadCodeParams();
      this.loadProudct(this.query);
      this.loadDefaultAddress();
      this.browsRecound(this.query.id);
    }
  },
  onShareAppMessage: function () {
    let merchantId = '';
    let path = '/integralshop/detail/detail?id=' + this.query.id + '&isShare=' + true;
    // console.log(!req.getStorage('userInfo').id);

    if (!req.getStorage('userInfo').id) {} else {
      path += '&userId=' + req.getStorage('userInfo').id;
    }

    // console.log(this.query.merchantId);
    let shopId = '';

      if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
      	path += '&merchantId=' + req.getStorage('MERCHANT').id;
      	merchantId = req.getStorage('MERCHANT').id;
      
      	if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
      		path += '&shopId=' + req.getStorage('smallShop').id;
      		shopId = req.getStorage('smallShop').id;
      		merchantId = req.getStorage('smallShop').merchantDTO.id;
      	}
      }


    route.share(1, req.getStorage('userInfo').id, path, merchantId, shopId, 1, this.query.id);
    // console.log(path);
    return {
      title: this.product.title,
      imageUrl: this.product.pic,
      path: path
    }; // let merchantId=''
    // // if(this.data.merchant.isDefault!=1){
    // //   merchantId=this.data.merchant.id
    // // }
    // if(this.query.merchantId) merchantId=this.query.merchantId
    // return {
    //   title: this.data.product.title,
    //   imageUrl: this.data.product.pic,
    //   path: '/integralshop/detail/detail?id=' + this.query.id + '&isShare=' + true + '&userId=' + req.getStorage('userInfo').id+'&merchantId='+merchantId
    // }
  },

  onReachBottom() {
    if (this.is_open_comments == 1 && this.tabIndex == 2) {
      this.form.page++;
      this.setData({
        ['form.page']: this.form.page
      });
      // this.selectComponent("#list").loadScore(this.current);
	  this.$refs.list.loadScore(this.current);
    }
  } // addShop() {//添加到小店
  //   req.postRequest('/api/shopProduct/save',{productId:this.data.product.id,type:1},data=>{
  //     console.log(data)
  //     this.setData({ isHide: false })
  //   })
  // },
  // hidePop() {//添加到小店
  //   this.setData({ isHide: true })
  // }
  ,

  methods: {
	  click(e){
	  		  // console.log(e)
	  		  this.hideShare=e
	  },
    showShare() {
		// #ifndef H5
      req.isLogin().then(success => {
        if (success) {
			this.setData({
			  hideShare: false
			});
          	this.getCodeUrl()
        }
      });
	  // #endif
    },

    /**
     * 轮播切换
     */
    swiperChange({
      detail
    }) {
      if (this.current == 0 && this.swiperCurrent > 1) {
        //卡死时，重置current为正确索引
        this.setData({
          current: this.swiperCurrent
        });
      } else {
        //正常轮转时，记录正确页码索引
        this.setData({
          swiperCurrent: detail.current
        });
      }
    },

    dotEvent(e) {
      this.setData({
        current: e.currentTarget.dataset.current
      });
    },

    browsRecound(id) {
      let from = {
        bindId: id,
        type: 1,
        page: '/integralshop/detail/detail?id=' + this.query.id
      }; //  if(this.query.scene){
      //    from.shareType=12
      //    from.page='/product/detail/detail?id=' + this.data.query.id +'&scene='+this.query.scene
      //    if(!this.data.params.merchantId){}else{
      //      from.merchantId=this.data.params.merchantId
      //    }
      //    if(!this.data.params.shopId){}else{
      //      from.shopId=this.data.params.shopId
      //    }
      //    if(!this.data.params.userId){}else{
      //      from.uid=this.data.params.userId
      //    }
      //  }

      if (this.query.isShare) {
        from.shareType = 1;
        from.page = '/integralshop/detail/detail?id=' + this.query.id + '&isShare=' + true;

        if (!this.query.userId) {} else {
          from.page += '&userId=' + this.query.userId;
        }

        if (!this.query.merchantId) {} else {
          from.merchantId = this.query.merchantId;
        }

        if (!this.query.shopId) {} else {
          from.shopId = this.query.shopId;
        }

        if (!this.query.userId) {} else {
          from.uid = this.query.userId;
        }
      }

      if (this.query.isShareTimeline) {
        from.shareType = 2;
        from.page = '/integralshop/detail/detail?id=' + this.query.id + '&isShareTimeline=' + true;

        if (!this.query.userId) {} else {
          from.page += '&userId=' + this.query.userId;
        }

        if (!this.query.merchantId) {} else {
          from.merchantId = this.query.merchantId;
        }

        if (!this.query.shopId) {} else {
          from.shopId = this.query.shopId;
        }

        if (!this.query.userId) {} else {
          from.uid = this.query.userId;
        }
      }

      req.postRequest('/api/browse', from, data => {});
    },

    // 选择服务门店
    updateShop() {
      let url = 'pages/nearby/nearby?isChoose=true';
      app.globalData.openPage(url); // let url = 'pages/nearby/nearby';
      // app.openPage(url)
    },

    loadCodeParams() {
      let _ts = this;

      return new Promise((resolve, reject) => {
        let form = {
          scene: _ts.scene
        };

        if (!_ts.scene) {
          resolve();
          return false;
        }

        if (_ts.merchantId) {
          // console.log("解析出来有门店");
          form.merchantId = _ts.merchantId;
        }

        req.getRequest('/api/code/params', form, data => {
          // console.log("====================================================================================" + data.merchantId);
          let res = data.scene.split('_');
          // console.log(res);
          this.query.id = res[0];
          this.query.merchantId = res[1];
          this.query.shopId = res[2]; // this.query.id = res[0];
          // this.query.merchantId = res[1];
          // this.query.shopId = res[2];

          if (res[1]) {
            this.setData({
              merchantId: res[1]
            });
          }

          if (res[2]) {
            this.setData({
              shopId: res[2]
            });
          }

          req.setStorage('pidCode', data.userId); // if (this.query.scene) {
          //   this.loadProudct();
          // }
          // this.browsRecound(this.query.id);

          resolve();
        });
      });
    },

    loadProudct(query) {
      // console.log(this.query)
      // const query = this.query;
      let that = this;
      // console.log(query.merchantId);
      let form = {
        id: query.id
      }; 
      if (query.merchantId) form.merchantId = query.merchantId;
	  let isShowLoading = false;
	  
	  if (!isShowLoading) {
	  	req.loadIng('加载中');
	  	isShowLoading = true;
	  }
      req.getRequest('/api/product/detail', form, data => {
        //富文本图片放大
        var nodes = data.detail;
        if (data.isOtc == 5) {
          uni.setNavigationBarTitle({
            title: '海外购'
          });
        }

        that.setData({
          bannerUrls: data.images,
          product: data,
          nodes: nodes,
		  allShow:true
        }); 
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
		// if (data.detail) {
        //   this.setData({ detail: data.detail.replace(/\<img/gi, '<img class="rich-img"') })
        // }
      });
    },

    getCodeUrl() {
      let that = this;
      let scene = that.product.id;

      if (!this.merchantId) {} else {
        scene += '_' + this.merchantId;
      }

      // console.log(scene); //获取小程序码

      const params = {
        page: 'integralshop/detail/detail',
        scene: scene
      }; // if(this.data.merchant&&this.data.merchant.isDefault!=1){
      //   params.merchantId=this.data.merchant.id
      // }

      if (this.query.merchantId) var merchantId = this.query.merchantId;
      req.getRequest('/api/program/codev', params, url => {
        that.setData({
          codeUrl: url
        });
      });
    },

    loadDefaultAddress() {
      if (req.isAuth()) {
        req.g('/api/address/default', data => {
          if (data) this.setData({
            address: data
          });else this.pointLocation();
        }, true);
      } else {
        this.pointLocation();
      }
    },

    pointLocation() {
      //定位当前位置
      let _ts = this;

      QQMapWX.initMap();
      req.getLocation(res => {
        QQMapWX.reverseGeocoder(res, data => {
          _ts.setData({
            'address.address': data.address
          });
        });
      });
    },

    toAddress() {
      app.globalData.openPage('mine/address/address');
    },

    atOnceBuy() {
      this.setData({
        isShow: true,
        isCart: false,
        popup: this.product
      });
    },

    addShopCart() {
      this.setData({
        isShow: true,
        isCart: true,
        popup: this.product
      });
    },

    hidePopup() {
      this.setData({
        isShow: false
      });
    },

    addCartSuccess(event) {
      this.setData({
        'product.count': parseInt(this.product.count) + parseInt(event.detail.quantity),
        isShow: false
      });
    },

    clickCollect() {
      let _ts = this;

      req.postRequest('/api/collect', {
        bindId: this.product.id,
        type: 1
      }, data => {
        _ts.setData({
          'product.isCollect': !_ts.product.isCollect
        });
      });
    },

    goTop: function (e) {
      // 一键回到顶部
      if (uni.pageScrollTo) {
        uni.pageScrollTo({
          scrollTop: 0
        });
      } else {
        uni.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        });
      }
    },

    onShareTimeline() {
      let merchantId = '';
      let path = 'id=' + this.query.id + '&isShareTimeline=' + true;

      if (!req.getStorage('userInfo').id) {} else {
        path += '&userId=' + req.getStorage('userInfo').id;
      }

      // console.log(this.merchantId);
      let shopId = '';

      if (!this.merchantId) {
        // console.log(123, path);
      } else {
        if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
          path += '&merchantId=' + req.getStorage('MERCHANT').id;
          merchantId = req.getStorage('MERCHANT').id;

          if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
            path += '&shopId=' + req.getStorage('smallShop').id;
            shopId = req.getStorage('smallShop').id;
            merchantId = req.getStorage('smallShop').merchantDTO.id;
          }
        }
      }

      let url = '/integralshop/detail/detail?' + path;
      route.share(2, req.getStorage('userInfo').id, url, merchantId, shopId, 1, this.query.id);
      // console.log(path, url);
      return {
        title: this.product.title,
        query: path,
        imageUrl: this.product.images[0]
      }; // return {
      //   title: this.data.product.title,
      //   path: this.data.product.images[0]
      // }
    },

    showTab: function (e) {
      this.setData({
        tabIndex: e.detail
      });
    },
    scoreTab: function (e) {
      this.form.page = 0;
      this.setData({
        current: e.detail,
        ['form.page']: 1
      });
    },
    freshenFun: function (e) {
      this.setData({
        freshen: e.detail
      });
    }
  }
};
</script>
<style>
@import "./detail.css";
</style>