import { isBoolean } from '../../../utils';
/* IBtnConfig = {
  text: string;
  // 样式
  extClass: 'cancel' | 'confirm';
  // 类型和传递的函数一致 类型为confirm 会调用 onConfirm
  type: 'cancel' | 'confirm';
} */

Component({
  props: {
    buttons: [{
      text: '取消',
      extClass: 'cancel',
      type: 'cancel'
    }, {
      text: '确认',
      extClass: 'confirm',
      type: 'confirm'
    }],
    onConfirm: () => null,
    onCancel: () => null,
    onOpenModal: () => null,
    dataType: '',
    zIndex: 1,
    opened: false,
    display: 'block'
  },
  data: {
    modalOpened: false
  },

  didMount() {
    const {
      opened = false
    } = this.props;
    this.setData({
      modalOpened: opened
    });
  },

  methods: {
    openModal() {
      this.setData({
        modalOpened: true
      });
      this.props.onOpenModal && this.props.onOpenModal();
    },

    // 关闭弹框
    onModalClose() {
      this.setData({
        modalOpened: false
      });
    },

    // 点击蒙层
    onMaskClick() {
      this.props.onCancel();
      this.onModalClose();
    },

    onConfirm() {
      const {
        dataType = ''
      } = this.props;
      const open = this.props.onConfirm(dataType) || false;

      if (!isBoolean(open)) {
        return this.onModalClose();
      }

      if (!open) {
        this.onModalClose();
      }
    },

    onCancel() {
      const open = this.props.onCancel() || false;

      if (!isBoolean(open)) {
        return this.onModalClose();
      }

      if (!open) {
        this.onModalClose();
      }
    },

    // 点击按钮
    onButtonClick(e) {
      // 底部按钮索引
      const {
        buttons = []
      } = this.props;
      const {
        index = 0
      } = e.target.dataset; // buttons中的type

      const {
        type = ''
      } = buttons[index];

      if (!type) {
        return;
      }

      const btnAction = {
        cancel: () => {
          this.onCancel();
        },
        confirm: () => {
          this.onConfirm();
        }
      }; // btn按钮点击操作

      btnAction[type] && btnAction[type]();
    }

  }
});