import { Button, Input } from 'element-ui';

const Jumper = {
  components: {
    [Button.name]: Button,
    [Input.name]: Input,
  },
  data() {
    return {
      oldValue: null,
    };
  },

  watch: {
    '$parent.internalPageSize'() {
      this.$nextTick(() => {
        this.$refs.input.$el.querySelector(
          'input'
        ).value = this.$parent.internalCurrentPage;
      });
    },
  },

  methods: {
    handleFocus(event) {
      this.oldValue = event.target.value;
    },
    handleBlur({ target }) {
      this.resetValueIfNeed(target.value);
      this.reassignMaxValue(target.value);
    },
    handleKeyup({ keyCode, target }) {
      if (keyCode === 13 && this.oldValue && target.value !== this.oldValue) {
        this.handleChange(target.value);
      }
    },
    handleChange(value) {
      this.$parent.internalCurrentPage = this.$parent.getValidCurrentPage(
        value
      );
      this.$parent.emitChange();
      this.oldValue = null;
      this.resetValueIfNeed(value);
    },
    resetValueIfNeed(value) {
      const num = parseInt(value, 10);
      if (!isNaN(num)) {
        if (num < 1) {
          this.$refs.input.setCurrentValue(1);
        } else {
          this.reassignMaxValue(value);
        }
      }
    },
    reassignMaxValue(value) {
      const { internalPageCount } = this.$parent;
      if (+value > internalPageCount) {
        this.$refs.input.setCurrentValue(internalPageCount || 1);
      }
    },
  },

  render(h) {
    return (
      <span class='el-pagination__jump'>
        跳转至
        <el-input
          class='el-pagination__editor is-in-pagination'
          min={1}
          max={this.$parent.internalPageCount}
          value={this.$parent.internalCurrentPage}
          domPropsValue={this.$parent.internalCurrentPage}
          type='number'
          ref='input'
          disabled={this.$parent.disabled}
          nativeOnKeyup={this.handleKeyup}
          onChange={this.handleChange}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
        />
        页<el-button>GO</el-button>
      </span>
    );
  },
};

export default Jumper;
