/* eslint-disable arrow-parens */
import { connect } from 'herculex';
import { updateGlobalData } from '../../utils/initMallList';
import { createSubscribe } from 'applet-page-component';
import { updateCar, queryForCarList, queryForStartTip } from '../mall-index/service';
import getLocationInfo from '../../utils/getLocationInfo';
import { queryForGoodsDetail } from './service';
import { getJumpStoreId } from '../../service/store';
import { DEFAULT_GOODS } from '../../utils/const';
import { isActive } from '../../utils';
const app = getApp();
Component(createSubscribe({
  async onShow() {
    const {
      skuId = 0
    } = this.$page.data.query;
    const {
      globalShopId
    } = this.data;
    await this.dispatch('getCardLevel');

    if (skuId && globalShopId) {
      this.initData({
        skuId,
        globalShopId
      });
    } else {
      const {
        jumpStoreId,
        skuId: newSkuId
      } = this.data;
      this.initData({
        skuId: newSkuId,
        globalShopId: jumpStoreId
      });
    }
  }

})(connect({
  mapStateToProps: {
    globalCar: state => state.$global.globalCar || [],
    globalShopId: state => state.$global.globalShopId || '',
    jumpSkuId: state => state.$global.jumpSkuId || '',
    memberLevel: state => state.$global.memberLevel || 'NONE'
  }
})({
  props: {},
  data: {
    goodsDetail: null,
    btnText: '去结算',
    tabBarHight: 0,
    skuId: 0,
    errorImg: DEFAULT_GOODS,
    componentData: {},
    currentIndex: 1,
    showFlag: false,
    startDeliveryAmount: 0,
    jumpStoreId: '',
    productId: '',
    header: '',
    isMember: false,
    memberPrice: 0
  },

  async didMount() {
    const {
      skuId = ''
    } = this.$page.data.query;
    const {
      globalShopId
    } = this.data;
    await this.dispatch('getCardLevel');

    if (skuId && globalShopId) {
      this.initData({
        skuId,
        globalShopId
      });
    } else {
      // 外部跳转
      await getLocationInfo();
      const {
        regionData
      } = app.globalData;
      const {
        query: {
          productId
        } = {}
      } = this.$page.data;
      const {
        latitude,
        longitude
      } = regionData || {};

      if (productId) {
        // 外部跳转
        const {
          shopId = '',
          skuId: newSkuId = ''
        } = (await getJumpStoreId({
          productId,
          latitude,
          longitude
        })) || {};

        if (!shopId) {
          return my.alert({
            content: '关联商品已不可购买,请选购商城其他商品',
            success: () => {
              my.navigateTo({
                url: '/pages/one/index?pageCode=shopIndex'
              });
            }
          });
        }

        this.initData({
          skuId: newSkuId,
          globalShopId: shopId
        });
        this.setData({
          jumpStoreId: shopId,
          productId,
          header: 'show'
        });
        my.setNavigationBar({
          title: '商品详情'
        });
      } else {
        my.showToast({
          content: '商场配置的跳转参数不正确'
        });
      }
    }
  },

  methods: {
    // swiper 滑动
    onSwiperChange(e) {
      const {
        detail: {
          current = 1
        }
      } = e;
      this.setData({
        currentIndex: current + 1
      });
    },

    // 获取当前商品在购物车中的数量
    getCarQuantity({
      skuId = '',
      carList = []
    }) {
      const index = carList.findIndex(v => v.skuId === skuId); // 找到了

      if (index !== -1) {
        return carList[index].quantity || 0;
      }

      return 0;
    },

    async initData({
      skuId,
      globalShopId
    }) {
      try {
        // 查询购物车
        const car = await queryForCarList({
          shopId: globalShopId
        });
        updateGlobalData.call(this, car); // 查询对应skuId的商品

        const res = await queryForGoodsDetail({
          skuId
        }); // 获取购物车中商品数量

        const quantity = this.getCarQuantity({
          skuId,
          carList: car.carts
        }); // 查询起送信息

        const {
          showFlag,
          startDeliveryAmount
        } = await queryForStartTip({
          shopId: globalShopId
        });
        const {
          memberLevel
        } = this.data;
        const {
          memberPrices
        } = res;

        if (memberPrices) {
          this.setData({
            isMember: true,
            memberPrice: this.getMemberPrice(memberPrices, memberLevel)
          });
        }

        this.setData({
          goodsDetail: { ...res,
            quantity
          },
          skuId,
          showFlag,
          startDeliveryAmount
        });
      } catch (err) {
        console.log(err);
        my.showToast({
          content: err.msg || '查询商品详情失败',
          type: 'fail'
        });
      }
    },

    getMemberPrice(priceSetting, level) {
      if (priceSetting.length === 1) {
        // 统一会员价
        return priceSetting[0].membershipPrice;
      }

      if (level === 'NONE') {
        return priceSetting[0] ? priceSetting[0].membershipPrice : 0;
      }

      const item = priceSetting.filter(v => v.level === level);
      return item[0] ? item[0].membershipPrice : 0;
    },

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

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

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

    // 点击stepper回调 @params { number: value ,type: ADD | SUBTRACT }
    changeNum(e) {
      const {
        type
      } = e;
      const {
        goodsDetail,
        skuId
      } = this.data;

      if (!isActive(goodsDetail) && type === 'ADD') {
        return;
      }

      this.handelCarChange({
        skuId,
        number: 1,
        type
      });
    },

    // 点击添加购物车按钮 显示 步进器
    async handleAddCarClick() {
      // 商品在售状态
      const {
        goodsDetail,
        skuId
      } = this.data; // 不在售

      if (!isActive(goodsDetail)) {
        return;
      }

      this.handelCarChange({
        skuId,
        number: 1,
        type: 'ADD'
      });
    },

    /**
     * 加入购物车操作被点击
     * @params { skuId, number: value ,type: ADD | SUBTRACT }
     */
    async handelCarChange(e) {
      const {
        skuId,
        number,
        type
      } = e;
      const {
        globalShopId,
        skuId: curSkuId
      } = this.data; // 发起请求 更新购物车

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

        const newCar = await queryForCarList({
          shopId: globalShopId
        });
        updateGlobalData.call(this, newCar);
        my.hideLoading();
      } catch (err) {
        my.hideLoading();
        my.showToast({
          content: err.msg,
          type: 'none'
        });
      } // 查询最新skuId的商品


      const res = await queryForGoodsDetail({
        skuId: curSkuId
      }); // 查询购物车

      const car = await queryForCarList({
        shopId: globalShopId
      }); // 获取购物车中商品数量

      const quantity = this.getCarQuantity({
        skuId,
        carList: car.carts
      });
      const detail = { ...res,
        quantity
      };
      this.setData({
        goodsDetail: detail
      });
    }

  }
})));