<template>
  <div :class="['form-item', half ? 'form-item-half' : '', elclass || '']">
    <slot name="input">
      <label>
        <span v-if="label !== undefined && label !== ''">
          {{ label }}
          <i v-if="required" class="form-item-alert">*</i>
        </span>
        <div class="input-a">
          <span>
            {{
              localFilename !== undefined && localFilename !== ''
                ? localFilename
                : 'Dosya yüklemek için tıklayın'
            }}
          </span>
          <i class="ico-c ico-section ico-section-header-btn">
            <svg><use href="/src/assets/images/icons.svg#upload"></use></svg>
          </i>
        </div>
        <input
          type="file"
          :disabled="disabled"
          @change="OnChange"
          :class="[
            invalidText !== undefined && invalidText !== '' ? 'invalid' : '',
            iclass || ''
          ]" />
        <span
          class="form-item-alert"
          v-if="InvalidMessages.length > 0 && InvalidMessages !== ''">
          {{ InvalidMessages }}
        </span>
        <span
          class="form-item-description"
          v-if="description !== undefined && description !== ''">
          {{ description }}
        </span>
      </label>
    </slot>
  </div>
</template>
<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()

  export interface Props {
    label?: string
    fileName?: string
    disabled?: boolean
    modelValue: number | string | FileList | File
    half?: boolean
    title?: string
    invalidText?: string
    description?: string
    maxFileSize?: number
    maxFileSizeText?: string
    required?: boolean
    iclass?: string
    elclass?: string
    modelKey?: string
    fileTypes?: string[]
    fileType?: string
    isValid?: boolean
  }
  const props = withDefaults(defineProps<Props>(), {
    disabled: false,
    half: false,
    required: false,
    fileName: '',
  })

  const emit = defineEmits(['update:modelValue', 'change','update:isValid',])

  const localFilename = ref<string>(props.fileName)

  const InvalidMessageText = ref<Record<string, any>>({})

  const InvalidMessages = computed<string>(() => {
    let text = ''
    Object.keys(InvalidMessageText.value).forEach((k: string, i: number) => {
      text += InvalidMessageText.value[k] + ', '
    })
    return text
  })

  const OnChange = (e: Event) => {
    let el: any = (e.target as HTMLInputElement)!['files']![0]
    localFilename.value = el.name
    let fileType: string = globalStore.FileType(el.name)
    let fileName: string = globalStore.FileName(el.name)
    let fileSize: number = el.size
    InvalidMessageText.value = {}

    if (props.fileType !== undefined) {
      if (props.fileType === 'img') {
        if (!globalStore.imageFormats.includes(fileType.toLowerCase())) {
          InvalidMessageText.value.type = `Sadece Resim dosyası yükleyebilirsiniz. Lütfen ${globalStore.imageFormats} formatındaki dosyaları yükleyin`
          el = null
          localFilename.value = ''
        }
      } else if (props.fileType === 'doc') {
        if (!globalStore.docFormats.includes(fileType.toLowerCase())) {
          InvalidMessageText.value.type = `Sadece doküman yükleyebilirsiniz. Lütfen ${globalStore.docFormats} formatındaki dosyaları yükleyin`
          el = null
          localFilename.value = ''
        }
      }
    }
    if (props.fileTypes !== undefined) {
      if (!props.fileTypes.includes(fileType.toLowerCase())) {
        InvalidMessageText.value.type = `Lütfen ${props.fileTypes} formatındaki dosyaları yükleyin`
        el = null
        localFilename.value = ''
        if(props.isValid !== undefined) {
          emit('update:isValid', false)
        }
      }else{
        if(props.isValid !== undefined) {
          emit('update:isValid', true)
        }
      }
    }

    if (props.maxFileSize !== undefined) {
      if (fileSize > props.maxFileSize) {
        InvalidMessageText.value.size = `Dosya boyutu en fazla ${props.maxFileSizeText} olabilir. Lütfen daha küçük boyutlu bir dosya yükleyin.`
        el = null
      }
    }
    emit('update:modelValue', el)
    emit('change', e, { filetype: fileType, filename: fileName, filesize: fileSize })
  }

  watch(
    () => props.invalidText,
    () => {
      if (props.invalidText !== undefined && props.invalidText !== '') {
        InvalidMessageText.value = {}
        InvalidMessageText.value.invalid = props.invalidText
      } else {
        delete InvalidMessageText.value.invalid
      }
    }
  )
</script>
