/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-31 11:37:56
 * @LastEditors: HJ
 * @LastEditTime: 2021-04-20 17:48:28
 */
const { fhReceivedCoupon } = require("../../../api/store/index");
const { Tips, Loading, hLoading, bus } = getApp();
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true,
  },
  properties: {
    value: {
      type: Object,
      value: {},
      observer(v) {
        const { threshold, validPeriod, id, name } = v || {};
        const thresholdText = threshold ? `满${threshold}可用` : "无门槛";
        const vavlidPeriodText = `有效期${validPeriod}天`;
        const coupon = {
          ...v,
          thresholdText,
          vavlidPeriodText,
        };

        this.key = `${coupon}_${name}_${id}`;
        this.setData({
          coupon,
        });
      },
    },
    // 是否为详情展示
    detail: {
      type: Boolean,
      value: false,
    },
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    coupon: {},
  },
  // 组件方法
  methods: {
    init() {
      bus.on("updateCouponData", this.handlerCouponData.bind(this));
    },
    // 处理点击领取优惠券
    handlerReceive() {
      const {
        coupon: { isReceived, id },
      } = this.data;

      if (!isReceived && id) {
        this.receivedCoupon(id);
      }
    },
    // 领取优惠券
    async receivedCoupon(couponId) {
      const memberId = wx.getStorageSync("memberId");
      if (!memberId) {
        wx.navigateTo({
          url: "/pages/authorization/authorization",
        });
        return;
      }

      Loading("领取中...");
      try {
        await fhReceivedCoupon(couponId);
        Tips("领取优惠券成功");
        this.setData(
          {
            "coupon.isReceived": true,
          },
          () => {
            bus.emit("updateCouponData", {
              key: this.key,
              data: this.data.coupon,
            });
          }
        );
      } catch (e) {
  console.error("debug axios", e);
        hLoading();
      }
    },
    // 更新优惠券数据
    handlerCouponData({ key, data }) {
      if (key === this.key) {
        const { coupon } = this.data;
        this.setData({
          coupon: {
            ...coupon,
            ...data,
          },
        });
      }
    },
  },
  // 组件生命周期
  lifetimes: {
    attached() {
      this.init();
    },
  },
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data;

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return;
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true,
      });

      // 清除定时器等操作
    },
  },
};

Component(componentOptions);
