<template>
    <hc-sys id="app-sys" class="h-full hc-uni-app-table-form" :isNavBar="false">
        <view id="title-bar" class="title-bar z-24">
            <button type="primary" class="title-bar-btn" @click="editTypeClick">切换</button>
            <button type="primary" class="title-bar-btn" @click="toCopyClick">复制</button>
            <button type="primary" class="title-bar-btn" @click="toHideClick">隐藏</button>
            <button type="primary" class="title-bar-btn" @click="previewClick">预览</button>
            <button type="primary" class="title-bar-btn" @click="toFileUp">{{pageNode.tabFileType === 2?'已上传':'上传'}}</button>
        </view>
        <template v-if="webviewShow">
            <web-view :webview-styles="webViewStyle" :style="webViewStyle" :src="webSrc" name="exceliframe" @message="handleMessage"/>
        </template>
        <view id="action-bar" class="action-bar z-24">
            <button type="primary" class="action-bar-btn" @click="formSaveClick">保 存</button>
        </view>
    </hc-sys>
</template>

<script setup>
import {ref, getCurrentInstance} from "vue";
import {onLoad, onShow, onReady, onUnload} from '@dcloudio/uni-app'
import {errorToast, successToast, toPdfPreview, querySelect} from "@/utils/tools";
import {getStorage} from "@/utils/storage";
import {useAppStore} from "@/store";
import wbsApi from '~api/data-fill/wbs';
import {getFormApiUrl} from '@/config/envApi';

const store = useAppStore()
const instance = getCurrentInstance().proxy
let wv; //计划创建的webview

//初始变量
const contractInfo = ref(store.contractInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);
const pageNode = ref({});
const webViewStyle = ref({})
const webviewShow = ref(true)

onLoad((option) => {
    // #ifdef H5
    window.addEventListener('message', handleMessage);
    // #endif
    const user = encodeURIComponent(JSON.stringify(getStorage('login_user_info')))
    if (option.node) {
        uni.showLoading({title: '加载中...', mask: true});
        const res = JSON.parse(decodeURIComponent(option.node));
        uni.setNavigationBarTitle({
            title: res.title
        })
        pageNode.value = res
        webSrc.value = `${htmlsrc}&user=${user}&node=${option.node}`
    } else {
        errorToast('参数错误');
        setTimeout(() => {
            toBack()
        },1500)
    }
})

onShow(() => {
    webviewShow.value = true
})

//表格地址
const webSrc = ref('');
const envUrl = getFormApiUrl()
const htmlsrc = `${envUrl}/#/app/table-form?date=${new Date().getTime()}&source=app&type=data-fill`

//渲染完成
onReady(() => {
    setWebViewStyle()
})

const setWebViewStyle = async () => {
    // #ifdef APP-PLUS
    await initWebview()
    // #endif

    const appSys = await querySelect(instance, 'app-sys')
    const appSysHeight = appSys.height
    //顶部
    const titleBar = await querySelect(instance, 'title-bar')
    const titleBarHeight = titleBar?.height ?? 48
    // #ifdef H5
    webViewStyle.value.top = titleBarHeight + 'px'
    // #endif
    // #ifdef APP-PLUS
    const {statusBarHeight} = uni.getSystemInfoSync()
    webViewStyle.value.top = statusBarHeight + 45 + titleBarHeight
    // #endif
    //底部
    const actionBar = await querySelect(instance,'action-bar')
    const actionBarHeight = actionBar?.height ?? 80
    webViewStyle.value.height = (appSysHeight - titleBarHeight - actionBarHeight - 3) + 'px'
}

//初始化webview
const initWebview = async () => {
    return new Promise((resolve) => {
        let currentWebview = instance.$scope.$getAppWebview()
        //如果是页面初始化调用时，需要延时一下
        setTimeout(() => {
            wv = currentWebview.children()[0]
            wv.setStyle({scalable:true})
            resolve(true)
        }, 1000);
    })
}

const isFormRender = ref(false)
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
    if (msg.source === 'web') {
        if (msg.type === 'formRender') {
            uni.hideLoading();
            isFormRender.value = true
        }
        if (msg.type === 'back') {
            toBack() //收到通知，刷新列表去
        }
        //保存成功
        if (msg.type === 'saveSuccess') {
            uni.hideLoading();
            previewClick()
        }
        //消息提示
        if (msg.type === 'msg') {
            uni.hideLoading();
            const { title, icon } = msg.data
            uni.showToast({
                title: title,
                duration: 2000,
                icon: icon,
                mask: true
            });
        }
    }
}

