<template>
  <div ref="uploadOutRef" style="width: 100%">
    <!-- :on-remove="delFile" -->
    <div class="form-item-box oneboxs" v-if="props.nopicer" :style="{ width: isAutoWidth ? `100% !importent` : width }">
      <el-upload v-model:file-list="fileList" :multiple="props.multiple"
        :style="{ width: isAutoWidth ? `100% !importent` : width }"
        :show-file-list="props.ShowfileList && fileList.length > 0 ? true : false" class="upload-demo" ref="uploadRef"
        :action="actionUrl" :on-change="Changefilehandle" :before-upload="beforeImgUpload" :on-exceed="handleExceed"
        :limit="limit" :on-success="handlerSuccess" :on-preview="clickFileList" :before-remove="beforeRemove"
        :on-remove="delFile" :disabled="props.disabled" :on-error="onError" :on-progress="onProgress">
        <div :style="{ width: isAutoWidth ? `100%` : props.widthNumber + 'px', 'align-items': 'end' }" class="flex"
          v-if="props.showbut && props.showinput">
          <div class="flex flex-warp" :style="{ width: isAutoWidth ? `100%` : props.widthNumber - 100 + 'px' }">
            <div v-if="fileList.length == 0" :style="{ width: isAutoWidth ? `100%` : props.widthNumber - 100 + 'px' }">
              <el-input v-model="filename" :placeholder="placeholder" readonly
                :style="{ width: isAutoWidth ? `100% - 100px` : props.widthNumber - 100 + 'px' }"
                :disabled="props.disabled"></el-input>
            </div>
            <div v-else-if="fileList.length > 0" v-for="it in fileList" :key="it" class="flex" style="align-items: end"
              :style="{ width: isAutoWidth ? `100%` : props.widthNumber + 'px' }">
              <el-input v-model="it.name" readonly
                :style="{ width: isAutoWidth ? `100% - 200px` : props.widthNumber - 200 + 'px' }"
                :disabled="props.disabled"></el-input>
              <!-- <el-button class="ml10" @click.stop="doPreview(it)" type="primary">预览文件</el-button>    -->
              <div class="ml10 el-button el-button--primary" @click.stop="doPreview(it)" v-if="disabledStatus">预览文件
              </div>
            </div>
          </div>
          <el-button class="ml10" :disabled="props.disabled" type="primary" :loading="loading">选择文件</el-button>
        </div>
        <el-button class="ml10" :disabled="props.disabled" v-if="props.showbut && !props.showinput"
          :loading="loading">选择文件</el-button>
        <!-- <el-button class="ml10" type="primary" v-if="props.showbut">
        <el-icon>
          <Download />
        </el-icon>{{ props.title }} </el-button> -->
      </el-upload>
    </div>
    <!-- :style="{ width: width }" -->
    <div class="form-item-box" v-else>
      <el-upload :class="upload_btn ? 'hide_box' : ''" ref="uploadRefs" :multiple="props.multiple"
        v-model:file-list="fileList" class="upload-demo no-animation" list-type="picture-card" :action="actionUrl"
        :before-upload="beforeImgUpload" :on-exceed="handleExceed" :limit="limit"
        :show-file-list="fileList.length > 0 ? true : false" :on-success="handlerSuccess" :on-preview="clickFileList"
        :on-error="onError" :on-progress="onProgress">
        <template #tip>
          <div class="el-upload__tip text-red">
            <div v-if="props.nameshow && !upload_btn" style="color: red; margin-top: 10px; line-height: 18px">
              {{ typeof props.nameshow == "boolean" ? "图片支持" + filfix + "上传格式" : props.nameshow }}
            </div>
          </div>
        </template>

        <template #default>
          <el-icon v-if="isImg || isPDF || isImgOrVideo">
            <Plus />
          </el-icon>
          <div v-else-if="props.showbut && props.showinput" class="flex flex-warp"
            :style="{ width: isAutoWidth ? `100%` : props.widthNumber + 'px' }">
            <div v-if="fileList.length == 0"
              :style="{ width: isAutoWidth ? `100% - 100px` : props.widthNumber - 100 + 'px' }">
              <el-input v-model="filename" :placeholder="props.placeholder" readonly
                :style="{ width: isAutoWidth ? `100% - 100px` : props.widthNumber - 100 + 'px' }"
                :disabled="props.disabled"></el-input>
            </div>
            <div v-else-if="fileList.length > 0" v-for="it in fileList" :key="it" class="flex mt10"
              :style="{ width: isAutoWidth ? `100% - 200px` : props.widthNumber - 200 + 'px' }">
              <el-input v-model="it.name"
                :style="{ width: isAutoWidth ? `100% - 200px` : props.widthNumber - 200 + 'px' }" readonly
                :disabled="props.disabled"></el-input>
              <!-- <el-button class="ml10" @click.stop="doPreview(it)" type="primary" :class="{ 'is-disabled': isButtonDisabled }">预览文件</el-button>    -->
              <div class="ml10 el-button el-button--primary" @click.stop="doPreview(it)" v-if="disabledStatus">预览文件
              </div>
            </div>
            <el-button class="ml10" :disabled="props.disabled" type="primary">上传</el-button>
          </div>
          <div v-else-if="props.showbut && !props.showinput">
            <el-button class="ml10" :disabled="props.disabled" type="primary">上传</el-button>
          </div>
          <div v-if="loading" v-loading="loading">加载中...</div>
        </template>

        <template #file="{ file }">
          <div v-if="isImg || isPDF || isImgOrVideo" style="width: 100%; height: 100%" v-loading="loading"
            element-loading-text="上传中...">
            <template v-if="getFileType(file) == '.pdf'">
              <img class="el-upload-list__item-thumbnail"
                style="width: 60px; height: 60px; margin: 10px 43px; border: 1px dashed var(--el-color-primary)"
                :src="getImgUrl('img/pdf.png')" />
              <div style="color: black; font-size: 12px; text-align: center">{{ file.name }}</div>
            </template>
            <template v-if="isImgOrVideo && getSuffix(file.name) === 'VIDEOSP'">
              <div style="position: relative; height: 100%; width: 100%">
                <video :title="file.name" style="width: 100%; height: 100%" :src="file.url"></video>
              </div>
            </template>
            <img v-else-if="getFileType(file) != '.pdf'" class="el-upload-list__item-thumbnail"
              style="width: 100%; height: 100%; object-fit: fill" :src="file.url" alt="" />

            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon><zoom-in /></el-icon>
              </span>
              <span class="el-upload-list__item-delete" @click="handleDownload(file)">
                <el-icon>
                  <Download />
                </el-icon>
              </span>
              <span class="el-upload-list__item-delete" @click="delpicFile(file)" v-if="!props.disabled">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
              <!-- <el-popconfirm v-if="!upload_btn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="确定要删除?" @confirm="delFile(file)">
                <template #reference>

                </template>
              </el-popconfirm> -->

              <span class="el-upload-list__item-delete" @click="scFile(file)" v-if="!props.disabled">
                <el-icon v-if="file.start" style="color: #fdcd49">
                  <StarFilled />
                </el-icon>
                <el-icon v-else>
                  <Star />
                </el-icon>
              </span>
            </span>
            <span class="file-name-txt" v-if="getSuffix(file.name) != 'PDF' && !isImgOrVideo">{{ file.name }}</span>
          </div>
        </template>
        <template #footer> </template>
      </el-upload>
      <!-- 放大 -->
      <el-dialog v-model="dialogVisible" :show-close="false" top="10px">
        <div style="height: 80vh; text-align: center">
          <el-image style="width: 47vw; height: 70vh" :src="dialogImageUrl" :fit="fit" />
        </div>
      </el-dialog>
    </div>
    <!-- 预览 -->
    <el-dialog v-model="flyldialog" :show-close="false" top="10px" width="1120px">
      <div style="height: 84vh; text-align: center">
        <Kkfile :files="fileid" @changedialog="changedialog" />
      </div>
    </el-dialog>
    <!-- <div v-if="flyldialog" class="dialog-box">
        <Kkfile :files="fileid" @changedialog="changedialog" />
      </div> -->
  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { COMPONENT_WIDTH } from "@/constant"
