<template>
    <el-upload
        ref="uploadRef"
        :accept="accept" :action="action" :before-remove="delUploadData" :before-upload="beforeUpload"
        :data="uploadData"
        :disabled="isCanuploadVal" :file-list="fileListData" :headers="getHeader()" :on-error="uploadError"
        :on-exceed="uploadExceed" :on-preview="uploadPreview" :on-progress="uploadprogress"
        :on-remove="uploadRemove" :on-success="uploadSuccess" class="hc-upload-border" 
        :class="autoUpload === false ? 'hc-upload-border1' : 'hc-upload-border'"
        drag multiple
        :auto-upload="autoUpload"
        :on-change="handleFileChange"
    >
        <!-- 使用file插槽自定义文件列表 -->
        <!-- 使用draggable组件包裹文件列表 -->
        <draggable v-model="fileListData" @end="onDragEnd">
            <template #item="{ element }">
                <div class="file-item">
                    <HcIcon name="file" class="file-icon" />
                    <span class="file-name">{{ element.name }}</span>

                    <HcIcon name="close" class="float-right cursor-pointer text-red" @click.stop="handleRemove(element)" />
                </div>
            </template>
        </draggable>


        <template #trigger>
            <div v-loading="uploadDisabled" :element-loading-text="loadingText" class="hc-upload-loading h-full" @click.stop="beforesubmitUpload">
                <HcIcon name="backup" ui="text-5xl mt-4" />
                <div class="el-upload__text">拖动文件到这里 或 <em>点击这里选择文件</em></div>
            </div>
        </template>

        <template #tip>
            <div class="el-upload__tip" style="font-size: 14px;">
                {{ acceptTip }}
            </div>
        </template>
    </el-upload>
    <div class="mt-3" style="float: right;">
        <el-button v-if="!autoUpload" type="primary" @click="submitUpload">
            确认上传
        </el-button>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { getHeader } from 'hc-vue3-ui'
import wbsApi from '~api/data-fill/wbs'
import { isFileSize } from 'js-fast-way'
import { toPdfPage } from '~uti/btn-auth'
import draggable from 'vuedraggable'
const props = defineProps({
    fileList: {
        type: Array,
        default: () => ([]),
    },
    datas: {
        type: Object,
        default: () => ({}),
    },
    isCanupload:{
        type:Boolean,
        default:false,
    },
    action:{
        type:String,
        default:'#',
    },
    accept:{
        type:String,
        default:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/pdf,.doc,.docx,application/msword',
    },
    acceptTip:{
        type:String,
        default:'允许格式：pdf/excel/word， 文件大小 小于 60MB',
    },
    autoUpload:{
        type:Boolean,
        default:true,
    },
    typevalue:{
        type:[String, Number],
        default:'',
    }, //附件类型

})

//事件
const emit = defineEmits(['change', 'close'])
//变量
const uploadData = ref(props.datas)
const fileListData = ref(props.fileList)
const action = ref(props.action)
const accept = ref(props.accept)
const acceptTip = ref(props.acceptTip)
const uploadDisabled = ref(false)
const isCanuploadVal = ref(props.isCanupload)
const autoUpload = ref(props.autoUpload)
const typevalue = ref(props.typevalue)


//监听
watch(() => [
    props.fileList,
    props.datas,
    props.isCanupload,
    props.action,
    props.accept,
    props.acceptTip,
    props.autoUpload,
    props.typevalue,

], ([fileList, datas, isCanupload, Action, Accept, Tip, auto, type]) => {
    uploadData.value = datas
    fileListData.value = fileList
    isCanuploadVal.value = isCanupload
    action.value = Action
    accept.value = Accept
    acceptTip.value = Tip
    autoUpload.value = auto
    typevalue.value = type
})
watch(() => [
    props.typevalue,
    props.autoUpload,
], ([ type, auto]) => {
    typevalue.value = type
    autoUpload.value = auto
},
{ immediate: true },
)

// 在watch中添加对fileList的深度监听
watch(() => props.fileList, (newVal) => {
    console.log(newVal, 'newVal')
    
  fileListData.value = [...newVal] // 使用新数组保证响应性
}, { deep: true, immediate: true })
//渲染完成
onMounted(() => {
    beforeFileNum.value = 0
    finishFileNum.value = 0
    errorFileNum.value = 0
})

//上传前
const beforeFileNum = ref(0)
const beforeUpload = async (file) => {
    if (isFileSize(file?.size, 60)) {
        beforeFileNum.value++
        // 获取当前文件的索引
        const fileIndex = fileListData.value.findIndex(f => f.raw === file.raw)
        
        // 设置uploadData中的sort参数
        uploadData.value.sort = fileIndex + 1
        return true
    } else {
        window?.$message?.warning('文件大小, 不能过60M!')
        return false
    }
}


