import { createSubscribe } from 'applet-page-component';
import { deleteCard, getCardDetail } from '../../utils/service';
import { history, replaceStar } from '../../utils';
import { CREATE_CARD_TYPE } from '../../utils/common';
Component(createSubscribe({
  onShow() {
    if (getApp().globalData.cardDetail) {
      my.pageScrollTo({
        scrollTop: 0
      });
      this.toCardDetail();
      getApp().globalData.cardDetail = false;
    }
  }

})({
  props: {
    data: {
      cardNum: undefined,
      type: undefined,
      pageUuid: undefined
    }
  },
  data: {
    imgSrc: undefined,
    cardDetail: {},
    modalOpened: false,
    buttonsDel: [{
      text: '取消'
    }, {
      text: '删除',
      extClass: 'buttonBold'
    }],
    reason: ''
  },

  didMount() {
    my.setNavigationBar({
      title: '就诊卡管理'
    });
    this.toCardDetail();
  },

  methods: {
    // 就诊卡详情
    toCardDetail() {
      const {
        cardNum
      } = this.props.data;
      this.getCardDetail(cardNum);
    },

    async getCardDetail(cardNum) {
      my.showLoading({
        content: '加载中...'
      });
      const [, res] = await getCardDetail({
        cardNum
      });

      if (res) {
        getApp().globalData.cardDetail = res;
        res.viewCardNum = replaceStar(res.cardNum, 1, 1);
        res.viewIdCardNo = replaceStar(res.idCardNo, 1, 1);
        res.viewPhoneNumber = replaceStar(res.phoneNumber, 3, 2);
        my.hideLoading();
        this.setData({
          cardDetail: res
        });
      } else {
        my.hideLoading();
      }
    },

    toDelCard() {
      this.setData({
        modalOpened: true
      });
    },

    setReason(e) {
      this.setData({
        reason: e.detail.value
      });
    },

    // 调用删除接口
    async onButtonClick(e) {
      const {
        target: {
          dataset
        }
      } = e;

      if (dataset.index === 0) {
        this.setData({
          modalOpened: false
        });
      } else if (dataset.index === 1) {
        const {
          cardNum
        } = this.data.cardDetail;
        const {
          reason
        } = this.data;
        const [err, res] = await deleteCard({
          reason,
          cardNum
        });
        history.replacePage({
          pageType: 'card-delete-result',
          data: {
            success: !!res,
            msg: err && err.msg
          }
        });
      }
    },

    toEditCard() {
      history.openPage({
        pageType: 'card-form',
        data: {
          type: CREATE_CARD_TYPE.EDIT,
          btnText: '修改就诊卡',
          cardDetail: this.data.cardDetail,
          pageUuid: this.props.data.pageUuid
        }
      });
    }

  }
}));