<template>
  <div class="upload-file clear-both">
    <div class="upload-file-list flex justify-center">
      <template v-if="myFileList.length">
        <div v-for="(item, index) in myFileList" :key="item.uid" class="file-wrap mr-16 border border-solid border-gray-1">
          <template v-if="item.status === 'done'">
            <a-image
              width="100%"
              height="100%"
              class="mini-img"
              v-if="fileType === 'image' && (item.url || item.response?.result)"
              :src="item.url || item.response?.result?.url || item.response?.result"
            ></a-image>
            <div v-if="fileType === 'video'" class="video-box bg-black w-full h-full flex items-center justify-center">
              <PlayCircleOutlined class="fs-28 c-primary cursor-pointer" @click="openVideo(item)"></PlayCircleOutlined>
            </div>
          </template>
          <div v-if="item.status === 'uploading'" class="w-full h-full flex items-center justify-center fs-30">
            <LoadingOutlined class="fs-20"></LoadingOutlined>
          </div>
          <CloseCircleFilled
            v-if="!disabled"
            @click="delFile(item.uid)"
            class="btn-del bg-white rounded-full p-2 fs-20 c-999 hover:color-primary transition cursor-pointer"
          />
        </div>
      </template>
      <a-upload
        :disabled="disabled"
        v-model:fileList="myFileList"
        :accept="accept[props.fileType]"
        :action="props.api"
        :maxCount="limit"
        :multiple="limit > 1"
        :before-upload="beforeUpload"
        :show-upload-list="false"
        @change="handleChange"
      >
        <div
          class="border border-gray-3 flex flex-col items-center justify-center transition-duration-300"
          :class="disabled ? 'cursor-not-allowed' : 'cursor-pointer hover:border-primary'"
          v-if="myFileList.length < limit"
        >
          <slot>
            <div>
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div></slot
          >
        </div>
      </a-upload>

      <a-modal v-model:open="videoVisible" :footer="false" title="预览">
        <video class="w-full h-full block" v-if="videoVisible" :src="videoUrl" controls></video>
      </a-modal>
    </div>
    <!-- {{ myFileList }} -->
  </div>
</template>
<script lang="ts" setup>
import { PlusOutlined, CloseCircleFilled, PlayCircleOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import type { UploadProps, UploadFile, UploadChangeParam } from 'ant-design-vue'
import { message } from 'ant-design-vue'
// const {id, onFieldChange, onFieldBlur} = useInjectFormItemContext()
import { Form } from 'ant-design-vue'
const formItemContext = Form.useInjectFormItemContext()
const emits = defineEmits(['success'])

type Props = {
  api: string
  limit: number
  limitSize: number
  fileType: 'image' | 'video'
  accept: string
}
const props = defineProps({
  api: {
    type: String,
    default: '/jeecgboot/sys/oss/file/otherUpload',
  },
  // 上传数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 文件大小限制
  limitSize: {
    type: Number,
    default: 5,
  },
  fileType: {
    type: String,
    default: 'image',
  },
  accept: {
    // 文件类型限制
    type: String,
    default: '.jpg,.jpeg,.png,.gif',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

const accept: { [key: string]: string } = {
  image: '.jpg,.jpeg,.png,.gif',
  video: '.mp4,.flv,.mov',
}
// const myFileList = defineModel<Array<UploadFile>>('list', { type: Array, default: [] })

/**
 * 工具方法 用来生成符合规范的 文件列表
 * @param fileUrlList 文件地址
 * @returns
 */
const genInitFileList = (fileUrlList: Array<string>): Array<UploadFile> => {
  return fileUrlList.map((fileUrl, index) => {
    return {
      uid: index + '',
      status: 'done',
      url: fileUrl,
      name: 'file',
    }
  })
}
const modelUrl = defineModel<string>('url', { type: String })
let myFileList = ref<Array<UploadFile>>([])

// if (modelUrl.value) {
//   // 根据传入的链接生成 起始文件
//   myFileList.value = genInitFileList(modelUrl.value.split(','))
// }
watch(
  modelUrl,
  (newVal) => {
    if (modelUrl.value) {
      // 根据传入的链接生成 起始文件
      myFileList.value = genInitFileList(modelUrl.value.split(','))
    }
  },
  // { deep: true, once: true, immediate: true}
  { deep: true, once: true }
)
// if (modelUrl.value) {
//   // 根据传入的链接生成 起始文件
//   myFileList.value = genInitFileList(modelUrl.value.split(','))
// }
// let myFileList = myFileList

const beforeUpload = (file: UploadFile) => {
  const suffix = '.' + file.name.toLowerCase().substring(file.name.lastIndexOf('.') + 1)
  const isFileTypeRight = accept[props.fileType].split(',').includes(suffix)
  const isLimitSize = file.size! / 1024 / 1024 < props.limitSize

  if (!isFileTypeRight) {
    message.error('文件格式错误')
  } else if (!isLimitSize) {
    message.error(`文件大小不能超过${props.limitSize}MB!`)
  }
  if (!isFileTypeRight || !isLimitSize) {
    delFile(file.uid)
    return false
  }
}
const handleChange = (info: UploadChangeParam) => {
  const { file, fileList } = info
  myFileList.value = fileList.filter((item) => !!item.status)

  if (file.status === 'uploading') {
    // return
  }
  if (file.status === 'removed') {
  }
  if (file.status === 'done') {
    if (file.response && file.response.success) {
    } else {
      // 如果接口上传失败 删除列表中此项
      message.error(file.response.message)
      delFile(file.uid)
      // myFileList.value = myFileList.value.filter((item) => item.uid !== file.uid)
      // console.log(myFileList.value.map((item) => item.uid))
      // console.log(file.uid)
    }
  }
  if (file.status === 'error') {
    message.error('上传失败')
  }
}

/**
 * 删除文件
 */
const delFile = (uid: string) => {
  myFileList.value = myFileList.value.filter((item) => item.uid !== uid)
}

const genUrlFromUploadList = (fileList: Array<UploadFile>): string => {
  // console.log(fileList)
  let urlList: Array<string> = []
  fileList.map((file, index) => {
    urlList.push(file.url || file.response?.result?.url || file.response?.result)
  })
  return urlList.join(',')
}
watch(
  myFileList,
  (newVal) => {
    const newUrl = genUrlFromUploadList(newVal)

    // console.log('---newUrl', newUrl)
    // console.log('---modelUrl.value', modelUrl.value)
    if (modelUrl.value !== newUrl) {
      modelUrl.value = newUrl
      formItemContext.onFieldChange()
      emits('success', newVal)
      // console.log('---newUrl', newUrl)
      // console.log('---modelUrl.value', modelUrl.value)
    }
  },
  { deep: true }
)

// ====== video 预览模块 =======
const videoVisible = ref(false)
const videoUrl = ref('')
const openVideo = (file: UploadFile) => {
  videoUrl.value = file.url || file.response?.result
  videoVisible.value = true
}
</script>
<style scoped lang="less">
.upload-file {
  :deep(.ant-upload-list-item) {
    border: none;
  }
  .file-wrap {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    :deep(.mini-img) {
      display: block;
      object-fit: cover;
    }
    .btn-del {
      position: absolute;
      z-index: 99;
      top: -10px;
      right: -10px;
    }
  }
}
</style>
