import { querySingle, bindMedicCard, patientDelete } from './service';
import { getMyCardInfo } from '../personal-center-head/service.js';
import history from '../../utils/history';
import { createSubscribe } from 'applet-page-component';
Component(createSubscribe({
  onShow() {
    this.init();
  }

})({
  props: {},
  data: {
    patient: {
      balance: 0,
      id: '',
      name: '',
      age: '',
      sex: '',
      phoneNumber: '',
      birthDay: '',
      idCardNo: '',
      relationShip: '',
      bindCardNum: '',
      medicCards: []
    },
    modalOpened: false,
    buttons: [{
      text: '取消'
    }, {
      text: '删除',
      extClass: 'buttonBold'
    }]
  },

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

  methods: {
    async init() {
      const {
        query = {
          id: ''
        }
      } = this.$page.data;
      this.setData({
        patient: { ...this.data.patient,
          medicCards: []
        }
      });

      if (query.id) {
        this.querySingle(query.id);
      } else {
        const info = await this.getMyCardInfo();
        this.querySingle(info.patientId);
      }
    },

    querySingle(id) {
      my.showLoading();
      querySingle({
        id
      }).then(data => {
        let bind = data.medicCards.findIndex(m => m.cardNum === data.bindCardNum);
        bind = Math.max(bind, 0);
        data.medicCards.forEach((m, i) => {
          m.expand = i === bind;
          m.checked = m.cardNum === data.bindCardNum;
        });
        this.setData({
          patient: data
        });
        my.hideLoading();
      });
    },

    getMyCardInfo() {
      return getMyCardInfo();
    },

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

    onButtonClick(e) {
      this.setData({
        modalOpened: false
      });

      if (e.target.dataset.index === 1) {
        patientDelete({
          id: this.data.patient.id
        }).then(() => {
          my.navigateBack();
        });
      }
    },

    onChange(e) {
      my.showLoading();
      this.setData({
        patient: { ...this.data.patient,
          bindCardNum: e.target.dataset.val
        }
      });
      bindMedicCard({
        id: this.data.patient.id,
        bindCardNum: e.target.dataset.val
      }).then(() => {
        this.init();
        my.hideLoading();
      });
    },

    // 编辑就诊人
    onEdit() {
      const {
        query = {
          id: ''
        }
      } = this.$page.data;
      history.push({
        query: {
          id: query.id
        },
        title: '编辑就诊人',
        pageType: 'patient-detail-edit'
      });
    },

    // 充值
    onPayment(e) {
      const {
        id,
        cardNum
      } = e.target.dataset;
      history.push({
        query: {
          id,
          cardNum
        },
        title: '充值',
        pageType: 'hospital-recharge'
      });
    }

  }
}));