<template>
  <div v-loading="loading" class="upload-file">
    <input
      ref="fileInputRef"
      type="file"
      style="display: none"
      @change="onChange"
    />
    <div v-if="imageMode" class="image-wrap" @click="onFileClick">
      <img v-if="value" :src="value" alt="" />
      <el-icon v-else><Plus /></el-icon>
    </div>
    <template v-else>
      <div v-if="(files && files.length) < max" class="upload-file-add">
        <el-icon @click="fileInputRef.click()"><Plus /></el-icon>
      </div>
      <ul class="files">
        <li
          v-for="(item, i) in files"
          :key="item.path"
          class="upload-files-file"
        >
          <span
            :title="`点击下载 ${item.path} 文件`"
            class="filename"
            @click="downloadFile(item)"
          >
            {{ item?.filename || filename(item.path) }}
          </span>
          <el-icon
            v-if="!disabled"
            style="cursor: pointer"
            @click="removeFile(i)"
            ><Close
          /></el-icon>
        </li>
      </ul>
    </template>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Plus, Close } from '@element-plus/icons-vue'
import { uploadImageApi, uploadFileApi } from '@/api/common'
const props = defineProps({
  modelValue: String,
  disabled: Boolean,
  imageMode: {
    type: Boolean,
    default: false,
  },
  max: {
    type: Number,
    default: 1,
  },
  text: String,
})
const emit = defineEmits(['update:modelValue'])
const value = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})
const files = ref<FileItem[]>([])
watch(
  value,
  () => {
    let file = []
    if (!Array.isArray(value)) {
      if (value.value) {
        file.push({ path: value.value })
      } else {
        file = []
      }
    }
    files.value = file
  },
  { immediate: true },
)
const fileInputRef = ref()
const loading = ref(false)
const onChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files) return
  const file = files[0]
  const isLtTenM = file.size / 1024 / 1024 < 200
  if (!isLtTenM) {
    ElMessage.error('上传文件大小不能超过 200MB!')
    return isLtTenM
  }
  if (props.imageMode) {
    imageUpload(file)
  } else {
    fileUpload(file)
  }
  fileInputRef.value.value = ''
}
interface FileItem {
  path: string
  filename?: string
}

const fileUpload = async (file: File) => {
  const formData = new FormData()
  const filename = file.name
  formData.append('file', file)
  formData.append('businessType', 'product')
  loading.value = true
  try {
    const res = await uploadFileApi(formData)
    files.value.push({ path: res.message ?? '', filename })
    value.value = res.message
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const imageUpload = async (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('businessType', 'product')
  loading.value = true
  try {
    const res = await uploadImageApi(formData)
    value.value = res.filePath
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const onFileClick = () => {
  if (props.disabled) return
  fileInputRef.value.click()
}
const filename = (path: string) => {
  if (!path) return ''
  const i = path.lastIndexOf('/')
  if (i === -1) return path
  return path.substring(i + 1)
}

const downloadFile = (item: FileItem) => {
  window.open(item.path)
}
const removeFile = (i: number) => {
  files.value.splice(i, 1)
  value.value = ''
}
// const _lastValue = ref()
// const emitValue = () => {
//   let v
//   if (props.max === 1) {
//     v = files.value[0] && files.value[0].path
//   } else {
//     v = files.value.map((e) => e.path)
//   }
//   _lastValue.value = v
//   emit('update:modelValue', v)
// }
</script>
<style scoped lang="scss">
ul,
li {
  margin: 0;
  padding: 0;
}
.upload-file {
  width: 100%;
}
.image-wrap {
  width: 100%;
  height: 200px;
  width: 100%;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  i {
    font-size: 36px;
    color: #777;
    cursor: pointer;
  }
  img {
    height: 100%;
    width: 100%;
    object-fit: contain;
  }
}

.upload-file-add {
  height: 100px;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  .el-icon {
    font-size: 36px;
    color: #777;
  }
}
.upload-files-file {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filename {
  cursor: pointer;
}
</style>
