import { Input, Button } from "ant-design-vue";
import { defineComponent, ref } from "vue";
import { bool, number, string } from "vue-types";
import Modal from "./Modal";

export default defineComponent({
  props: {
    title: string().def("请填写"),
    defaultValue: string().def(""),
    placeholder: string().def(""),
    maxLength: number(),
    selection: bool().def(false),
    okText: string().def("确定"),
    cancelText: string().def("取消"),
  },
  setup(props) {
    const modal = Modal.use();
    const firstLoad = ref(true);
    const inputValue = ref(props.defaultValue);
    return () => (
      <div class="ant-modal-input">
        <Input
          maxlength={props.maxLength}
          ref={(input: any) => {
            if (input) {
              if (
                props.selection &&
                inputValue.value.length > 0 &&
                firstLoad.value
              ) {
                input.setSelectionRange(0, inputValue.value.length);
              }
              input.focus();
            }
          }}
          value={inputValue.value as string}
          placeholder={props.placeholder as string}
          autofocus={true}
          onChange={(e: any) => {
            inputValue.value = e.target.value;
            firstLoad.value = false;
          }}
        />
        <div class="input-btns">
          <Button onClick={() => modal.cancel()}>{props.cancelText}</Button>
          <Button
            onClick={() => {
              if (!inputValue.value) return;
              modal.submit(inputValue.value);
            }}
            type="primary"
          >
            {props.okText}
          </Button>
        </div>
      </div>
    );
  },
});
