<template>
  <div class="upload-input">
    <el-upload
      ref="upload"
      v-bind="$attrs"
      class="avatar-uploader"
      v-model:file-list="fileList"
      action=""
      :show-file-list="props.imges"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :http-request="handleUploadFile"
      :on-exceed="handleExceed"
      :limit="props.limit"
    >
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 上传图片，并返回id，多个以,号分割
 */
import useBaseStore from '@store/modules/base'
import {_list, _view, _export, _add, _adds, _up, _ups, _del} from '@/api/app'
import {genFileId} from 'element-plus'
const baseStore = useBaseStore()
const fileList = ref([])
const upload = ref(null)
// {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
// }
const dialogImageUrl = ref('') // 预览图片的url
const dialogVisible = ref(false) // 是否显示预览图片的弹窗
const fileIds = ref([]) // 上传后返回的id集合
const fileUrl = ref([]) // 上传后返回的url集合
const props = defineProps({
  limit: {
    type: Number
  },
  attmodel: {
    type: String
  },
  attId: {
    type: String
  },
  oldUrl: {
    type: String
  },
  imges: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['update:fileID', 'update:fileUrl'])

const handleRemove = (uploadFile, uploadFiles) => {
  fileIds.value = fileIds.value.filter((item) => item.uid !== uploadFile.uid)
  const idStr = fileIds.value.map((item) => item.id).join(',')
  emits('update:fileID', idStr)
}

// const handleExceed = (files) => {
//   upload.value.clearFiles()
//   const file = files[0]
//   file.uid = genFileId()
//   upload.value.handleStart(file)
//   console.log(file, 'file')
//   handleUploadFile(file)
// }

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const handleUploadFile = async (option) => {
  const {file} = option
  console.log(file, option)

  // uid: 1701335764403
  // lastModified: 1701138254763
  // name: "dark.78ba5f53.svg"
  // size: 2625
  // type: "image/svg+xml"

  const formData = {
    attmodel: props.attmodel, //模块
    attpath: '/account/', //路径
    file
  }

  // const formData = new FormData()
  // formData.append(`attmodel`, 'account') //模块
  // formData.append(`attpath`, '/account/')  //路径
  // formData.append(`pic${fileList.value.length}`, file) //文件

  // 上传图片
  await baseStore.attachmentAddtoPath(formData).then((res) => {
    // Data: "2023113021355006455689"
    // Message: "执行成功"
    // OtherData: null
    // Status: 0

    if (res.Status === 0) {
      fileIds.value.push({
        uid: file.uid,
        id: res.Data
      })
      const idStr = fileIds.value.map((item) => item.id).join(',')
      emits('update:fileUrl', idStr)

      // 上传图片成功,将回调的id生成完整的图片url
      // generateImgAllUrl(res.Data)
    }
  })
}

// 查询图片详情
import useDictStore from '@store/modules/dict'
const generateImgAllUrl = async (attId) => {
  if (attId) {
    const response = await _list({
      pagevalue: 123,
      attlsh: attId,
      attmodel: 'aiimage',
      attpath: '/aiimage/',
      ['attdelcode.value']: 0,
      pageindex: 1,
      rows: 9999
    })
    const {Data, Status, Message} = response
    if (Status === 0) {
      if (Data.Data.length) {
        const fileHeadUrl = useDictStore().getDict('fileheadurl')
        const url = fileHeadUrl[0].substance + Data.Data[0].attpath + Data.Data[0].attname + '.' + Data.Data[0].atttype
        fileUrl.value.push({
          url: url,
          id: attId
        })
        const fileUrlStr = fileUrl.value.map((item) => item.url).join(',')
        console.log(fileUrlStr, 'fileUrlStr')
        emits('update:fileUrl', fileUrlStr)
      }
    }
  }
}

onMounted(async () => {
  // console.log(props.oldUrl, 'props')
  // console.log(fileList.value, 'fileList')
  if (props.oldUrl) {
    fileList.value.push({url: props.oldUrl, name: 'img'})
  }

  // const filepath = useDictStore().getDict('filepath')
  // const fileHeadUrl = useDictStore().getDict('fileheadurl')
  // console.log(filepath, fileHeadUrl)
  // if (props.attId) {
  //   const response = await _list({
  //     pagevalue: 123,
  //     attlsh: '2023122612241915333077',
  //     attmodel: 'aiimage',
  //     attpath: '/aiimage/',
  //     ['attdelcode.Value']: 0,
  //     pageindex: 1,
  //     rows: 9999
  //   })
  //   const {Data, Status, Message} = response
  //   if (Status === 0) {
  //     if (Data.Data.length) {
  //       const url = filePath + Data.Data[0].attpath + Data.Data[0].attname + '.' + Data.Data[0].atttype
  //       state.avatarImg = url
  //       console.log(url, 'urlurlurl')
  //     }
  //   }
  // }
})

defineExpose({
  clearFiles() {
    fileList.value = []
    fileIds.value = []
  }
})
</script>

<style lang="scss" scoped></style>
