import { queryList } from '../../order-pay/service';
import history from '../../../utils/history';
Component({
  props: {
    show: false,
    onClose: () => null,
    onChange: () => null,

    /*
    * 是否自动选中默认就诊人
    * */
    autoSelectDefault: true
  },
  data: {
    patientList: []
  },

  didUpdate({
    show: preShow
  }) {
    const {
      show,
      autoSelectDefault
    } = this.props;

    if (!autoSelectDefault) {
      if (preShow !== show && show) {
        this.queryList();
      }
    }
  },

  didMount() {
    const {
      show,
      autoSelectDefault
    } = this.props;

    if (show || autoSelectDefault) {
      this.queryList();
    }
  },

  methods: {
    onClose() {
      this.props.onClose();
    },

    // 查询就诊人列表
    queryList() {
      const {
        autoSelectDefault
      } = this.props;
      queryList({
        type: 9,
        pageIndex: 1,
        pageSize: 999
      }).then(data => {
        this.setData({
          patientList: data
        });

        if (autoSelectDefault) {
          this.selectPatient();
        }
      });
    },

    // 选择就诊人
    checkedPatient(e) {
      const {
        id
      } = e.target.dataset;
      this.selectPatient(id);
      this.onClose();
    },

    // 默认选中就诊人
    selectPatient(id) {
      const {
        patientList
      } = this.data;
      let checkedPatient = {};

      if (id) {
        checkedPatient = patientList.find(m => m.id === id);
      } else if (patientList.length === 1) {
        [checkedPatient] = this.data.patientList;
      } else {
        checkedPatient = patientList.find(m => m.defaultPatient);
      }

      this.props.onChange(checkedPatient);
    },

    // 添加就诊人
    addPatient() {
      this.props.onClose();
      history.push({
        title: '添加就诊人',
        pageType: 'edit-patient'
      });
    }

  }
});