import { connect } from 'herculex';
import { getMedicalInformation, getMedicalInformationList } from './service';
import doLogin from '../../utils/doLogin';
import { NOTIFY_STATUS } from '../../utils/const';
import history, { getEntryPage } from '../../utils/history';

const isEmptyObj = obj => !Object.keys(obj).length;

Component(connect({
  mapStateToProps: {
    scopes: ({
      $global
    }) => $global.scopes,
    userInfo: ({
      $global
    }) => $global.userInfo || {},
    isLogin: ({
      $global
    }) => $global.userInfo.isLogin
  }
})({
  props: {
    componentData: {}
  },
  data: {
    items: [],
    loading: true,
    isLogin: false,
    openNotify: false
  },

  didMount() {
    this.getNotifyStatus();
  },

  didUpdate(_, preState) {
    const {
      isLogin
    } = this.data;

    if (preState.isLogin !== isLogin && isLogin) {
      this.getMedicalInformation();
    }
  },

  methods: {
    getExtInfo() {
      const {
        componentData
      } = this.props;
      const {
        componentExtInfo = {}
      } = componentData;
      return componentExtInfo;
    },

    saveSubscribe(ref) {
      this.subscribeRef = ref;
    },

    /* 获取消息通知的开启状态 */
    getNotifyStatus() {
      const {
        data
      } = my.getStorageSync({
        key: NOTIFY_STATUS
      });
      if (data) this.setData({
        openNotify: true
      });
    },

    /**
     * 导航按钮
     */
    onNavTo({
      target
    }) {
      const {
        textUrl = ''
      } = target.dataset;
      this.toUrl(textUrl);
    },

    toMainUrl({
      target
    }) {
      const {
        mainUrl = ''
      } = target.dataset;
      this.toUrl(mainUrl);
    },

    toUrl(url) {
      if (!url) return;
      const reg = /(http|https):\/\//;
      const isH5 = reg.test(url);

      if (isH5) {
        history.toH5(url);
      } else {
        my.navigateTo({
          url: `${getEntryPage()}?${url}`
        });
      }
    },

    /**
     * 获取就医信息
     */
    async getMedicalInformation() {
      let list = [];
      /* mode 的值为single和multiple; */

      const {
        mode = 'single'
      } = this.getExtInfo();

      try {
        if (mode === 'single') {
          const info = await getMedicalInformation();
          if (info && !isEmptyObj(info)) list = [info];
        } else {
          list = await getMedicalInformationList();
        } // eslint-disable-next-line no-empty

      } catch (e) {}

      this.setData({
        items: list,
        loading: false
      });
    },

    /**
     * 去授权
     */
    async onAuthHandel() {
      const {
        isLogin,
        openNotify
      } = this.data;
      /* 如果未登录，唤起登录 */

      if (!isLogin) {
        await doLogin.call(this);
      }
      /* 如果没有开启消息通知 */


      if (!openNotify) {
        this.subscribeRef.subscribeMessage({
          success: () => {
            this.setData({
              openNotify: true
            });
          }
        });
      }
    }

  }
}));