import { connect } from 'herculex';
import { getIn } from 'herculex/dist/utils/manipulate';
import { getAppId, aliTracertTa } from '../../utils/jsapi';
import { createSubscribe } from 'applet-page-component';

const app = getApp();
Component(
  createSubscribe({
    onShow() {
      const { componentData: { componentType } } = this.props;
      const { data } = my.getStorageSync({ key: componentType });
      // 缓存中的页面id是当前id 执行onshow
      if (this.$id === data) {
        this.componentShow();
      }
    },
  })(
    connect({
      mapStateToProps: {
        regionCode: state => state.$global.regionCode,
        titleBarHeight: state => state.$global.titleBarHeight || 0,
        userInfo: state => state.$global.userInfo || {},
        memberLevel: state => state.$global.memberLevel || 'NONE',
        memberRes: state => state.$global.memberRes || '',
      },
    })({
      data: {
        defaultAtvar:
          'https://gw.alipayobjects.com/mdn/rms_47fd3e/afts/img/A*8THwT7aSeiYAAAAAAAAAAABkARQnAQ',
        imgSrcPrefix: app.globalData.imgSrcPrefix,
        defaultBackImg:
          'https://gw.alipayobjects.com/mdn/rms_8ed4a1/afts/img/A*BrKyS7jkmFwAAAAAAAAAAAAAARQnAQ',
        isLogin: false,
        defaultIcon:
          'https://gw.alipayobjects.com/mdn/rms_8ed4a1/afts/img/A*m7DmQLHFYBUAAAAAAAAAAAAAARQnAQ',
        APPID: getAppId(),
      },
      props: {
        componentData: {},
      },
      async didMount() {
        // 页面打开 埋点
        this.pageOpenTracertTa();
        console.log(this.props.componentData);
        // 将页面id缓存
        const { componentData: { componentType, componentExtInfo: { version } } } = this.props;
        my.setStorageSync({
          key: componentType,
          data: this.$id,
        });
        if (version === 'v2') {
          await this.dispatch('getCardLevel');
          const [err, res] = await this.dispatch('getOpeMemberCardUrl');
          if (!err) {
            this.setData({
              configure: { ...res },
            });
            const { cardTemplateId = '' } = res;
            const newMemberInfo = await this.dispatch('getMemberInfo', { componentData: { componentExtInfo: { cardTemplateId } } });
            this.setData({
              memberInfo: newMemberInfo,
            });
          }
        }
      },
      async didUpdate(preProps) {
        const {
          componentData: {
            componentExtInfo: { memberInfo: preMenberInfo },
          },
        } = preProps;
        const {
          componentData: {
            componentExtInfo: { memberInfo },
          },
        } = this.props;
        if (!preMenberInfo && memberInfo) {
          this.componentShow();
        }
      },
      methods: {
        // 普通登录
        async doLogin() {
          await this.dispatchGlobal('doLogin');
        },
        // 入会
        async goToLogin() {
          const { APPID } = this.data;
          // 点击登录按钮
          const TracertTa = aliTracertTa({
            spmAPos: 'a2829', // spma位，必填
            spmBPos: 'b38646', // spmb位，必填
          });
          TracertTa.click('c98316.d203407', {
            APPID,
          });
          const { isLogin = false } = this.data.userInfo;

          // 点击入会 未登录
          if (!isLogin) {
            // await this.dispatchGlobal('doLogin');
            const success = await this.dispatchGlobal('doLogin', {
              scopes: 'phoneNumber',
            });
            if (!success) {
              await this.dispatchGlobal('doLogin');
            }
          }
          // 登录后 查看是否以及开卡
          const {
            memberInfo: { flag = false },
            version = 'v1',
          } = this.props.componentData.componentExtInfo;
          const { memberLevel } = this.data;
          if (!flag && version === 'v1') {
            this.addCard();
          }
          if (version === 'v2' && memberLevel === 'NONE') {
            this.addCard();
          }
        },
        addCard(e) {
          const {
            componentConfigure,
            componentExtInfo: { version = 'v1' },
          } = this.props.componentData;
          const { configure = {} } = this.data;
          const { applyUrl, cardTemplateId } = version === 'v1' ? componentConfigure : configure;
          const { regionCode } = this.data;
          const index = getIn(e, ['target', 'dataset', 'index']);
          this.dispatch('addCard', {
            index,
            applyUrl,
            cardTemplateId,
            regionCode,
            type: 'mall',
          });
        },
        goToCardDetail(e) {
          const { APPID } = this.data;
          // 点击卡包信息 进入卡详情
          const TracertTa = aliTracertTa({
            spmAPos: 'a2829', // spma位，必填
            spmBPos: 'b38646', // spmb位，必填
          });
          TracertTa.click('c98317.d203410', {
            APPID,
          });
          const {
            version = 'v1',
          } = this.props.componentData.componentExtInfo;
          const { memberRes } = this.data;
          const memberInfo = version === 'v1' ? getIn(e, ['target', 'dataset', 'memberInfo'], {}) : memberRes;
          const { passId } = memberInfo;
          console.log('卡实例ID passId===', passId);
          if (passId) {
            this.commit({
              memberInfo: {
                isOpenCardDeail: true,
                ...memberInfo,
              },
            });
            my.openCardDetail({
              passId,
            });
          }
        },
        // 页面打开 埋点
        pageOpenTracertTa() {
          const TracertTa = aliTracertTa({
            spmAPos: 'a2829', // spma位，必填
            spmBPos: 'b38646', // spmb位，必填
          });
          TracertTa.logPv({});
        },
        // 会员相关组件渲染 埋点
        componentShow() {
          // 个人中心展示曝光
          const {
            componentExtInfo: { memberInfo },
          } = this.props.componentData || {};
          if (!memberInfo) {
            return;
          }
          const { flag = false } = memberInfo;
          const TracertTa = aliTracertTa({
            spmAPos: 'a2829', // spma位，必填
            spmBPos: 'b38646', // spmb位，必填
          });
          const { APPID } = this.data;
          // 入会了
          if (flag) {
            TracertTa.expo('c98317', {
              APPID,
            });
          } else {
            TracertTa.expo('c98316', {
              APPID,
            });
          }
        },

        // 点击会员权益 埋点
        benefitClick() {
          const TracertTa = aliTracertTa({
            spmAPos: 'a2829', // spma位，必填
            spmBPos: 'b38646', // spmb位，必填
          });
          const { APPID } = this.data;
          TracertTa.click('c98316.d203408', { APPID });
        },
      },
    }),
  ),
);
