import history from '../../../../utils/history';

const isEqual = (oldVal, curVal) => JSON.stringify(oldVal) === JSON.stringify(curVal);

Component({
  props: {
    filters: {},
    patients: [],
    patientId: '',
    typeOptions: [],
    hasFilter: true,
    medicCards: [],
    onChange: () => null,
    onAutoFilter: () => null,
    statusItems: [],
    defaultName: '',
    defaultLabel: ''
  },
  data: {
    activeTab: 0
  },

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

  didUpdate(preProps) {
    /* 监听patientId */
    const hasDiff = !isEqual(preProps.patients, this.props.patients);

    if (preProps.patientId !== this.props.patientId || hasDiff) {
      this.autoActiveTab();
    }
  },

  methods: {
    autoActiveTab() {
      const {
        patients,
        patientId,
        onAutoFilter
      } = this.props;

      if (patients.length > 0) {
        const activeTab = patients.findIndex(({
          extData
        }) => extData.id === patientId);
        if (activeTab > -1) this.setData({
          activeTab
        });
        const {
          extData
        } = patients[activeTab > -1 ? activeTab : 0];
        onAutoFilter(extData);
      }
    },

    /* 切换就诊人 */
    handleTabClick({
      index,
      tabsName
    }) {
      const activeTab = this.data[tabsName];
      /* 这里防止重复点击 */

      if (activeTab === index) return;
      const {
        patients
      } = this.props;
      const patient = patients[index];
      const {
        extData,
        id
      } = patient;
      this.props.onAutoFilter(extData); // const { medicCards = [] } = extData;

      this.props.onChange({
        cardNum: id
      });
      this.setData({
        [tabsName]: index
      });
    },

    /* 切换筛选项 */
    onFilterChange(filter) {
      this.props.onChange(filter);
    },

    handlePlusClick() {
      history.push({
        title: '添加就诊人',
        pageType: 'edit-patient'
      });
    }

  }
});