import {getCoupon, getMaskCoupon,getAdBefore,getAdAfter} from './server/api'

const {windowWidth, windowHeight, model} = wx.getSystemInfoSync()
const menuInfo = wx.getMenuButtonBoundingClientRect()
const app = getApp();
const globalData = app.globalData;
const maxMove = 500 // 全局变量-控制回弹得最大距离
let startX = 0 // 全局变量-储存手指触摸之后得横向移动距离
let startY = 0 // 全局变量-储存手指触摸之后得纵向移动距离

// 根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
function getDirection(_startx, _starty, _endx, _endy) {
  const angx = _endx - _startx
  const angy = _endy - _starty
  let result = 0
  if (Math.abs(angx) < 10 && Math.abs(angy) < 10) return result // 如果滑动距离太短
  const angle = Math.atan2(angy, angx) * 180 / Math.PI // 获得角度
  if (angle >= -135 && angle <= -45) result = 1
  else if (angle > 45 && angle < 135) result = 2
  else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) result = 3
  else if (angle >= -45 && angle <= 45) result = 4
  return result
}

Component({
  properties: {
    serverUrl: {
      type: String,
      value: ''
    },
    token: {
      type: String,
      value: ''
    },
    locName: {
      type: String,
      value: ''
    },
    openid: {
      type: String,
      value: ''
    },
    extendParam: {
      type: [Object, Array, Number, String, Boolean]
    }
  },
  data: {
    appId: 'wxde69093658ce8aa8',
    homePath: '',
    jumpMiniAppInfo: {
      appId: '',
      path: '',
      ad_image: ''
    },
    menuInfo,
    isIpx: (model.search('iPhone X') !== -1 || model.search('iPhone13') > 1 || model.search('iPhone 11') !== -1) || false,
    material: {}, // 广告位数据
    coupon: [], // 页面优惠券列表
    curTab: 0, // 当前选中tab项
    scrollLeft: 0, // tab列表的横向滚动距离
    showMask: false, // 弹窗控制变量
    sign: '', // 弹窗券批量签名
    merchant: '', // 商户号
    empty: false, // 页面优惠券数据是否获取失败
    slidingDistance: 0, // 存储下拉回弹距离
    windowWidth, // 页面计算最小高度使用
    windowHeight, // 页面计算最小高度使用
    scrollTop: 0,
    showBackBtn: false, // 导航栏显示返回按钮
    getCouponSuccess:0,
    getMaskCouponSuccess:0,
  },
  lifetimes: {
    attached() {
      const {
        token, locName, openid, serverUrl, extendParam
      } = this.data
      if (!token || !locName || !openid || !serverUrl) {
        wx.showToast({icon: 'none', title: '缺少必传参数'})
        return
      }
      wx._hwjShareData = { // 设置共享数据
        serverUrl,
        token,
        loc_name: locName,
        openid,
        extendParam
      }
      console.log('globalData',globalData);
      this.setData({
        requestId:globalData.appOrderNo
      })
      this.getAdBefore()
      // 判断是否为分享进入
      const {scene} = wx.getEnterOptionsSync() || wx.getLaunchOptionsSync()
      const shareList = [1007, 1008, 1044, 1096] // 点击分享进入小程序得渠道列表
      const isShareInto = shareList.indexOf(scene) <= -1 // true：不是分享渠道进入小程序
      // 判断当前小程序页面栈
      const showBackBtn = getCurrentPages().length > 1
      this.setData({
        showBackBtn, // 当前小程序存在上一页
        isShareInto, // 保存isShareInto变量xml调用
        homePath: `/pages/index/index?channel=${locName}`
      })
      if (isShareInto) this.getMaskCoupon() // 不是分享进入得需要获取弹窗
      this.getCoupon()
      // this.getTabTop()
    },
    detached() {
      if (this._observer) this._observer.disconnect()
    },
    ready() {
      this.getTabTop()
    },

  },
  observers: {
    'getCouponSuccess, getMaskCouponSuccess': function(getCouponSuccess, getMaskCouponSuccess) {
      console.log('observers');
     if(getCouponSuccess==1&&getMaskCouponSuccess==1){
      this.getAdAfter()
     }
    }
  },
  methods: {
    getAdBefore() { // 接口调用成功后埋点
      console.log('this.data.requestId',this.data.requestId);
      getAdBefore({requestId:this.data.requestId}).then((res) => {
        console.log('getAdBefore--success')
      }).catch(()=>{})
    },
    getAdAfter() { // 接口调用成功后埋点
      getAdAfter({requestId:this.data.requestId}).then((res) => {
        console.log('getAdAfter--success')
      }).catch(()=>{})
    },
    onObserver() { // 因为tab切换不会触发scroll-view触底，故监听上滑切换分类wxml在界面显示判断是否触底
      this._observer = this.createIntersectionObserver()
      this._observer.relativeTo('.wrap').observe('.footer-tip-wrap', (res) => {
        this.setData({isBottom: res.intersectionRatio > 0})
      })
    },
    getTabTop() { // 初始化保存tabs距离窗口顶部的距离
      const add = wx.createSelectorQuery().in(this).select('.add')
      add.boundingClientRect((val) => {
        if (val && val.height) {
          this.tabTop = val.height / 2
        }
      }).exec()
    },
    async bindscroll(e) { // 监听页面滚动
      const {scrollTop} = e.detail
      const tabSticky = scrollTop >= this.tabTop + 30
      if (tabSticky !== this.data.tabSticky) this.setData({tabSticky})
    },
    bindNavBack() { // 导航栏点击返回事件
      wx.navigateBack()
    },
    bindHGoHwjMiniprogram(type) { // 弹窗领券后跳转到好物集小程序
      const {appId, path} = this.data.jumpMiniAppInfo
      if (type === 'half') {
        wx.openEmbeddedMiniProgram({
          appId,
          path: path || '',
          complete: res => {
            this.setData({showMask: false})
            console.log('打开半屏小程序结果', res)
          }
        })
      } else {
        wx.navigateToMiniProgram({
          appId: appId || this.data.appId,
          path: path || this.data.homePath,
          envVersion: 'release',
          complete: res => {
            this.setData({showMask: false})
            console.log('跳转到小程序结果：', res)
          }
        })
      }
    },
    getRpxToPx(rpx) { // rpx转换px
      return Math.floor((rpx / 750) * windowWidth)
    },
    bindChangeTab(e) { // 点击页面tab切换
      const curT = e.currentTarget
      this.setData({
        curTab: curT.dataset.id,
        scrollLeft: curT.offsetLeft > (windowWidth - this.getRpxToPx(272)) ? curT.offsetLeft : 0
      })
    },
    async bindChangeSwiper(e) { // 手动左右滑动切换页面
      const curTab = e.detail.current
      this.setData({
        curTab,
        scrollLeft: curTab > 3 ? windowWidth * parseFloat(curTab / 5, 0) : 0
      })
      if (this.data.tabSticky) this.setData({scrollTop: this.tabTop + 1})
    },
    bindTouchStart(e) { // 触摸开始
      this.setData({slidingDistance: 0})
      startX = e.changedTouches[0].clientX
      startY = e.changedTouches[0].clientY
    },
    async bindTouchMove(e) { // 触摸移动中
      if (!this.data.isBottom || this.data.curTab === (this.data.coupon.length - 1)) return
      const {clientX, clientY} = e.changedTouches[0]
      const direction = getDirection(startX, startY, clientX, clientY)
      if (direction === 3 || direction === 4) return // 如果左右滑动则禁止移动距离
      let y = maxMove
      if (clientY - startY <= maxMove) y = clientY - startY
      if (y > 0) return
      this.setData({slidingDistance: 0.3 * y}) // 为了清除卡顿问题，需要清除过渡效果, 移动系数0.3
    },
    async bindTouchEnd(e) { // 触摸结束-优惠券列表滚动到底部-切换下一个类目
      if (!this.data.isBottom || this.data.curTab === (this.data.coupon.length - 1)) return
      this.setData({slidingDistance: 0}, () => { // 添加过渡效果
        const {clientX, clientY} = e.changedTouches[0]
        const direction = getDirection(startX, startY, clientX, clientY)
        if (direction === 1) { // 1:上拉
          const t = setTimeout(() => {
            clearTimeout(t)
            this.setData({curTab: this.data.curTab + 1})
          }, 300)
        }
      })
    },
    bindCloseMask(e) { // 关闭弹窗
      console.log('弹窗点击回调', e)
      const data = {showMask: false}
      if (e.detail.success) {
        this.data.coupon.forEach(function (item, index) {
          if (item.stocks && item.stocks.length) {
            item.stocks.forEach(function (stock, i) {
              e.detail.coupon.forEach(function (c) {
                if (c.stock_id === stock.stock_id) {
                  data[`coupon[${index}].stocks[${i}].ustatus`] = 1
                  data[`coupon[${index}].stocks[${i}].coupon_code`] = c.coupon_code
                }
              })
            })
          }
        })
      }
      this.bindHGoHwjMiniprogram('half')
      this.setData(data)
    },
    sendCouponCallback(e) { // 商家券领券回调
      console.log('页面领券回调', e)
      if (!e.detail.success) return
      if (e.detail.coupon && e.detail.coupon.length) {
        const i = this.data.coupon[this.data.curTab].stocks.findIndex(function (item) {
          return item.stock_id === e.detail.coupon[0].stock_id
        })
        if (i > -1) {
          const stock = `coupon[${this.data.curTab}].stocks[${i}]`
          this.setData({
            [`${stock}.ustatus`]: 1,
            [`${stock}.coupon_code`]: e.detail.coupon[0].coupon_code
          })
        }
      }
    },
    async getMaskCoupon() { // 获取弹窗优惠券
      const {token, locName, openid} = this.data
      const res = await getMaskCoupon({token, loc_name: locName, openid,requestId:'123'})
      if (!res) return
      console.log('getMaskCoupon弹窗接口返回数据', res)
      const showMask = res.stocks && res.stocks.length > 0
      this.setData({
        maskCouponList: res.stocks || [],
        tempCode: res.temp_code || '',
        showMask,
        merchant: res.merchant || '',
        sign: res.sign || '',
        jumpMiniAppInfo: res.mini_app || {},
        getMaskCouponSuccess:1,
      }, () => !showMask && this.bindHGoHwjMiniprogram('half'))
    },
    async getCoupon() { // 获取页面优惠券
      const {
        token, locName, openid
      } = this.data

      getCoupon({token, loc_name: locName, openid,requestId:'123'}).then((res) => {
        if (!res) throw Error
        if (!res.data) return
        console.log('getCoupon页面接口返回数据', res)
        this.setData({
          coupon: res.data,
          material: res.material,
          getCouponSuccess:1
        })
        this.onObserver()
      }).catch(() => this.setData({empty: true}))
    }
  }
})
