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

interface Props {
  modelValue?: string;
  placeholder?: string;
}

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

const emit = defineEmits(['update:modelValue', 'refresh', 'update:randomKey']);

const captchaValue = ref(props.modelValue);
const captchaUrl = ref('');
const randomKey = ref('');

watch(
  () => props.modelValue,
  (val) => {
    captchaValue.value = val;
  },
);

watch(captchaValue, (val) => {
  emit('update:modelValue', val);
});

function handleRefresh() {
  const random = randomString(16);
  randomKey.value = random;
  captchaUrl.value = `/File/ImageCheckCode?w=130&h=40&len=4&key=${random}`;
  emit('update:randomKey', random);
}

function randomString(length: number): string {
  let result = '';
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

onMounted(() => {
  handleRefresh();
});
</script>

<template>
  <div class="flex w-full items-center gap-2">
    <input
      v-model="captchaValue"
      :placeholder="placeholder"
      class="h-[38px] flex-1 rounded-md border border-gray-300 px-3 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-[#8B0046]"
      type="text"
    />
    <div
      class="flex h-[38px] w-[120px] cursor-pointer items-center justify-center overflow-hidden rounded-[5px]"
      @click="handleRefresh"
    >
      <img
        v-if="captchaUrl"
        :src="captchaUrl"
        alt="验证码"
        class="h-full w-full object-contain"
      />
      <span v-else class="text-xs text-gray-500">点击刷新</span>
    </div>
  </div>
</template>
