<template>
  <div>
    <a-input
      :size="size"
      v-model:value="code"
      :placeholder="placeholder"
      :addonBefore="addonBefore"
      :addonAfter="addonAfter"
      :disabled="disabled"
      readonly
    >
      <template #prefix v-if="prefix">
        <Icon :icon="prefix" />
      </template>
      <template #suffix v-if="suffix">
        <Icon :icon="suffix" />
      </template>
    </a-input>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, watch, inject, Ref } from 'vue';
  import { generateCodeRule } from '/@/api/system/code';
  import { Icon } from '/@/components/Icon';

  const props = defineProps({
    value: String,
    size: String,
    placeholder: String,
    addonBefore: String,
    addonAfter: String,
    prefix: String,
    suffix: String,
    autoCodeRule: String,
    disabled: {
      type: Boolean,
      default: false,
    },
  });

  const isCopy = inject<Ref<boolean>>('isCopy', ref(false));
  const code = ref('');
  const emit = defineEmits(['update:value', 'change']);
  onMounted(async () => {
    if (!!props.autoCodeRule) {
      code.value = await generateCodeRule(props.autoCodeRule);
      if (props.value && !isCopy.value) {
        code.value = props.value;
      }
      emit('update:value', code.value);
      emit('change', code.value);
    }
  });

  // watch(
  //   () => props.autoCodeRule,
  //   async (val) => {
  //     if (!!val) {
  //       code.value = await generateCodeRule(val);
  //       emit('update:value', code.value);
  //     }
  //   },
  //   {
  //     immediate: true,
  //   },
  // );
  watch(
    () => props.value,
    async (val) => {
      if (!!props.autoCodeRule && !val) {
        code.value = await generateCodeRule(props.autoCodeRule);
      }
      if (val) code.value = val;
      emit('update:value', code.value);
    },
  );
</script>
