<template>
    <web-view
        ref="webViewRef"
        :update-title="false"
        :webview-styles="webViewStyle"
        :style="webViewStyle"
        :src="`/hybrid/html/select-file/index.html?accept=${accept}`"
        name="selectFileIframe"
        @message="handleMessage"
    />
</template>

<script setup>
import {ref, onMounted, getCurrentInstance} from "vue";
import {onUnload} from '@dcloudio/uni-app'

//初始变量
let wv;
const webViewStyle = ref({
    height: '1px',
    width: '1px',
    top: '300px',
})

const props = defineProps({
    accept: {
        type: String,
        default: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/pdf,.doc,.docx,application/msword'
    }
});

const webViewRef = ref(null)

//事件
const emit = defineEmits(['change'])

//渲染完成
onMounted(() => {
    // #ifdef H5
    window.addEventListener('message', handleMessage);
    // #endif
    initWebview()
})

//初始化webview
const initWebview = () => {
    // #ifdef APP-PLUS
    const instance = getCurrentInstance().proxy.$parent
    let currentWebview = instance.$getAppWebview()
    //如果是页面初始化调用时，需要延时一下
    setTimeout(() => {
        wv = currentWebview.children()[0]
        // #ifdef APP-PLUS
        //ios 禁用缓存，测试生效！！
        let cache1 = plus.ios.newObject('NSURLCache');
        let cache = plus.ios.invoke(cache1, 'sharedURLCache');
        plus.ios.invoke(cache, 'removeAllCachedResponses');
        plus.ios.invoke(cache, 'setDiskCapacity:', 0);
        plus.ios.invoke(cache, 'setMemoryCapacity:', 0);

        //安卓端缓存清理。
        plus.cache.clear();
        // #endif
    }, 1000);
    // #endif
}

const handleMessage = (event) => {
    let msg = {};
    // #ifdef H5
    if (event.data && event.data.data && event.data.data.arg) {
        msg = event.data.data.arg
    }
    // #endif
    // #ifdef APP-PLUS
    msg = event.detail.data[0]
    // #endif
    console.log('event.detail', msg)
    if (msg.source === 'file-web') {
        if (msg.type === "selectFileChange") {
            selectFileChange(msg.data)
        }
    }
}

onUnload(()=>{
    // #ifdef H5
    window.removeEventListener('message', handleMessage);
    // #endif
})

//选择文件
const selectFile = () => {
    // #ifdef H5
    window.frames["selectFileIframe"].postMessage({
        type: 'selectFile',
        source: 'file-app',
        data: {}
    });
    // #endif
    // #ifdef APP-PLUS
    wv.evalJS(`selectFile()`)
    // #endif
}

//文件选择完毕
const selectFileChange = (files) => {
    if (files && files.length > 0) {
        let file = files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        //监听文件读取结束后事件
        reader.onloadend = function (e) {
            //e.target.result就是最后的路径地址
            emit('change', {
                file: file,
                path: e.target.result
            })
        }
    }
}

//到处函数
defineExpose({
    selectFile
})
</script>

<style scoped lang="scss">
@import "./style.scss";
</style>
