import { connect } from 'herculex';
import { setStorage } from '../../utils';

const app = getApp();
Component(connect({
  mapStateToProps: {
    pageUuid: state => state.pageUuid,
  },
})({
  props: {
    componentData: {},
  },
  data: {
    imgSrcPrefix: app.globalData.imgSrcPrefix,
    show: false,
    key: 'ADVERT_SHOW',
  },
  didMount() {
    this.init();
  },
  methods: {
    async init() {
      const { key, pageUuid } = this.data;
      const {
        serviceList,
        componentExtInfo,
      } = this.props.componentData;
      let showRate = componentExtInfo.showRate || 0;
      showRate = parseInt(showRate);
      const service = serviceList[0];
      let { data } = my.getStorageSync({ key }) || {};
      let rate = 0;
      if (showRate < 0) return;
      if (data && data[pageUuid]) {
        rate = data[pageUuid].serviceUUID === service.serviceUUID ? data[pageUuid].showRate : 0;
        if (!data[pageUuid].show || (rate >= showRate && showRate !== 0)) return;
      }
      this.setData({
        show: true,
      });
      rate += 1;
      data = {
        ...data,
        [pageUuid]: {
          show: false,
          showRate: rate,
          serviceUUID: service.serviceUUID,
        },
      };
      await setStorage(key, data);
    },
    onModalClose() {
      this.setData({ show: false });
    },
  },
}));
