// pages/productDetail/productDetail.js
var app = getApp()
const wxService = require('../../utils/wxService')
import { Integer } from '../../utils/integerDigitalConvertion'
const utils = require('../../utils/util')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    productId: '',
    scrollTips: '继续拖动，查看图文详情', // 滑动文案
    productInfo: '',
    showHtml: false,
    reachBottom: false, // 标识是否触底
    showSkuPopup: false,
    btnText: '确定',
    baseImgUrl: app.globalData.imageUrl,
    swiperCurrent: 0,
    selectSkuName: '',
    openPlusStatus: false,
    memberLevel: false,
    showCardModal: false,
    currentShareContent: null,
    fromZc : false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    if (options && options.id) {
      this.setData({
        productId: options.id,
        fromZc: options.fromZc == 1 
      });
      //不是从种草过来的， 需要清除本地临时的触点信息
      if (!options.fromZc){
        wx.removeStorageSync('TEMP_TENTACLE_INFO');
        wx.removeStorageSync('TIME_EXPIRATION');
      }
    }
  },

  swiperChange(e) {
    console.log(e)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  addCart: function (event) {
    this.setData({
      showSkuPopup: true,
      showSkuPopupType: 'cart'
    })
    // 商品加入购物车
    // xm_bi.Event.stat("skuAddToCart", { "amount":"666","skuId":'abcd1234'});
  },
  goBuy: function (event) {
    this.setData({
      showSkuPopup: true,
      showSkuPopupType: 'buy'
    })
  },

  // 分享
  onTapShare() {
    let content = {
      title: this.data.productInfo.productName,
      id: this.data.productInfo.productId,
      url: this.data.productInfo.indexUrl
    }
    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: this.data.productInfo.productId,
      contentType: app.globalData.contants.SHARE_TYPE.PRODUCT_DETAIL, //内容类型 
      title: this.data.productInfo.productName, //标题
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    }

    this.data.currentShareContent = this.data.productInfo;
    this.data.currentShareContent.id = this.data.productInfo.productId;

    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.tentacleId) {
        this.data.currentShareContent.tentacleId = res.tentacleId;
        let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
        let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
        var path = 'pages/productDetail/productDetail?i=' + id + '&t=' + tentacleId;
        this.setData({
          showCardModal: true,
          cardTitle: this.data.productInfo.productName,
          cardUrl: this.data.productInfo.indexUrl,
          pagePath: path
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getProInfo()
    this.getOpenStatus()
    this.data.currentShareContent = null
  },

  //获取商品详情
  getProInfo() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/sale/product/buyer/findByProductId?productId=${this.data.productId}`).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        wx.hideLoading()
        this.setData({
          productInfo: data
        })
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  // 获取会员等级开关
  getMemberLevel() {
    wxService.get(`/merchant/brandSwitchSetting/getOpenStatus?businessType=2`).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          memberLevel: data
        })
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  // 获取plus会员开关
  getOpenStatus() {
    wxService.get(`/merchant/brandSwitchSetting/getOpenStatus?businessType=3`).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          openPlusStatus: data
        })
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  // 页面touchstart事件
  pageTouchStart: function (e) {
    if (this.data.showHtml) {
      return
    }
    this.setData({
      reachBottom: false,
      startTouchY: null
    })
  },

  // 页面touchend事件
  pageMoveEnd: function (e) {
    if (this.data.showHtml) {
      return
    }
    if (this.data.startTouchY - e.changedTouches[0].pageY >= 50) {
      this.setData({
        showHtml: true,
        scrollTips: ''
      })
    }
  },

  // 页面touchmove事件
  pageMove: function (e) {
    if (this.data.showHtml) {
      return
    }
    wx.createSelectorQuery().selectViewport().scrollOffset((pageRes) => {
      wx.createSelectorQuery().select('.product-container').fields({
        size: true
      }, (res) => {
        if (res.height >= app.globalData.systemInfo.windowHeight + pageRes.scrollTop) {
          this.setData({
            reachBottom: true
          })
        } else {
          if (this.data.reachBottom) {
            this.setData({
              reachBottom: false
            })
          }
        }
        if (this.data.startTouchY == null) {
          this.setData({
            startTouchY: e.changedTouches[0].pageY
          })
        }
      }).exec()
    }).exec()
  },

  confirmClick(event) {
    const { skuId, count } = event.detail
    const trolleySku = {
      count,
      skuId
    }

    var selectSkuName = []
    for (let i in event.detail.selectSku) {
      selectSkuName.push(event.detail.selectSku[i].name)
    }
    var selectSkuStr = selectSkuName.join(',')
    this.setData({
      selectSkuName: selectSkuStr
    })

    if (this.data.showSkuPopupType == 'cart') {
      // 加入购物车
      this.getPutCart(trolleySku)
    } else if (this.data.showSkuPopupType == 'buy') {
      // 关闭弹框
      this.setData({
        showSkuPopup: false
      }, () => {
        // 去下单页 && 参数
        let trolleySku2Buy = []
        trolleySku2Buy.push(trolleySku)

        let parmas = {
          trolleySku2Buy: JSON.stringify(trolleySku2Buy)
        }
        //判断是否从种草商品过来购买
        if (fromZc){
          wxService.updateLocalTentacleInfo();
        }
        wxService
          .router('/pages/confirmOrder/confirmOrder')
          .search(parmas)
      })
    }
  },
  // put 购物车
  getPutCart(trolleySku) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post('/sale/trolley/put', trolleySku).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          // 关闭弹框
          this.setData({
            showSkuPopup: false
          })
          wx.hideLoading()
          wx.showToast({
            title: '添加成功，在购物车等亲~',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
    let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
    var path = 'pages/productDetail/productDetail?i=' + id + '&t=' + tentacleId;
    console.log(path)
    return {
      path: path
    }
  }
})