const toBack = () => {
    webviewShow.value = false
    uni.navigateBack()
}

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

//切换显示模式
const editType = ref('form')
const editTypeClick = () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    const type = editType.value === 'form' ? 'table' : 'form'
    // #ifdef H5
    window.frames["exceliframe"].postMessage({
        type: 'editTypeClick',
        source: 'app',
        data: type
    }, envUrl);
    // #endif
    // #ifdef APP-PLUS
    wv.evalJS(`editTypeClick('${type}')`)
    // #endif
    editType.value = type
}

//复制本表
const toCopyClick = async () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    const { pkeyId, status } = pageNode.value
    if (!pkeyId) {
        errorToast('pkeyId为空');
        return
    } else if (status === '3') {
        errorToast('已上报的资料，不允许复制');
        return
    }
    uni.showLoading({title: '复制中...', mask: true});
    const { error, code, msg } = await wbsApi.copeBussTab({
        pkeyId: pkeyId,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('复制成功');
        setTimeout(() => {
            toBack()
        }, 1500)
    } else {
        errorToast('复制失败：' + msg);
    }
}

//隐藏表单
const toHideClick = async () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    const { pkeyId, status } = pageNode.value
    if (!pkeyId) {
        errorToast('pkeyId为空');
        return
    } else if (status === '3') {
        errorToast('已上报的资料，不允许隐藏示');
        return
    }
    uni.showLoading({title: '隐藏中...', mask: true});
    const { error, code, msg } = await wbsApi.showBussTab({
        pkeyId: pkeyId,
        status: 2,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('隐藏成功');
        setTimeout(() => {
            toBack()
        }, 1500)
    } else {
        errorToast('隐藏失败：' + msg);
    }
}

//预览表单
const previewClick = async () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    const { pkeyId, isBussShow, isTabPdf, pdfUrl } = pageNode.value
    if (!pkeyId) {
        errorToast('pkeyId为空');
        return
    } else if (isBussShow === 2 || isTabPdf === 1 || pdfUrl === '') {
        errorToast('当前状态无法预览');
        return
    }
    uni.showLoading({title: '获取PDF中...', mask: true});
    const { error, code, data, msg } = await wbsApi.getBussPdfInfo({
        pkeyId: pkeyId,
    })
    uni.hideLoading();
    if (!error && code === 200 && data) {
        toPdfPreview(data).then()
    } else {
        errorToast('获取失败：' + msg);
    }
}

//保存
const formSaveClick = () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    uni.showLoading({title: '保存中...', mask: true})
    // #ifdef H5
    window.frames["exceliframe"].postMessage({
        type: 'formSave',
        source: 'app',
        data: {}
    }, envUrl);
    // #endif
    // #ifdef APP-PLUS
    wv.evalJS(`formSave()`)
    // #endif
}

//上传
const toFileUp = () => {
    if (isFormRender.value === false) {
        errorToast('表单未渲染完成，请稍后再试');
        return
    }
    const { pkeyId, status } = pageNode.value
    if (!pkeyId) {
        errorToast('pkeyId为空');
        return
    } else if (status === '3') {
        errorToast('已上报的资料，不允许上传');
        return
    }
    uni.navigateTo({
        url: '/pages/data-fill/fileUp?node=' + encodeURIComponent(JSON.stringify(pageNode.value))
    });
}
</script>

<style lang="scss" scoped>
page {
    height: 100%;
    background: #FAFBFE;
}
.hc-uni-app-table-form {
    .title-bar {
        position: absolute;
        top: 0;
        display: flex;
        width: 100%;
        padding: 15rpx;
        background: #E8EEF2;
        overflow-x: auto;
        white-space: nowrap;
        z-index: 9999;
        .title-bar-btn {
            flex: 1;
            color: #6FCC9F;
            background-color: #EBF9F4;
            height: 58rpx;
            font-size: 25rpx;
            padding: 0;
            margin: 0;
            line-height: initial;
            border-radius: 6rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            &:after {
                display: none;
            }
        }
        .title-bar-btn + .title-bar-btn {
            margin-left: 16rpx;
        }
    }
    .action-bar {
        position: absolute;
        bottom: 0;
        width: 100%;
        display: flex;
        background: white;
        padding: 28rpx 28rpx calc(var(--window-bottom) + 34rpx);
        .action-bar-btn {
            flex: 1;
        }
    }
}
</style>
