/* eslint-disable arrow-parens */
import { getHeaderHeight } from '../../utils';
import { connect } from 'herculex';
import { createSubscribe } from 'applet-page-component';
import { initMallData, updateGlobalData } from '../../utils/initMallList';
import { updateCar, queryForCarList, queryForGoodsList, queryForStartTip } from './service';
import showToast from '../../utils/showToast';
Component(createSubscribe({
  onShow() {
    const {
      globalShopId
    } = this.data;
    const {
      globalShopId: stateShopId
    } = this.$store.stateConfig.$global;

    if (globalShopId === stateShopId) {
      this.initWithLoading();
    }
  },

  onPageScroll() {// this.isArriveTop();
  }

})(connect({
  mapStateToProps: {
    globalTabs: state => state.globalTabs || [],
    globalGoodsList: state => state.globalGoodsList || [],
    globalCar: state => state.$global.globalCar || [],
    globalShopId: state => state.$global.globalShopId || '',
    headB2bHight: state => state.$global.headB2bHight || 0,
    userInfo: state => state.$global.userInfo || {},
    jumpSkuId: state => state.$global.jumpSkuId || '',
    memberLevel: state => state.$global.memberLevel || ''
  }
})({
  props: {
    componentData: {}
  },

  async didUpdate(preProps, preData) {
    if (preData.globalShopId !== this.data.globalShopId && this.data.globalShopId !== '') {
      this.setData({
        hasLocation: true
      });
      this.initWithLoading();
    }
  },

  didMount() {},

  data: {
    hasLocation: false,
    activeTab: 0,
    headerHight: getHeaderHeight(),
    carTotalNum: 0,
    scrollArriveTop: false,
    tabBarHight: 0,
    jumpId: '',
    // jumpItem: [tabIndex, index]
    jumpItem: [0, 0],
    extraTotalHight: 0,
    showFlag: false,
    startDeliveryAmount: 0,
    emptyImage: 'https://gw.alipayobjects.com/mdn/rms_0e8a29/afts/img/A*uhaRQLLUyZ0AAAAAAAAAAAAAARQnAQ'
  },
  methods: {
    // saveRef 调用子组件click
    saveRef(ref) {
      // 存储自定义组件实例，方便以后调用
      this.childClickFunc = ref;
    },

    // saveCarRef 调用购物车 子组件方法
    saveCarRef(ref) {
      // 存储自定义组件实例，方便以后调用
      this.carRef = ref;
    },

    // 将自组件的确认方法 放到确认按钮
    handleConfirm() {
      this.carRef.handelCreateOrder();
    },

    // 将自组件的打开购物车方法 放到购物车按钮
    handleCarClick() {
      this.carRef.openPopup();
    },

    // 刷新界面
    refreshPage() {
      my.navigateTo({
        url: './index'
      });
    },

    // init with loading
    async initWithLoading() {
      my.showLoading();

      try {
        await this.initGoodsList();
        my.hideLoading(); // 获取底部 头部高度

        this.queryHight();
        const {
          jumpId,
          globalGoodsList
        } = this.data;

        if (jumpId) {
          globalGoodsList.some((tabItem, tabIndex) => {
            return tabItem.list.some((item, index) => {
              if (item.skuId === jumpId) {
                this.setData({
                  jumpItem: [tabIndex, index]
                });
                return true;
              }

              return false;
            });
          });
        }

        const [jumpActive, jumpIndex] = this.data.jumpItem;
        this.setData({
          activeTab: jumpActive
        });
        const distance = await this.queryScrollDistance(jumpIndex);
        jumpId ? this.childClickFunc.handleGotoItem(jumpActive, distance) : this.childClickFunc.clickRef(jumpActive); // 获取配送提示
        // 获取配送提示栏高度

        this.extraComponentHight();
      } catch (err) {
        my.hideLoading();
        showToast({
          content: err.msg,
          type: 'none'
        });
      }
    },

    // init
    async initGoodsList() {
      const {
        jumpSkuId = ''
      } = this.data; // 是跳转过来的

      this.setData({
        jumpId: jumpSkuId
      });
      this.commitGlobal && this.commitGlobal({
        jumpSkuId: ''
      });
      const {
        globalShopId
      } = this.data; // 获取商品列表数据

      const list = await queryForGoodsList({
        shopId: globalShopId
      }); // 获取购物车数据

      const car = await queryForCarList({
        shopId: globalShopId
      }); // 查询起送信息

      const {
        showFlag,
        startDeliveryAmount
      } = await queryForStartTip({
        shopId: globalShopId
      }); // 初始化数据

      const {
        leftTabs,
        goodsList
      } = initMallData({
        tabs: list,
        carList: car.carts
      });
      this.commitGlobal && this.commitGlobal({
        globalCar: car
      });
      this.commit && this.commit({
        globalTabs: leftTabs,
        globalGoodsList: goodsList
      }); // header 高度

      this.setData({
        activeTab: 0,
        showFlag,
        startDeliveryAmount
      });
    },

    // 点击左侧栏目
    // handleChange(index) {
    //   this.setData({
    //     activeTab: index,
    //   });
    // },
    // // 滑动右侧
    onChange(index) {
      this.setData({
        activeTab: index
      });
    },

    /**
     * 某个goodsItem 被点击
     * @params { skuId, number: value ,type: ADD | SUBTRACT }
     */
    async handelItemChange(e) {
      const {
        skuId,
        number,
        type
      } = e;
      const {
        globalShopId
      } = this.data; // 发起请求 更新购物车

      try {
        // @param shopId skuId num type
        my.showLoading();
        await updateCar({
          shopId: globalShopId,
          skuId,
          num: number,
          type
        }); // 发起请求 查询购物车

        const car = await queryForCarList({
          shopId: globalShopId
        });
        my.hideLoading();
        updateGlobalData.call(this, car);
      } catch (err) {
        my.hideLoading();
        showToast({
          content: err.msg
        });
      }
    },

    extraComponentHight() {
      my.createSelectorQuery().select('.shop-deliver-info').boundingClientRect().exec(ret => {
        ret && this.setData({
          extraTotalHight: ret.reduce((total, item) => total + (item ? item.height : 0), 0)
        });
      });
    },

    isArriveTop() {
      my.createSelectorQuery().selectAll('.group-text').boundingClientRect().select('.mall-index-container').boundingClientRect().exec(ret => {
        const {
          top: rightTop
        } = ret[0][0];
        const {
          top: totalTop
        } = ret[1]; // 到达顶部

        if (getHeaderHeight() - totalTop > 0) {
          // 往下滑
          if (this.preRightTop - rightTop > 0) {
            this.setData({
              scrollArriveTop: true
            });
          } else {
            // 往上滑
            this.setData({
              scrollArriveTop: !(totalTop - rightTop <= 1)
            });
          }
        }

        this.preRightTop = rightTop;
      });
    },

    // 获取商品高度
    queryScrollDistance(itemIndex) {
      return new Promise(resolve => {
        my.createSelectorQuery().select('.goods-item-container').boundingClientRect().select('.group-text').boundingClientRect().exec(ret => {
          const goodsItemHeight = ret[0] ? ret[0].height : 0;
          const titleHeight = ret[1] ? ret[1].height : 0;
          console.log(titleHeight, goodsItemHeight, 'Height');
          console.log(ret[0], ret[1], 'ret');
          resolve(titleHeight + goodsItemHeight * itemIndex);
        });
      });
    },

    // 获取tabbar高度
    queryHight() {
      my.createSelectorQuery().select('.tabbar-box.fixed').boundingClientRect().exec(ret => {
        const tabBarHight = ret[0] ? ret[0].height : 0;
        this.setData({
          tabBarHight
        });
      });
    }

  }
})));