<template>

  <a-upload list-type="picture-card" @change="onChangeFile" accept="image/*" :file-list="fileList"
    @before-upload="beforeUpload" @before-remove="beforeMove" action="/"  :multiple="isMultiple" :auto-upload="false" image-preview />
</template>
<script setup>
  import { ref, getCurrentInstance,toRefs,watch} from 'vue';
  import { ossSign, ossUpload } from '@/api/oss';
  import dayjs from 'dayjs'
  const { proxy } = getCurrentInstance();
  const props = defineProps({
    // 数组名称
      fileList: {
        type: Array,
      },
      dataType:{
        type:String
      },
      isMultiple: {
        type: Boolean,
        default:false
      }
     });

  const {fileList,isMultiple,dataType} = toRefs(props);
  const emits = defineEmits(['changeData']);
  const beforeUpload = (file) => {
   
    return new Promise((resolve, reject) => {
      if(!isMultiple.value && fileList.value.length>=1){
        proxy.$notification.error("只能上传一张图片,请先删除原有图片");
        reject('cancel')
      }else if (file.size >= 10 * 1024 * 1024) {
        proxy.$notification.error("图片大小不能超过10M");
        reject('cancel')
      } else {
         resolve(true);
         
         let scene=1;
        if(dataType.value=="license_cert_list" || dataType.value=="qualification_cert_list" || dataType.value=="work_cert_list" || dataType.value=="sign_image_list" || dataType.value=="id_card_front_list" || dataType.value=="id_card_back_list"){
          scene=2
        };
        getOssSign(scene,file)
       }
    });
  };
  const beforeMove=(file)=>{
    return new Promise((resolve, reject) => {
       emits("changeData",{url:file.url,type:dataType.value,dealType:"remove"})
       resolve(true)
    });
  }
  //上传文件
 const onChangeFile = (fileList) => {
 
    // for (let i = 0; i < fileList.length; i++) {
    //   getOssSign(1, fileList[i].file);
    // }
    // //getOssSign(1, fileList[0].file);
    // console.log(fileList)
  };
  //获取oss签名
  const getOssSign = async (scene, File) => {
    proxy.$loading.show();
    const { data, code, message } = await ossSign({
      user_type: 2,
      scene,
    });
    if (code == 200) {
      let { access_id, dir, policy, signature, host } = data;
      let filename = File.name;
      let time = dayjs().format("YYYYMMDDHHmmss")
      let formData = new FormData();
      formData.append('OSSAccessKeyId', access_id);
      formData.append('policy', policy);
      formData.append('signature', signature);
      formData.append('key', dir + time + filename);
      formData.append('file', File, filename);
      ossUpload(host, formData).then((res) => {
        proxy.$loading.hide();
        emits("changeData",{url:host+"/"+ dir + time + filename,type:dataType.value,dealType:"add"})
        // if(fileNum.value==fileList.value.length){
        //   fileNum.value=0;
        //   proxy.$loading.hide();
        // }
      });

    } else {
      proxy.$notification.error(message);
    }
  }
 
</script>
