<!-- 离线数据导入 -->
<template>
    <el-dialog v-model="dialogVisible" title="文件列表" width="70%" draggable>
        <!-- 上传文件列表 -->
        <div class="offline_data">
            <div class="offline_data_btn">
                <el-button type="primary" @click="handleUpload" size="small" :disabled="offLineFileList.length == 0">
                    开始上传
                </el-button>
                <el-button type="primary" @click="removeAllFile" size="small" :disabled="offLineFileList.length == 0">
                    清空文件
                </el-button>
            </div>
            <div class="offline_data_list">
                <!-- <el-upload
                    ref="upload"
                    accept=".zip,.rar,.7z"
                    action="#"
                    :auto-upload="false"
                    :on-change="handleFileChange"
                > -->
                <!-- <el-button slot="trigger" size="small" type="primary">选择ZIP文件</el-button> -->
                <el-button
                    :loading="loading"
                    style="margin-left: 10px"
                    size="small"
                    type="primary"
                    @click="submitUpload"
                >
                    上传离线数据
                </el-button>
                <!-- </el-upload> -->
                <div>
                    <el-table :data="offLineFileList" style="width: 100%" height="280" border stripe>
                        <el-table-column prop="name" label="文件名" align="center"></el-table-column>
                        <el-table-column prop="webkitRelativePath" label="文件地址" align="center"></el-table-column>
                        <el-table-column prop="status" label="状态" align="center" width="100">
                            <template #default="{ row }">
                                {{ row.status == 0 ? '等待上传' : '上传成功' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100" fixed="right" align="center">
                            <template #default="{ row }">
                                <!-- <el-button size="small" @click="previewFile(row)">预览</el-button> -->
                                <el-button size="small" type="danger" text @click="removeFile(row)">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <!-- <el-button type="primary" @click="close">提交</el-button> -->
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { ElMessageBox } from 'element-plus'
import { uploadOffLineDataFile } from '@/api/cs-device-boot/EquipmentDelivery.ts'
import { off } from 'process'
const dialogVisible = ref(false)
const selectedFile = ref(null)

const loading = ref(false)
const offLineFileList: any = ref([])
//上传zip
const handleFileChange = (file: any, fileList: any) => {
    console.log(fileList, 'fileList555333222')
    loading.value = true
    JSZip.loadAsync(file.raw)
        .then(zip => {
            console.log(file.raw, '++++++++++++hahhahahabvggeiwtei哈哈')
            offLineFileList.value = Object.keys(zip.files).map(name => ({ name }))
            // Object.keys(zip.files).map(entry => {
            //     console.log(entry, 'entryentryentryentryentry')
            //     // return zips.file(entry).then((blob: any) => {
            //         // 创建File对象
            //         return new File(['file'], entry)
            //     // })
            // })
            // console.log(zip.files, 'zip.fileszip.fileszip.fileszip.files')
        })
        .catch(error => {
            console.error('解压错误:', error)
            ElMessageBox.alert('解压错误: ' + error.message, '错误', { type: 'error' })
        })
        .finally(() => {
            loading.value = false
        })

    const reader = new FileReader()

    const zip = new JSZip()
    reader.onload = e => {
        console.log(e, '++++++++++++EEeeeEEEEEEEEE')
        // 加载压缩包内容
        zip.loadAsync(e.target.result).then(zip => {
            console.log(e.target.result, '??????????')
            // 获取压缩包内的文件
            const files = Object.values(offLineFileList.value)
                .map((entry: any) => {
                    if (!entry.dir && entry.name) {
                        // 将压缩包内的文件转换为Blob对象
                        return zip
                            .file(entry.name)
                            .async('blob')
                            .then(blob => {
                                // 创建File对象
                                return new File([blob], entry.name)
                            })
                    }
                })
                .filter(Boolean) // 过滤掉文件夹和未定义的文件

            Promise.all(files).then(allFiles => {
                // 这里你已经拿到了压缩包内所有文件的File对象数组
                console.log(allFiles)
            })
        })
    }

    // 读取文件内容
    reader.readAsArrayBuffer(file.raw)
}
const uploadChange = e => {
    const formData = new FormData()
    const file = e.target['files']
    for (let i = 0; i < file.length; i++) {
        formData.append('files', file[i])
        console.log(file[i])
        console.log(file[i].webkitRelativePath)
    }
    console.log(formData.getAll('files'), '++++++++++++++++')
}
const upload = ref()
const submitUpload = e => {
    // e.preventDefault()
    const input = document.createElement('input')
    input.type = 'file'
    input.setAttribute('allowdirs', 'true')
    input.setAttribute('directory', 'true')
    input.setAttribute('webkitdirectory', 'true')
    input.multiple = true
    document.querySelector('body').appendChild(input)
    // todo 这里增加了input标签，可以给它删掉
    input.click()
    input.onchange = function (e) {
        const formData = new FormData()

        // e.preventDefault()
        const file = e.target['files']
        for (let i = 0; i < file.length; i++) {
            formData.append('files', file[i])
            console.log(file[i])
            console.log(file[i].webkitRelativePath)
        }
        console.log(formData.getAll('files'), '++++++++++++++++')
        offLineFileList.value = formData.getAll('files')
        offLineFileList.value.map((item: any) => {
            item.status = 0
        })
    }
}
//清空文件
const removeAllFile = () => {
    offLineFileList.value = []
}
//移除文件
const removeFile = async (file: any) => {
    console.log(file, '移除文件指令')
    const delIndex = offLineFileList.value.findIndex((item: any) => {
        return item.webkitRelativePath == file.webkitRelativePath && item.name == file.name
    })
    console.log(delIndex, '((((((()))))))')
    offLineFileList.value.splice(delIndex, 1)
    return
    const zip = new JSZip()
    // 假设有一个zip文件的ArrayBuffer数据
    const zipBuffer = file

    // 加载ZIP文件
    // const jszip = await zip.loadAsync(zipBuffer)

    // 删除指定文件
    // delete jszip.files[file.name]

    // 生成新的ZIP文件
    const newZipContent = await zip.generateAsync({ type: 'arraybuffer', platform: 'DOS' })

    // 处理新生成的ZIP文件，例如下载或者其他操作
    // ...
    // 使用FileSaver库保存新的ZIP文件
    saveAs(newZipContent, '5555.zip')
}
//开始上传
const handleUpload = async () => {
    // return
    console.log(offLineFileList.value, '000000000')
    const subForm = new FormData()
    let obj = {
        devId: deviceId.value, //设备id
        lineId: lineId.value, //监测点id
        files: offLineFileList.value, //上传文件集
        paths: offLineFileList.value //上传文件路径集
    }
    subForm.append('devId', deviceId.value)
    subForm.append('lineId', lineId.value)
    // subForm.append('files', offLineFileList.value)
    let webkitRelativePathList: any = []
    offLineFileList.value.map((item: any, index: any) => {
        console.log(item)
        // obj.paths.push(item.webkitRelativePath)
        subForm.append(`files[${index}]`, item)
        // subForm.append(`paths[${index}]`, item.webkitRelativePath)
        webkitRelativePathList.push(item.webkitRelativePath)
    })
    console.log(subForm.getAll('files'), subForm)
    subForm.append('paths', webkitRelativePathList.join(','))
    // return;
    await uploadOffLineDataFile(subForm).then(res => {
        if (res.code == 'A0000') {
            console.log(res, '0999999999状态吗')
        }
    })
}
const deviceId: any = ref()
const lineId: any = ref()
const open = (devId: any, lineIds: any) => {
    deviceId.value = devId
    lineId.value = lineIds
    dialogVisible.value = true
}
const close = () => {
    dialogVisible.value = false
}
onMounted(() => {
    console.log()
})
defineExpose({ open })
</script>
<style lang="scss" scoped>
.offline_data {
    width: 100%;
    height: 400px;
    .offline_data_btn {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }
    .offline_data_list {
        width: 100%;
        height: 300px;
    }
}
</style>
