<script setup lang="ts">
import { httpFileUpload } from "/@/api/sellOut/bargainList";
import { useVModel } from "@vueuse/core"
import { ElMessage} from "element-plus"
import { getToken } from "/@/utils/auth";
import { useTask } from "/@/hooks/core"
import { ref, watch } from "vue"

const props = defineProps<{ modelValue: string }>()
const modelValue = useVModel(props, 'modelValue')
const file_name = ref('')

const uploadTask = useTask({ success(data){
  ElMessage.success('上传成功')
  file_name.value = data[0].name
  modelValue.value = `http://cxinv.api.caixiao365.com/${data[0].url}`
} })

async function handleUpload({ file }){
  const token = getToken()
  const uploadFormData = new FormData()
  uploadFormData.append('files', file)
  uploadFormData.append('token', token)
  uploadTask.run(httpFileUpload(uploadFormData))
}

function onDelete(){
  modelValue.value = ''
  file_name.value = ''
}


watch(() => modelValue.value, () => {
  if(!modelValue.value) return;
  const chunks = modelValue.value.split('/');
  file_name.value = chunks[chunks.length -1];
}, {
  immediate: true
})


function onDownload(){
  const link = document.createElement('a');
  link.href = modelValue.value;
  link.download = file_name.value;
  link.click();

}
</script>


<template>
  <div class="flex">
    <div class="flex mr-[10px]">
      <p v-if="!modelValue">暂未上传文件</p>

      <a 
        style="overflow:hidden;white-space:nowrap; text-overflow: ellipsis; color: #409eff" 
        v-else 
        :src="modelValue" 
        target="_blank" 
        :underline="false"
        @click="onDownload"
      >{{ file_name }}</a>
    </div>
    <ElUpload :show-file-list="false" :before-upload="() => true"  accept=".pdf"  :http-request="handleUpload">
      <template #trigger>
        <ElButton v-if="!modelValue" type="primary" size="small">选择文件</ElButton>
        <ElButton v-else type="danger" size="small" @click="onDelete">删除文件</ElButton>
      </template>
    </ElUpload>
  </div>
</template>