import { computed, defineEmits, defineProps, onMounted, onUnmounted, ref, watch } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { getApi } from "@/api/tobAcco_api.js"
import Kkfile from "@/components/MyComponents/kkfile/index.vue"

const uploadRef = ref(null)
const uploadRefs = ref(null)
const filename = ref("")
const filfix = ref(null)
const upload_btn = ref(false)
const fileid = ref("")
// 传给子组件的id
const fileListId = ref([])
const flyldialog = ref(false)
const fileNamelist = ref([])
const fileList = ref([])
const dialogImageUrl = ref("")
const dialogVisible = ref(false)
const loading = ref(false)
const isButtonDisabled = ref(false)
/** 组件最外层的Ref */
const uploadOutRef = ref()
/** 自动设置的宽度 (300px)*/
// const autoWidth = ref('300px')
const props = defineProps({
  disabledStatus: {
    type: Boolean,
    default: true
  },
  isShow: {
    default: false,
    type: Boolean
  },
  //刷新组件
  keys: {
    type: Number,
    default: 10
  },
  // 提示字体，如果为boolean类型，给默认提示，如果为string类型，则提示传进来的值
  nameshow: {
    type: Boolean,
    default: false
  },
  // 是否预览学习法律法规标准
  studyShowId: {
    type: String,
    default: ''
  },
  //是否展示新增
  disabled: {
    type: Boolean,
    default: false
  },
  //获取组件传值
  modelValue: {
    type: [String, Array],
    default: () => { }
  },
  //限制附件数量
  limit: {
    type: Number,
    default: 10
  },
  //按钮名称
  title: {
    type: String,
    default: "选择文件"
  },
  //是否只上传图片
  isImg: {
    type: Boolean,
    default: false
  },
  //是否上传PDF
  isPDF: {
    type: Boolean,
    default: false
  },
  //是否只上传视频格式
  isVideosp: {
    type: Boolean,
    default: false
  },
  /** 是否只上传 【图片，视频】格式 */
  isImgOrVideo: {
    type: Boolean,
    default: false
  },
  //是否展示上传按钮
  showbut: {
    type: Boolean,
    default: true
  },

  width: {
    default: COMPONENT_WIDTH,
    type: String
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  //列表形式
  nopicer: {
    type: Boolean,
    default: false
  },
  // 是否显示文件列表
  ShowfileList: {
    type: Boolean,
    default: true
  },
  //需要删除的对象
  delrow: {
    type: Object,
    default: {}
  },
  //附件上传的宽度，类型数字
  widthNumber: {
    type: Number,
    default: 700
  },
  //是否搭配输入框
  showinput: {
    type: Boolean,
    default: false
  },
  //输入框默认提示
  placeholder: {
    type: String,
    default: "请选择文件"
  },
  //限制只能上传某些附件=>:gsgfList="['pdf','doc','docx','xls','xlsx']"
  gsgfList: {
    type: Array,
    default: []
  },
  //多选
  multiple: {
    type: Boolean,
    default: false
  },
  /** 自动设置宽度 */
  isAutoWidth: {
    type: Boolean,
    default: false
  },
  //文件类型
  accept: {
    type: String,
    default: ""
  },
  // 文件最大尺寸
  maxSize: {
    type: Number,
    default: 20 * 1024 * 1024
  },
  /** model值类型,避免每次转格式  */
  stringify: {
    type: Boolean,
    default: false
  }
})
const actionUrl = computed(() => "/mosty-api/mosty-base/minio/image/upload/id")
const emits = defineEmits(["update:modelValue", "handleChange", "filehandleChange"])
//获取附件格式=>fileTypeArr:传入的附件格式
const getfileGs = (fileName, fileTypeArr) => {
  let fileType = ""
  try {
    // 后缀名
    const suffix = fileName.substr(fileName.lastIndexOf(".") + 1, 4) || "" //截取最后一个点号后4个字符
    fileType = suffix.toLowerCase() //转小写,方便忽略可以传大写的文件名
  } catch (err) {
    fileType = ""
    return "OTHER"
  }
  // fileName无后缀返回 false
  if (!fileType) return ""
  if (fileTypeArr.includes(fileType)) return "Yestype"
}
//获取后缀
const getSuffix = fileName => {
  let suffix = ""
  try {
    suffix = fileName.substr(fileName.lastIndexOf(".") + 1, 4) //截取最后一个点号后4个字
  } catch (err) {
    suffix = ""
    return "OTHER"
  }
  // fileName无后缀返回 false
  if (!suffix) return ""

  // 图片格式
  var imglist = ["png", "jpg", "jpeg", "bmp", "gif"]
  if (imglist.includes(suffix) || imglist.includes(suffix.toLowerCase())) return "IMG"
  //视频格式
  let videospList = ["mp4", "avi", "wmv", "mpg", "mov", "rm", "flv"]
  if (videospList.includes(suffix) || videospList.includes(suffix.toLowerCase())) return "VIDEOSP"
  //txt
  if (suffix === "txt" || suffix.toLowerCase() === "txt") return "TXT"

  //excel XLS
  const excelist = ["xls", "xlsx"]
  if (excelist.includes(suffix) || excelist.includes(suffix.toLowerCase())) return "XLS"

  // 匹配 word
  var wordlist = ["doc", "docx"]
  if (wordlist.includes(suffix) || wordlist.includes(suffix.toLowerCase())) return "DOC"

  //pdf
  if (suffix === "pdf" || suffix.toLowerCase() === "pdf") return "PDF"

  // WPS
  if (suffix === "wps" || suffix.toLowerCase() === "WPS") return "WPS"

  //ofd
  if (suffix === "ofd" || suffix.toLowerCase() === "ofd") return "OFD"
  //视频 音频
  var videolist = ["mp4", "m2v", "mkv", "rmvb", "wmv", "avi", "flv", "mov", "m4v"]
  if (videolist.includes(suffix) || videolist.includes(suffix.toLowerCase())) return "VIDEO"

  var musiclist = ["mp3", "wav", "wmv"]
  if (musiclist.includes(suffix) || musiclist.includes(suffix.toLowerCase())) return "MUSIC"

  var pptlist = ["ppt", "pptx"]
  if (pptlist.includes(suffix) || pptlist.includes(suffix.toLowerCase())) return "PPT"

  //压缩包
  var yslist = ["7z", "rar", "zip", "apz", "ar", "hpk", "hyp", "hbc2"]
  if (yslist.includes(suffix) || yslist.includes(suffix.toLowerCase())) return "YS"

  //否则返回other
  return "OTHER"
}
watch(
  () => props.modelValue,
  newVal => {
    filfix.value = props.gsgfList ? props.gsgfList.toString() : null
    if (newVal) {
      if (newVal instanceof Array) return //如果是上传时的数据 不做处理
      // 是否不需要设置数据
      const isNotNeedSet = () => {
        // 本地都有就不用请求数据设置了
        let ids = typeof newVal === "string" ? newVal.split(",") : []
        return ids.every((id, idx) => {
          return ids?.length == fileList.value?.length && fileList.value?.[idx]?.id == id && fileListId.value?.[idx] == id
        })
      }

      if (isNotNeedSet()) return
      // 回显时处理
      fileList.value = []
      let ids = newVal.split(",")
      fileListId.value = ids
      Promise.all(
        ids.map(async item => {
          return getApi({}, `/mosty-base/minio/file/download/${item}`)
        })
      ).then(resPicArr => {
        const fileArr = Array.isArray(resPicArr) ? resPicArr : []
        /** 因为异步，验证下是否是当前的ids结果 */
        const isNowRes = fileArr.length === ids.length && fileArr.every((item, i) => item.id === ids[i])
        if (isNowRes) {
          fileList.value = fileArr.map(res => {
            return {
              name: res.originalName,
              id: res.id,
              url: res.url,
              suffix: res.suffix
            }
          })
          if (fileList.value[0]) fileList.value[0].start = true
          fileNamelist.value = fileList.value
          emits("filehandleChange", fileList.value)
        }
      })
    } else {
      fileList.value = []
      fileNamelist.value = []
    }
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => props.disabled,
  val => {
    upload_btn.value = val
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => props.delrow,
  val => {
    if (val) {
      handleRemove(val)
    }
  }
)
watch(
  () => props.keys,
  val => {
    if (val) {
      fileNamelist.value = []
    }
  }
)
//预览
function doPreview(item) {
  if (item) {
    fileid.value = item.id
    if (props.isShow) {
      getApi({ rwId: props.studyShowId }, `/mosty-jcgl/lawRegulations/previewLearning`)
        .then((res) => {
          console.log(res)
        });
    }
    flyldialog.value = true
  } else {
    ElMessage.warning(`请先上传文件`)
  }
}
function Changefilehandle(params) { }
function changedialog() {
  flyldialog.value = false
}
function beforeRemove(uploadFile, uploadFiles) {
  if (uploadFile?.status === "success") {
    // 解题决上传文件格式不符合时，也会触发【确认删除】弹框事件
    return ElMessageBox.confirm(`确认删除 ${uploadFile.name}文件 ?`).then(() => true)
  }
}
function delpicFile(file) {
  ElMessageBox.confirm(`确认删除 ${file.name}文件 ?`).then(() => {
    delFile(file)
  })
}
function formmatVal(val) {
  console.log("props.stringify: ", props.stringify)
  if (props.stringify) return val ? val.toString() : ""
  return val
}
function delFile(file) {
  fileList.value = fileList.value.filter(item => {
    return item.id !== file.id
  })
  const fileIds = fileList.value.map(item => item.id)
  emits("update:modelValue", formmatVal(fileIds))
  // if (file.id) {
  //   fileList.value = fileList.value.filter((item) => {
  //     return item.id !== file.id;
  //   });
  //   const index1 = fileListId.value.findIndex((item) => item === file.id);
  //   if (index1 !== -1) {
  //     fileListId.value.splice(index1, 1);
  //     emits("update:modelValue", fileListId.value);
  //   }
  // } else if (file.response.data) {
  //   delisfile.value = delisfile.value.filter((item) => {
  //     return item.url !== file.url;
  //   });
  //   fileList.value = delisfile.value
  //   let id = file.response.data
  //   const index3 = fileListId.value.findIndex((item) => item === id);
  //   const index4 = fileNamelist.value.findIndex((item) => item.data === id);
  //   if (index3 !== -1) {
  //     fileListId.value.splice(index3, 1);
  //     emits("update:modelValue", fileListId.value);
  //   }
  //   //删除输入附件框内容
  //   if (index4 !== -1) {
  //     fileNamelist.value.splice(index4, 1);
  //   }
  // }
  upload_btn.value = false
}
//获取文件得格式
const getFileType = val => {
  if (val.name !== undefined) {
    return val.name.substring(val.name.length - 4, val.name.length)
  }
}
const onError = () => {
  loading.value = false
}
const onProgress = (val, val2) => {
  let percent = val?.percent
  if (percent > 0 && percent < 100) {
    loading.value = true
  } else {
    loading.value = false
  }
}
const handlerSuccess = (res, file, list) => {
  loading.value = false
  if (res.code == "10000") {
    const newFileList = list.map(item => {
      return {
        url: item.url,
        name: item.name,
        id: item.id ? item.id : item?.response?.data // 获取文件 ID
      }
    })
    dialogVisible.value = false
    fileList.value.push(newFileList[newFileList.length - 1])
    if (props.limit == 1) {
      emits("update:modelValue", formmatVal([res.data]))
      upload_btn.value = true
    } else {
      fileListId.value = newFileList.map(item => item.id)
      emits("update:modelValue", formmatVal(fileListId.value))
      if (fileList.value.length == props.limit) {
        upload_btn.value = true
      }
    }

    emits("filehandleChange", newFileList)
  } else {
    fileList.value = []
    ElMessage.error(res.message)
  }
}
const handleExceed = (files, fileList) => {
  ElMessage.warning(`限制，只能上传${props.limit}个文件或图片`)
  upload_btn.value = true
}
/** 是否在限制尺寸之内
 * @param file 文件对象
 * @param isShowMessage 是否显示提示信息
 */
const isSizeOK = (file, isShowMessage) => {
  const isSizeValid = file.size < props.maxSize
  if (!isSizeValid && isShowMessage) {
    let num = props.maxSize / 1024 / 1024
    ElMessage.error(`上传文件大小不能超过 ${num}MB!`)
  }
  return isSizeValid
}

const beforeImgUpload = file => {
  // loading.value = true;
  // if (getSuffix(file.name) === "OFD") {
  //   let isPDF = false;
  //   ElMessage.error("上传附件不能是OFD格式!");
  //   return isPDF
  // }

  if (props.isImg) {
    let isIMG = false
    if (getSuffix(file.name) === "IMG" || getSuffix(file.name) === "PDF") {
      isIMG = true
    }
    // const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isIMG) {
      ElMessage.error("上传图片只能是jpg/png/jpeg/bmp/gif格式!")
    }
    // if (!isLt5M) {
    //   ElMessage.error("上传图片大小不能超过 5MB!");
    // }
    // return isIMG && isLt5M;
    return isIMG
  }
  if (props.isPDF) {
    let isPDF = false
    if (getSuffix(file.name) === "PDF") {
      isPDF = true
    }
    if (!isPDF) {
      ElMessage.error("上传图片只能是PDF格式!")
      // loading.value = false
    }
    return isPDF
  } else if (props.isVideosp) {
    /** 是否在限制尺寸之内 */
    const isSizeOk = file.size < props.maxSize
    if (!isSizeOk) {
      let num = props.maxSize / 1024 / 1024
      ElMessage.error(`上传文件大小不能超过 ${num}MB!`)
    }
    let isSP = false
    if (getSuffix(file.name) === "VIDEOSP") {
      isSP = true
    }
    if (!isSP) {
      ElMessage.error("上传的不是视频格式，请重新上传！！")
    }
    return isSP && isSizeOk
  } else if (props.isImgOrVideo) {
    if (!isSizeOK(file, true)) return false
    /** 文件名合格 */
    const isFileNameOk = getSuffix(file.name) === "IMG" || getSuffix(file.name) === "PDF" || getSuffix(file.name) === "VIDEOSP"
    if (!isFileNameOk) ElMessage.error("上传附件只能是图片或视频格式！")
    return isFileNameOk
  } else if (props.gsgfList && props.gsgfList.length > 0) {
    let isFh = false
    if (getfileGs(file.name, props.gsgfList) === "Yestype") {
      isFh = true
    }

    if (!isFh) {
      ElMessage.error("上传的文件格式不符合，请重新上传！！")
    }
    return isFh
  } else {
    return true
  }
}

const handlePictureCardPreview = uploadFile => {
  if (getSuffix(uploadFile.name) === "IMG") {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  } else {
    fileid.value = uploadFile.id
    flyldialog.value = true
  }
}
//收藏图片
function scFile(file) {
  fileList.value.forEach(item => {
    if (item.id == file.id) {
      item.start = true
    } else {
      item.start = false
    }
  })
  fileList.value.sort((a, b) => {
    if (a.start === true) {
      return -1
    } else if (b.start === true) {
      return 1
    } else {
      return 0
    }
  })
  fileListId.value = fileList.value.map(item => {
    return item.id
  })
  emits("update:modelValue", formmatVal(fileListId.value))
}
const handleDownload = file => {
  if (file.response) {
    window.open(`/mosty-api/mosty-base/minio/image/download/${file.response.data}`, "_blank")
  } else {
    // window.open(file.url, "_blank");
    createAndClickLink(file.url, file.name)
  }
}
//附件列表点击事件（点击附件进行下载）
const clickFileList = file => {
  if (file.url) {
    createAndClickLink(file.url, file.name)
  } else {
    getApi({}, `/mosty-base/minio/file/download/${file.id}`).then(res => {
      createAndClickLink(res.url, res.originalName)
    })
    // window.open(`/mosty-api/mosty-base/minio/image/download/${file.id}`, "_blank");
  }
}

const createAndClickLink = (downloadUrl, fileName) => {
  return new Promise((resolve, reject) => {
    const xhr = new window.XMLHttpRequest()
    xhr.open("GET", downloadUrl, true)
    xhr.responseType = "blob"
    xhr.onload = () => {
      const url = window.URL.createObjectURL(xhr.response)
      const a = document.createElement("a")
      a.href = url
      a.download = fileName
      // 使用 setTimeout 延迟点击操作
      setTimeout(() => {
        a.click()
        window.URL.revokeObjectURL(url) // 释放资源
        resolve() // 解决 Promise
      }, 0)
    }
    xhr.onerror = () => {
      reject(new Error("文件下载失败"))
    }
    xhr.send()
  })
}
const handleRemove = file => {
  fileList.value = fileList.value.filter(item => {
    return item.id !== file.id
  })
  const fileIds = fileList.value.map(item => item.id)
  emits("update:modelValue", formmatVal(fileIds.value))
  // if (file.data) {
  //   //有id就通过id删除
  //   const index = fileListId.value.findIndex((item) => item === file.data);
  //   const indexs = fileNamelist.value.findIndex((item) => item.data === file.data);
  //   if (index !== -1) {
  //     fileListId.value.splice(index, 1);
  //     emits("update:modelValue", fileListId.value);
  //   }
  //   //删除输入附件框内容
  //   if (indexs !== -1) {
  //     fileNamelist.value.splice(indexs, 1);
  //   }
  // } else if (file.id) {
  //   const index1 = fileListId.value.findIndex((item) => item === file.id);
  //   const index2 = fileNamelist.value.findIndex((item) => item.data ? item.data : item.id === file.id);
  //   if (index1 !== -1) {
  //     fileListId.value.splice(index1, 1);
  //     emits("update:modelValue", fileListId.value);
  //   }
  //   //删除输入附件框内容
  //   if (index2 !== -1) {
  //     fileNamelist.value.splice(index2, 1);
  //   }
  // } else if (file.response.data) {
  //   let id = file.response.data
  //   const index3 = fileListId.value.findIndex((item) => item === id);
  //   const index4 = fileNamelist.value.findIndex((item) => item.data === id);
  //   if (index3 !== -1) {
  //     fileListId.value.splice(index3, 1);
  //     emits("update:modelValue", fileListId.value);
  //   }
  //   //删除输入附件框内容
  //   if (index4 !== -1) {
  //     fileNamelist.value.splice(index4, 1);
  //   }
  // }
  // emits("filehandleChange", fileNamelist.value);
  // handlerSuccess()
}
/** 自动设置宽度 如果是自动宽度(props.isAutoWidth=true) 就设置宽度 */
const setWidthAuto = () => {
  // if (!props.isAutoWidth) return;
  // const ele = uploadOutRef.value && uploadOutRef.value.parentElement;
  // if (!ele) return;
  // autoWidth.value = ele.offsetWidth;
}
onMounted(() => {
  setWidthAuto()
  window.addEventListener("resize", setWidthAuto)
})
onUnmounted(() => {
  window.removeEventListener("resize", setWidthAuto)
})
</script>

<style lang="scss" scoped>
::v-deep .hide_box .el-upload--picture-card {
  display: none;
}

.oneboxs {
  ::v-deep .el-upload {
    width: 100% !important;
    text-align: start !important;
  }
}

// .hide_box .el-upload--picture-card {
//   display: none !important;
// }

::v-deep .upload-demo {
  text-align: left;
}

.list_box {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 10px;
  color: #fff;

  .one_text_detail {
    color: #1983e5;
  }

  .icon_box {
    display: flex;

    &>div {
      margin-left: 10px;
    }
  }
}

::v-deep .el-upload-list__item {
  // width: 100% !important;
  transition: unset !important;

  .el-icon--close {
    font-size: 16px;
    color: red;
  }

  &:hover {
    background: transparent;
  }
}

::v-deep .el-upload-list__item-status-label {
  font-size: 16px;
}

::v-deep .el-upload-list__item-name {
  .el-icon--document {
    font-size: 16px;
    top: 2px;
  }
}

::v-deep .el-upload-list__item-name {
  font-size: 15px;
}

::v-deep .form-item-box {
  width: 100% !important;
  // min-width: 270px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-actions {
  // position: absolute;
  // width: 100%;
  height: 21% !important;
  left: 0;
  top: 115px !important;
  bottom: 0 !important;
  cursor: default;
  text-align: center;
  color: #fff;
  // opacity: 0;
  font-size: 20px;
  background-color: rgba(27, 129, 62, 0.7);
  // transition: opacity var(--el-transition-duration);
}

.yellse {
  color: #fdcd49 !important;
}

.no-animation {
  ::v-deep .el-upload-list__item {
    transition: unset !important;
  }
}

.is-disabled {
  pointer-events: none;
  // opacity: 0.5;
}

.file-name-txt {
  display: inline-block;
  width: 148px;
  text-align: center;

  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: black;
}
</style>
