<template>
  <el-input
    v-model="fileName"
    placeholder="请输入"
    clearable
    :disabled="disabled"
    @change="changeFun"
    @clear="clearFun"
  >
    <template v-if="fileSuffix" #append>.{{ fileSuffix }}</template>
  </el-input>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';

interface Props {
  modelValue: string;
  disabled: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  disabled: false,
});

const emit = defineEmits(['update:modelValue', 'change', 'clear']);
const fileName = ref('');
const fileSuffix = ref('');

watch(
  () => props.modelValue,
  (val: any) => {
    const lastDotIndex = val.lastIndexOf('.');
    fileName.value = val.slice(0, lastDotIndex);
    fileSuffix.value = val.slice(lastDotIndex + 1);
  },
  {
    immediate: true,
  }
);

const changeFun = () => {
  let name = '';
  if (fileSuffix.value) {
    name = `${fileName.value}.${fileSuffix.value}`;
  } else {
    name = fileName.value;
  }
  emit('update:modelValue', name);
  emit('change', name);
};

const clearFun = () => {
  emit('clear');
};
</script>
