<template>
  <!-- <BasicTable @register="registerTable" /> -->
  <div class="wrap">
    <div class="content">
      <Input :placeholder="placeholder" disabled v-model:value="value" />
      <a-button
        class="mr-2 add-btn"
        color="success"
        :disabled="disabled"
        @click="openAddPop(placeholder)"
      >
        添加
      </a-button>
    </div>
    <Popup @register="register" @select="select" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onUpdated, reactive, nextTick, toRefs } from 'vue';
  import { Input } from 'ant-design-vue';
  import Popup from './popup.vue';
  import { useModal } from '/@/components/Modal';

  const props = {
    value: { type: Object, default: '' },
    placeholder: { type: String, default: '' },
  };
  interface State {
    value: object | string;
    placeholder: string;
    disabled: boolean;
  }

  export default defineComponent({
    name: 'CustomInput',
    components: { Input, Popup },
    props,
    emits: ['change'],
    setup(props, { emit }) {
      const state = reactive<State>({
        value: '',
        placeholder: props.placeholder,
        disabled: false,
      });
      const [register, { openModal: openPopup }] = useModal();
      // 初始化
      function init() {
        nextTick(() => {
          if (props.value.name) {
            console.log(`props.value.name`, props.value.name);
            state.value = props.value.name;
          } else if (props.value.url) {
            state.value = props.value.url;
          } else {
            state.value = props.value;
          }
          if (
            state.value !== '' &&
            (typeof props.value === 'string' || typeof props.value === 'number')
          ) {
            state.disabled = true;
          } else {
            state.disabled = false;
          }
        });
      }
      onUpdated(() => {
        init();
      });
      function openAddPop(title) {
        openPopup(true, title);
      }
      function select(data) {
        emit('change', data);
      }

      return {
        openAddPop,
        select,
        openPopup,
        register,
        ...toRefs(state),
      };
    },
  });
</script>
<style scoped>
  .content {
    display: flex;
  }

  .add-btn {
    margin-left: 2px;
  }
</style>
