// index.ts

import { api_shopProduct } from "../../api/login";
import { debounce } from '../../utils/util'

// 获取应用实例
const app = getApp<IAppOption>()
// pages/orders/orders.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    serviceShow: true,
    scrollTop: 0,
    current: 0,
    autoplay: false,
    interval: 5000,
    duration: 500,
    popupShow: false,
    list: [] as any,
    isOverSaled: false, // 是否所有商品都没有库存
    selected: {} as any,
    opacity: 0,
    scrolIntoViewStr: '',
    scrolIntoView: '',
    scrollDiscount: false, // 是否扣减启
    scrollIntoViewType: false,
    headerHeight: 0, // 头部的高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // this.onInit()
  },
  onReady() {
    const that = this
    wx.createSelectorQuery().select('#scroll-header').boundingClientRect(function (rect) {
      that.setData({
        headerHeight: rect.height
      })
    }).exec();
  },
  /**
   * 获取基础信息
   */
  async onInit() {
    try {
      const { data } = await api_shopProduct({ appId: app.globalData.appId });
      const list = data.data || []
      let selected: any = {}
      let isOverSaled = true // 是否销售完
      list.forEach((item: any) => {
        item.originalPrice = this.formatPrice(item.originalPrice, 'ALL');
        item.showSalePrice = this.formatPrice(item.salePrice, 'ALL');
        item.typeName = this.formatPeriod(item.num, item.period);
        item.discountPrice = this.formatPrice(item.originalPrice - item.salePrice, 'ALL')
        const prices: any = this.formatPrice(item.salePrice)
        item.integerPart = prices.integerPart
        item.decimalPart = prices.decimalPart
        if(item.stockNum > 0) {
          isOverSaled = false
          if( !selected.id) {
            selected = item
          }
        }
      });
      if(isOverSaled) {
        // 没有可购买商品则默认选中第一个商品
        selected = list[0]
      }

      this.setData({
        list,
        isOverSaled,
        selected
      })
    } catch(e) {
      console.log(e, 'e')
    }
  },
  // 格式化价格
  formatPrice(price: number, type?: string) {
    const amountStr = price.toFixed(2)
    const [integerPart, decimalPart] = amountStr.split('.');
    if(type === 'ALL') {
      return amountStr
    }
    return {
      integerPart,
      decimalPart
    }
  },
  // 格式化类型
  formatPeriod(num: number, type: string) {
    const template: any = {
      DAY: "天卡",
      MONTH: "月卡",
      YEAR: "年卡"
    }
    if(type === "YEAR" && num >= 99) {
      return '永久卡'
    }
    return num + template[type]
  },
  // 选择
  onSelectGoods(e: any) {
    const { dataset } = e.currentTarget
    const item = this.data.list.find((item: any) => item.id === dataset.id)
    // 判断是否有库存
    if(item.stockNum <= 0) {
      return
    }
    this.setData({
      selected: item || {}
    })
  },
  // 事件处理函数
  changeSwiper(e: any) {
    const detail = e.detail;
    if(detail.source === 'touch' || detail.source == 'autoplay') {
      this.setData({
        current: detail.current
      })
    }
  },
  isLogin() {
    // 判断是否登录
    if(!app.globalData.isLogin) {
      wx.navigateTo({
        url: '../login/login',
      })
      return false
    }
    return true
  },
  /** 我的订单 */
  onOrder() {
    // 判断是否登录
    if(!this.isLogin()) {
      return
    }
    wx.navigateTo({
      url: '../orders/orders',
    })
  },
  onBuyShop() {
    // 判断是否登录
    if(!this.isLogin()) {
      return
    }
    this.setData({
      popupShow: true
    })
  },
  onClose() {
    this.setData({
      popupShow: false
    })
  },
  onSubmit() {
    // 判断是否登录
    const that = this
    debounce(function () {
      if(!that.isLogin()) {
        return
      }
      let info = JSON.stringify({
        ...that.data.selected
      });
      // console.log(that.data.selected, "that.data.selected")
      info = encodeURIComponent(info);
      wx.navigateTo({
        url: `../orders/order-detail?orderInfo=${info}`,
      })
      that.setData({
        popupShow: false
      })
    }, 500)()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onInit()
    this.setData({
      serviceShow: true
    })
  },
  onHide() {
    this.setData({
      serviceShow: false
    })
  },
  // onReady() {
  //   const scrollView = this.selectComponent('#scrollarea');
  //   console.log(scrollView, 'scrollView')
  // },
  // 页面滚动时颜色变化
  onScrollView(e: { detail: any }) {
    const top = e.detail.scrollTop || 0 
    // 从100开始显示
    this.setData({
      opacity: top < 100 ? 0 : (top - 100) > 150 ? 1 : (top - 100) / 150
    })
    if(this.data.scrollIntoViewType) {
      this.setData({
        scrollTop: this.data.scrollDiscount ? top - this.data.headerHeight : top,
        scrollIntoViewType: false,
        scrollDiscount: false,
      })
    } else {
      this.onChangeScroll()
    }
  },
  onChangeScroll() {
    const that = this;
    debounce(function() {
      wx.createSelectorQuery().select('#type3').boundingClientRect(function (rect) {
        if(rect.top > 0 &&  rect.top <= that.data.headerHeight) {
         that.setData({
           scrolIntoViewStr: 'type3',
         })
        }
      }).exec();
      wx.createSelectorQuery().select('#type2').boundingClientRect(function (rect) {
        if(rect.top > 0 &&  rect.top <= that.data.headerHeight) {
          that.setData({
            scrolIntoViewStr: 'type2'
          })
        }
        if(rect.top > 0 && rect.top > that.data.headerHeight) {
          that.setData({
            scrolIntoViewStr: 'type1'
          })
        }
      }).exec();
    }, 600)()
    
    
  },
  onTapAnchor(e: { currentTarget: { dataset: any } }) {
    const type = e.currentTarget.dataset.type
    this.setData({
      scrolIntoView: type,
      scrolIntoViewStr: type,
      scrollDiscount: type !== 'type3' ? true : false,
      scrollIntoViewType: true,
    })
  }
})