//超出限制时
const uploadExceed = () => {
    window?.$message?.warning('请上传 jpg/png/pdf/excel/word 的文件，文件大小 不超过60M')
}
const q = 1 // 假设q是固定偏移量，可以根据需要调整
// 新增的处理方法
// 文件变化处理
const handleFileChange = (file, fileList) => {
    console.log(fileList, 'fileList')
    
  fileListData.value = fileList.map((item, index) => ({
    ...item,
    sort: index + q, // 为每个文件添加sort字段
  }))
}
// 新增的拖拽结束事件处理函数
const onDragEnd = (event) => {
    console.log('拖拽结束', event)
    // 可以在这里处理拖拽结束后的逻辑，比如更新文件顺序等
}
// 手动删除文件
const handleRemove = (file) => {
  const index = fileListData.value.findIndex(f => f.uid === file.uid)
  if (index !== -1) {
    fileListData.value.splice(index, 1)
  }
}
//上传中
const loadingText = ref('上传中...')
const uploadprogress = () => {
    loadingText.value = '上传中...'
    uploadDisabled.value = true
}

//上传完成
const finishFileNum = ref(0)
const uploadSuccess = () => {
    finishFileNum.value++
    if (beforeFileNum.value === finishFileNum.value) {
        uploadDisabled.value = false
        emit('change', { type: 'success' })
    }
}

//上传失败
const errorFileNum = ref(0)
const uploadError = () => {
    errorFileNum.value++
    window?.$message?.error('上传失败')
    const num = finishFileNum.value + errorFileNum.value
    if (beforeFileNum.value === num) {
        uploadDisabled.value = false
        emit('change', { type: 'success' })
    }
}

//预览
const uploadPreview = ({ url }) => {
    emit('close')
    toPdfPage(url)
    /*if (url) {
        window.open(url, '_blank')
    }*/
}
const uploadRef = ref(null)
//删除文件
const delUploadData = async (res) => {
    const { id, status } = res
    console.log(res, 'res')
    
    if (accept.value === 'application/pdf') {
        if (!id || status === 'uploading') {
            uploadRef.value.abort()
            uploadDisabled.value = false
            return true
         } else {
            loadingText.value = '删除中...'
            uploadDisabled.value = true
            const { error, code, msg } = await wbsApi.delTabById({
                ids: id,
            })
            uploadDisabled.value = false
            if (!error && code === 200) {
                window?.$message?.success('删除成功')
                return true
            } else {
                window?.$message?.error(msg || '操作失败')
                return false
            }
        }

    } else {
        if (!id || status === 'uploading') {
            uploadRef.value.abort()
            uploadDisabled.value = false
            return true
        } else {
            loadingText.value = '删除中...'
            uploadDisabled.value = true
            const { error, code, msg } = await wbsApi.removeBussFile({
                ids: id,
            })
            uploadDisabled.value = false
            if (!error && code === 200) {
                window?.$message?.success('删除成功')
                return true
            } else {
                window?.$message?.error(msg || '操作失败')
                return false
            }
        }

    }
}

const uploadRemove = () => {


    if (fileListData.value.length <= 0) {
        emit('change', { type: 'del' })
    }
}

const beforesubmitUpload = () => {
    if (!typevalue.value && !autoUpload.value) {
        window.$message.warning('请先选择附件类型')
        return
    } else {
        const uploadInput = uploadRef.value.$el.querySelector('input[type=file]')
        if (uploadInput) {
            uploadInput.click()
        }
    }



}
const submitUpload = async ()=>{
  if (!typevalue.value && !autoUpload.value) {
    window.$message.warning('请先选择附件类型')
    return
  }

  // 准备文件数据（确保有sort参数）
  const filesWithSort = fileListData.value.map((file, index) => ({
    file: file.raw || file, // 源文件
    sort: index + q, // 排序值
  }))

    // 创建 FormData 对象
  const formData = new FormData()

  // 2. 单独添加每个文件（保持文件二进制数据）
  filesWithSort.forEach((item, index) => {
    formData.append(`file_${index}`, item.file, item.file.name)
  })

  // 添加其他必要的上传参数
  formData.append('classify', uploadData.value.classify)
  formData.append('nodeId', uploadData.value.nodeId)
  formData.append('type', uploadData.value.type)
    formData.append('contractId', uploadData.value.contractId)
          const { error, code, msg } = await wbsApi.addBussFileNode(formData)
            uploadDisabled.value = false
            if (!error && code === 200) {
                window?.$message?.success('删除成功')
                return true
            } else {
                window?.$message?.error(msg || '操作失败')
                return false
            }
//   uploadRef.value.submit()
}
</script>

<style lang="scss">
.hc-upload-border1 .el-upload-dragger{
    padding: 0px;
}
.hc-upload-border1 .el-upload-dragger .el-upload__text{
    padding: 40px;
}
</style>
