<template>
  <div class="clearfix">
    <a-upload
      v-model:file-list="fileList"
      list-type="picture"
      :multiple="true"
      :accept="accept"
      @remove="remove"
      :beforeUpload="change"
      @preview="handlePreview"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        upload
      </a-button>
    </a-upload>

    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="previewVisible=false;previewTitle=''" width="1000px">
      <img alt="example" style="width: 100%" v-if="previewImage" :src="previewImage" />
      <video :src="previewVideo" v-if="previewVideo" controls></video>
    </a-modal>
  </div>
</template>
<script setup>
import { UploadOutlined } from '@ant-design/icons-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {ref, defineProps, defineEmits, onMounted} from 'vue'
import Api from '@/api/api'
import Up from '@/api/upload'
import utils from '@/utils/utils'
const emit = defineEmits(['uploadSuccess'])
const props = defineProps({
  id:String,
  text:String,
  bindData:Object,
  accept: {
    type:String,
    default:() => {
      return ''
    }
  }
})
const previewVisible = ref(false)
const previewImage = ref('')
const previewVideo = ref('')
const previewTitle = ref('')
let fileList = ref([])
let currentIndex = ref(0)
let callback = ref('')

const handlePreview = async file => {
  previewImage.value = false
  previewVideo.value = false
  console.log(file);
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  if (file.postfix && 'mp4 avi mov wmv rmvb mkv m4v'.indexOf(file.postfix) != -1) {
    previewVideo.value = file.url || file.preview
    previewVisible.value = true
  } else if (file.postfix && 'bmp jpg png tif gif pcx tga exif fpx svg psd cdr pcd dxf ufo eps ai raw WMF webp avif apng'.indexOf(file.postfix) != -1) {
    previewImage.value = file.url || file.preview
    previewVisible.value = true
  } else {
    console.log('触发',file);
    window.open(file.url || file.preview,'_self')
  }
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}


/* 主动上传 */
let change = (file) => {
  if (Object.keys(props.bindData).length) {
    fileList.value = [...fileList.value,file]
    let index = file.name.lastIndexOf(".");
    let type = file.name.substr(index + 1);
    getUploadUrl(file.name, type,file)
  }
  return false
}

/* 外部触发上传 */
let toUpload = (fun) => {
  callback.value = fun
  console.log(callback.value);
  currentIndex.value = 0
  fileList.value.forEach(file=>{
    let index = file.originFileObj.name.lastIndexOf(".");
    let type = file.originFileObj.name.substr(index + 1);
    getUploadUrl(file.name, type,file.originFileObj)
  })
  
}
const getUploadUrl = async (filename,type,file)=>{
  const res = await Api.requested({
    "classname": "system.attachment.huawei.OBS",
    "method": "getFileName",
    "content": {
      "filename": filename,
      "filetype": type,
      "parentid": appfolderid.value//归属文件夹ID
    }
  })
  let url = res.data.uploadurl

  let obsfilename = res.data.serialfilename

  upoladFileToServer(url, file, type, obsfilename)
}
const setProgress = (percent)=>{
  return {
    strokeColor: {
      '0%': '#108ee9',
      '100%': '#87d068',
    },
    strokeWidth: 3,
    format: percent => `${parseFloat(percent.toFixed(2))}%`,
    class: 'test',
  };
}
const upoladFileToServer = async (url, file, ext, obsfilename)=> {
  let config = {
    headers: ext === 'pdf' ? { 'Content-Type': 'application/pdf' } : ext === 'svg'?{ 'Content-Type': 'image/svg+xml' } : { 'Content-Type': 'application/octet-stream' },
    onUploadProgress: function (progressEvent) {
      let percent = progressEvent.loaded / progressEvent.total * 100
      fileList.value = fileList.value.map((e,index) => {
        if (e.uid === file.uid) {
          e = { ...e, percent: percent.toFixed(0) }
        }
        return e
      })
    },
  }
  await Up.upload(url, file, config)
  createFileRecord(obsfilename)
}
// 上传成功以后生成附件记录
const createFileRecord = async (obsfilename)=> {
  let obj = {
    "serialfilename": obsfilename
  }
  obj = Object.assign({},obj,props.bindData)
  let param = {
    "classname": "system.attachment.huawei.OBS",
    "method": "uploadSuccess",
    "content":obj
  }
  const res = await Api.requested(param)
  emit('uploadSuccess',res)
  currentIndex.value++
  if (currentIndex.value >= fileList.value.length) {
    callback.value && callback.value()
    currentIndex.value = 0
  }
  if (Object.keys(props.bindData).length) {
    let data = JSON.parse(res.attinfos)
    fileList.value[fileList.value.length - 1].linksid = data.data[data.data.length - 1].linksid
  }
  
}

let remove = async (data) => {
  let res = await Api.requested({
    "classname": "system.attachment.Attachment",
    "method": "deleteFileLink",
    "content": {
        "linksids": [
            data.linksid
        ]
    }
  })
  utils.message(res,'删除成功',() => {
    // fileList.value.splice(fileList.value.findIndex(item => item == data),1)
    console.log(fileList.value);
    emit('deleteSuccess')
  })
}


const appfolderid = ref('')
const salematerialfolderid = ref('')
const querySite_Parameter = async ()=> {
  const res = await Api.requested({
    "id":20230608103802,
    "content": {}
  })
  appfolderid.value = res.data.appfolderid, // 应用附件文件夹ID
  salematerialfolderid.value = res.data.salematerialfolderid // 营销物文件夹ID
}

let refresh = () => {
  fileList.value = []
}

onMounted(() => {
  querySite_Parameter()
})

defineExpose({
  toUpload,
  fileList,
  refresh
})
</script>

<style scoped>
/deep/.ant-upload-list-item-error {
  border-color: #d9d9d9 !important;
}
</style>
