<template>
  <!-- capture="user environment" -->
  <q-uploader
    class="upload-file"
    :class="{
      'no-list': !props.multiple
    }"
    :multiple="props.multiple"
    :headers="headers"
    :with-credentials="false"
    no-thumbnails
    v-bind="attrs"
    :url="service.defaults.baseURL+props.url"
    ref="uploaderRef"
    max-file-size="20971520"
    auto-upload
    color="white"
    text-color="grey-7"
    @uploaded="uploaded"
    @failed="uploadFailed"
    @finish="onFinish"
    @rejected="onRejected"
  >
    <template v-slot:header="scope">
      <span>
        <slot name="header" v-bind="scope">
          <q-circular-progress
            v-if="scope.isUploading"
            :value="parseFloat(scope.uploadProgressLabel)"
            size="md"
            color="red"
            track-color="grey-3"
            class="absolute-center"
          >
          </q-circular-progress>
          <slot name="header-content">
            <q-icon name="file_upload" />
          </slot>
        </slot>
	<!-- v-show="!scope.isBusy" -->
      <template v-if="!props.disable">
        <template v-if="$q.platform.is.android && $q.platform.is.cordova">
          <div class="q-uploader__input overflow-hidden absolute-full">
            <q-menu self="top start" :offset="[-10, -10]" touch-position>
              <q-list style="min-width: 120px">
                <q-item clickable v-close-popup @click="onClick($event,scope)">
                  <q-item-section>拍照</q-item-section>
                </q-item>
                <q-separator />
                <q-item clickable v-close-popup @click="scope.pickFiles">
                  <q-item-section>选择图片</q-item-section>
                  <q-uploader-add-trigger ref="triggerRef" />
                </q-item>
              </q-list>
            </q-menu>
          </div>
        </template>
        <q-uploader-add-trigger v-else ref="triggerRef" />
      </template>
      </span>
    </template>
    <template v-if="slots.list" v-slot:list="scope" >
      <slot name="list" v-bind="scope"></slot>
    </template>
  </q-uploader>
</template>
<script setup>
import { ref, reactive, onMounted, useAttrs, defineEmits, useSlots } from 'vue';
import { api, service } from "boot/axios";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import {captureImage,IS_MOBILE} from 'src/utils/mobile'
const props = defineProps({
  'multiple':Boolean,
  'url':String,
  'disable':Boolean
})
const slots = useSlots()
const emit = defineEmits( ['uploaded','failed'])
const attrs = useAttrs()
const $q = useQuasar();
const router = useRouter();
const uploaderRef = ref(null);
const triggerRef = ref(null)
const headers = [
  {name: 'Authorization',value: service.defaults.headers.common['Authorization']},
  {name: 'Accept', value: 'application/json'}
]
function formatResponse(xhr){
  let res
  try{
    res = JSON.parse(xhr.responseText)
  }catch(e){
  }
  return res
}
function uploaded({files, xhr}){
  const res = formatResponse(xhr)
  if(res.code !== 200){
    return uploadFailed({files,xhr})
  }
  if(triggerRef.value?.$el){
    triggerRef.value.$el.value = ''
  }
  emit("uploaded",res)
}
function uploadFailed({files, xhr}){
  const res = formatResponse(xhr)
  let msg = res?.message||xhr.responseText||xhr.statusText||"网络异常，请稍后重试！"
  $q.notify({
    type: 'negative',
    message: msg
  })
  emit("failed",new Error(msg))
}
function onRejected(rejectedEntries){
  let msg = rejectedEntries.reduce((total,item)=>{
    let str = ''
    switch(item.failedPropValidation){
      case 'accept':
        str = "文件格式不正确"
        break;
      case 'max-file-size':
        str = '文件太大，无法上传'
        break;
      default:
        str = '上传失败，请检查文件'
    }
    return total + (total?'\n':'') + str
  },'')
  $q.notify({
    type: 'negative',
    message: msg
  })
  emit("failed",new Error(msg))
}
function onClick(event,scope){
  !props.multiple && scope.reset()
  if(IS_MOBILE){
    captureImage().then(file => {
      scope.addFiles([file])
    }).catch(e=>{
    })
  }else{
    scope.pickFiles(event)
  }
}
function onFinish(){
  uploaderRef.value.reset()
}
</script>
<style lang="scss" scoped>
.upload-file.no-list{
  :deep(.q-uploader__list){
    display: none;
  }
}
</style>
