import { createSubscribe } from 'applet-page-component';
import { CREATE_CARD_TYPE } from '../utils/common';
import { getCardList } from '../utils/service';
import { connect } from 'herculex';
import { promisify, replaceStar, history } from '../utils';
import { reportCmPV_YL } from '../utils/cloudMonitorHelper';
const getAuthCode = promisify(my.getAuthCode);
Component(connect({
  mapStateToProps: {}
})(createSubscribe({
  onShow() {
    this.scrollFetch && this.scrollFetch.fetchList({
      pageIndex: 1
    }, true, true);
  }

})({
  props: {
    componentData: {}
  },
  data: {
    tabsConfig: {
      tabs: [{
        title: '就诊卡'
      }, {
        title: '医保卡'
      }]
    },
    activeTab: 0,
    cardType: 0 // 0-普通卡 1-医保卡 9-全部

  },

  didMount() {
    const {
      serviceCode
    } = getCurrentPages().pop().options;
    reportCmPV_YL({
      title: '就诊卡管理',
      query: {
        serviceCode
      }
    });
    getApp().globalData.cardFormComponentData = this.props.componentData;
  },

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

    async getCardLists(params) {
      let authCode = '';
      const {
        cardType,
        medicareflag
      } = this.data;

      if (medicareflag) {
        const [err, res] = await getAuthCode({
          scopes: ['medicare']
        });

        if (err) {
          return my.alert({
            content: '获取授权失败'
          });
        }

        authCode = res.authCode;
      }

      const [err, res] = await getCardList({ ...params,
        authCode,
        type: cardType
      });

      if (res) {
        res.list.forEach(item => {
          item.viewCardNum = replaceStar(item.cardNum, 3, 4);
        });
      }

      return [err, res];
    },

    // 卡管理页，tabble切换
    async handleTabClick({
      index,
      tabsName
    }) {
      await this.setData({
        medicareflag: index,
        [tabsName]: index,
        cardType: index
      });
      this.scrollFetch.fetchList({
        pageIndex: 1
      }, true, true);
    },

    // 绑定就诊卡
    toBindCard() {
      history.openPage({
        pageType: 'card-form',
        data: {
          type: CREATE_CARD_TYPE.BIND,
          btnText: '绑定就诊卡'
        }
      });
    },

    // 创建就诊卡
    toCreateCard() {
      history.openPage({
        pageType: 'card-form',
        data: {
          type: CREATE_CARD_TYPE.CREATE,
          btnText: '创建电子就诊卡'
        }
      });
    },

    // 就诊卡详情
    toCardDetail(e) {
      const cardNum = e.target.dataset.cardnum;
      const {
        type
      } = e.target.dataset;

      if (type === 1) {
        my.navigateToMiniProgram({
          appId: '2021001123625885',
          path: 'pages/index/index'
        });
      } else {
        history.openPage({
          pageType: 'card-detail',
          data: {
            cardNum,
            type
          }
        });
      }
    }

  }
})));