import { connect } from 'herculex';
import { getIn } from 'herculex/dist/utils/manipulate';
import { notifyMktApply, messageSubscribeNotify } from '../../utils/service';
import { promisify } from '../../utils/';
import { promisifyCallback } from '../../utils/jsapi';

const app = getApp();
Component(connect({
  mapStateToProps: {
    cityCode: state => state.$global.cityCode,
    mktCode: state => state.$global.mktCode,
    scopes: state => state.$global.scopes,
    userInfo: state => state.$global.userInfo,
    memberInfo: state => state.getIn(['memberCardComponent', 'componentExtInfo', 'memberInfo'], {}),
  },
})({
  data: {
    canIUse: my.canIUse('mkt'),
    hasMktData: true, // 券组件是否有数据
    imgSrcPrefix: app.globalData.imgSrcPrefix,
  },
  props: {
    componentData: {},
  },
  didMount() {
    // 无定位信息，则需要弹起授权
    const { cityCode, mktCode } = this.data;
    if (!cityCode && !mktCode && app.globalData.showRegion !== 'Y') {
      this.getLbs();
    }
    this.setData({
      hasMktData: true,
    });
  },
  methods: {
    async getLbs() {
      const [, res] = await this.dispatchGlobal('getRegions');
      if (res && res.cityAdcode) {
        const { userInfo = {} } = this.data;
        const needCheckLogin = getIn(this.props, ['componentData', 'componentExtInfo', 'isLogin'], 0);
        // 券组件需要校验登录且没有登录时，显示弹框
        if (+needCheckLogin === 1 && !userInfo.isLogin) {
          this.commit({
            showLoginModal: true,
          });
        }
      }
    },

    async joinMember() {
      const isLogin = getIn(this.props, ['componentData', 'componentExtInfo', 'isLogin'], 0);
      if (+isLogin === 2) {
        // 登录
        await this.dispatch('customerCheck'); // 会员验证
        // if (res === 'addCardFail') return false; // 开卡失败拦截
      }
    },

    onSubmit(e) {
      this.commit('$global:updateFormId', {
        formId: e.detail.formId,
      });
      const { scopes } = this.data;
      if (!scopes) {
        // 没有scope 走第一种登录方式
        this.dispatchGlobal('doLogin');
      }
    },
    async onGetAuthorize() {
      const { scopes } = this.data;
      if (!scopes) return;
      this.dispatchGlobal('doLogin');
    },

    onRender(e) {
      // my.alert({
      //   content: e.detail,
      // });
      // eslint-disable-next-line no-unused-vars
      const { campAmount, campaigns = [] } = e.detail;
      if (+campAmount === 0) {
        this.setData({
          hasMktData: false,
        });
      }
      if (!this.data.hasMktData && +campAmount > 0) {
        this.setData({
          hasMktData: true,
        });
      }
    },

    async onApplySuccess(e) {
      console.log('> MKT onApplySuccess', e);

      const notifyOnRecv = getIn(this.props, ['componentData', 'componentExtInfo', 'notifyOnRecv'], 'N');
      const notifyMsgMixId = getIn(this.props, ['componentData', 'componentExtInfo', 'msgTemplateId'], '').trim();

      if (notifyOnRecv == 'N') {
        return;
      }

      if (notifyMsgMixId == null || notifyMsgMixId.length == 0) {
        return;
      }

      // 检查是否需要订阅消息
      const [, res] = await promisify(my.loadPlugin)({ plugin: '2021001155639035@*' });
      if (!res) {
        return;
      }

      this.commit('$global:updateState', {
        isMessagePluginLoad: true,
      });

      // eslint-disable-next-line
      const msgPlugin = requirePlugin('dynamic-plugin://2021001155639035') || {};
      const { requestSubscribeMessage } = msgPlugin;
      if (typeof requestSubscribeMessage !== 'function') {
        return;
      }

      const promisifyRequestSubscribeMessage = promisifyCallback(requestSubscribeMessage);

      const ids = notifyMsgMixId.split(';');
      const templateId = ids[0];
      const alipayTemplateId = ids[1];

      const userResult = await promisifyRequestSubscribeMessage({ entityIds: [alipayTemplateId] });

      if (!userResult.success) {
        return;
      }

      messageSubscribeNotify({ userResult, templateIds: [notifyMsgMixId] });

      const mktEventId = e.detail.id;
      await notifyMktApply({ eventId: mktEventId, alipayTemplateId, templateId });
    },

    onError(e) {
      console.log('> MKT onError', e);
    },
    onApplyFail(e) {
      console.log('> MKT onApplyFail', e);
    },
  },
}));
