import { connect } from 'herculex';
import { createSubscribe } from 'applet-page-component';
import { getCardList } from '../../utils/service';
import { history, openCardForm, replaceStar } from '../../utils';
Component(connect({
  mapStateToProps: {
    componentList: state => state.componentList
  }
})(createSubscribe({
  onShow() {
    const {
      refreshPage
    } = getApp().globalData;

    if (refreshPage) {
      this.scrollFetch && this.scrollFetch.fetchList({
        pageIndex: 1
      }, true, true);
      getApp().globalData.refreshPage = false;
    }
  }

})({
  props: {
    data: {
      bookInfo: {}
    }
  },
  data: {
    serviceList: {}
  },

  didMount() {
    my.setNavigationBar({
      title: '选择就诊人'
    }); // 新：自定义页面没有componentList，通过遍历页面栈找到上一个页面的componentList

    const pages = getCurrentPages().reverse();
    const page = pages.find(item => item.data.componentList);

    if (page) {
      const {
        componentData: {
          serviceList
        }
      } = page.data.componentList.find(item => item.componentType === 'hospitalCardRegistrationComponent');
      this.setData({
        serviceList
      });
    } // 旧：找不到componentList
    // const { componentData: { serviceList } } = this.data.componentList.find(item => item.componentType === 'hospitalCardRegistrationComponent');
    // this.setData({ serviceList });

  },

  methods: {
    saveRef(ref) {
      this.scrollFetch = ref;
    },

    toBookInfo(e) {
      const {
        card
      } = e.target.dataset;
      const bookInfo = { ...card,
        ...this.props.data.bookInfo,
        cardName: card.name
      };
      this.setData({
        bookInfo
      });
      history.openPage({
        pageType: 'booking-info',
        data: {
          bookInfo
        }
      });
    },

    createCard(e) {
      openCardForm(e.target.dataset.item);
    },

    async onService(params) {
      const [err, res] = await getCardList({ ...params,
        type: 0
      });
      res && res.list.map(item => ({ ...item,
        viewCardNum: replaceStar(item.cardNum, 3, 4)
      }));
      return [err, res];
    }

  }
})));