<template>
    <hc-sys class="h-full hc-uni-app-form-upload" :isNavBar="false">
        <uni-section class="mb-1" title="文件列表" sub-title="允许格式：jpg/png/pdf/excel/word， 文件大小 小于 60MB"/>
        <template v-if='fileListData.length > 0'>
            <view v-for="item in fileListData" class="hc-file-item">
                <view class="name" @click="fileTap(item)">{{item.name}}</view>
                <view class="action">
                    <uni-tag :inverted="true" text="删除" type="error" @click="delFileClick(item)"/>
                </view>
            </view>
        </template>

        <view class="action-bar-block"/>
        <view class="action-bar">
            <button type="primary" class="action-bar-btn" @click="selectImageTap">选择图片</button>
            <button type="primary" class="action-bar-btn" @click="selectFileTap">选择文件</button>
        </view>

        <hc-select-file ref="selectFileRef" @change="selectFileChange"/>
    </hc-sys>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {onLoad} from '@dcloudio/uni-app'
import {useAppStore} from "@/store";
import wbsApi from '~api/data-fill/wbs';
import {errorToast, openDocFile, successToast, toPdfPreview} from "@/utils/tools";
import {getArrValue, getObjValue} from "js-fast-way";
import {getTokenHeader} from "@/httpApi/request/header";
import {getUploadApi} from "@/httpApi/modules/upload";

const store = useAppStore()

//基础变量
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);
const pageNode = ref({});

//页面启动
onLoad((option) => {
    if (option.node) {
        const res = JSON.parse(decodeURIComponent(option.node));
        pageNode.value = {
            projectId: projectId.value,
            contractId: contractId.value,
            classify: res.classify,
            pkeyId: res.pkeyId,
            nodeId: res.treeId,
        }
    }
})

//渲染完成
onMounted(() => {
    getBussFileList()
})

//获取已上传的文件列表
const fileListData = ref([])
const getBussFileList = async () => {
    const { pkeyId } = pageNode.value
    if (!pkeyId) {
        errorToast('pkeyId为空');
        return
    }
    const { data } = await wbsApi.getBussFileList({
        pkeyid: pkeyId,
    })
    fileListData.value = getArrValue(data)
}

//选择图片上传
const selectImageTap = () => {
    uni.chooseImage({
        count: 3,
        sizeType: ['original'],
        success: (res)=> {
            setUploadFile(res.tempFilePaths)
        }
    });
}

//选择文件上传
const selectFileRef = ref(null)
const selectFileTap = () => {
    selectFileRef.value.selectFile()
}
//文件选择完成
const selectFileChange = ({file, path}) => {
    if(file) {
        uni.showLoading({title: '上传文件中...', mask: true})
        uni.uploadFile({
            url: getUploadApi() + 'blade-manager/exceltab/add-buss-file',
            name: 'file',
            file: file,
            filePath: path,
            formData: pageNode.value,
            header: getTokenHeader(),
            timeout: 300000,
            success: (res) => {
                uni.hideLoading()
                getBussFileList()
            },
            fail: () => {
                uni.hideLoading()
            }
        });
    }
}

//处理文件上传
const setUploadFile = async (arr) => {
    if (arr && arr.length > 0) {
        uni.showLoading({title: '上传文件中...', mask: true})
        for (let i = 0; i < arr.length; i++) {
            await uploadFileApi(arr[i])
            getBussFileList().then()
        }
        uni.hideLoading()
    }
}

//上传文件
const uploadFileApi = async (file) => {
    return new Promise((resolve) => {
        uni.uploadFile({
            url: getUploadApi() + 'blade-manager/exceltab/add-buss-file',
            name: 'file',
            filePath: file,
            formData: pageNode.value,
            header: getTokenHeader(),
            timeout: 300000,
            success: (res) => {
                resolve(getObjValue(res.data));
            },
            fail: () => {
                resolve({});
            }
        });
    })
}

//删除文件
const delFileClick = async(item) => {
    uni.showLoading({title: '删除文件中...', mask: true})
    const {error, code, msg} = await wbsApi.removeBussFile({
        ids: item.id
    })
    uni.hideLoading()
    if (!error && code === 200) {
        successToast('删除成功');
        getBussFileList().then()
    } else {
        errorToast('删除失败' + msg);
    }
}

//查看文件
const fileTap = async({url, extension}) => {
    const word = ['doc', 'docx', 'pdf', 'xls', 'xlsx']
    const img = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp']
    if(word.indexOf(extension) !== -1) {
        if(extension === 'pdf') {
            toPdfPreview(url).then()
        } else {
            openDocFile(url, extension)
        }
    } else if(img.indexOf(extension) !== -1) {
        uni.previewImage({
            current: 1,
			urls: [url]
		});
    } else {
        errorToast('当前' + extension + '文件格式暂不支持预览');
    }
}
</script>

<style scoped lang="scss">
page {
    height: 100%;
    background: #FAFBFE;
}
</style>

<style lang="scss">
@import "@/style/data-fill/uploadFile.scss";
</style>
