<template>
    <hc-sys id="app-sys" class="h-full hc-ledger-table-form" navBarUi="white">
        <template #navBar>
            <hc-nav-back-bar :title="pageNode.title + '填报'">
                <zb-tooltip placement="bottom-end" ref="tooltipRef" v-if="currentPage > 0">
                    <view class="hc-page-bar">
                        <text class="i-ri-arrow-down-s-line icon"/>
                        <text class="text">第{{currentPage}}页</text>
                    </view>
                    <template #content>
                        <template v-for="item in pageTotal" :key="item">
                            <view class="more-bar-item" @click="pageClick(item)">第{{item}}页</view>
                        </template>
                    </template>
                </zb-tooltip>
            </hc-nav-back-bar>
        </template>
        <view id="title-bar" class="title-bar">
            <button type="primary" class="title-bar-btn" @click="editTypeClick">切换表单</button>
            <button type="primary" class="title-bar-btn" @click="linkTabClick">+ 关联工序</button>
            <button type="primary" class="title-bar-btn" @click="delCurrentPage" v-if="currentPage > 1">删除当前页</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">
            <view class="text-bar">
                <view class="left" @click="copyTableFormClick">复制当前表格及内容</view>
                <view class="right" @click="copyTimeLogModal">复制任意时间表格及内容</view>
            </view>
            <uni-row :gutter="20">
                <uni-col :span="6">
                    <button class="cu-btn round c1" @click="addFormClick">新 增</button>
                </uni-col>
                <uni-col :span="6">
                    <button class="cu-btn round c2" @click="previewTap">预 览</button>
                </uni-col>
                <uni-col :span="6">
                    <button class="cu-btn round c3" @click="reportModalClick">上 报</button>
                </uni-col>
                <uni-col :span="6">
                    <button class="cu-btn round c4" @click="formSaveClick">保 存</button>
                </uni-col>
            </uni-row>
        </view>
    </hc-sys>
</template>

<script setup>
import {ref, getCurrentInstance} from "vue";
import {onLoad, onReady, onShow, onUnload} from '@dcloudio/uni-app'
import {errorToast, toPdfPreview, querySelect} from "@/utils/tools";
import {getObjValue, isNullES} from "js-fast-way";
import {getStorage} from "@/utils/storage";
import mainApi from '~api/ledger/index';
import {getFormApiUrl} from '@/config/envApi';

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

//初始变量
const pageNode = ref({});
const webViewStyle = ref({})
const webviewShow = ref(true)
const tooltipRef = ref(null)

onLoad((option) => {
    // #ifdef H5
    window.addEventListener('message', handleMessage);
    // #endif
    const user = encodeURIComponent(JSON.stringify(getStorage('login_user_info')))
    if (option.node) {
        const res = JSON.parse(decodeURIComponent(option.node));
        uni.setNavigationBarTitle({title: res.title + '填报'})
        pageNode.value = res
        webSrc.value = `${htmlsrc}&user=${user}&node=${option.node}`
        checkTheLogTaskStatus()
    }
})

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

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

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

//获取状态
const taskStatus = ref(1)
const checkTheLogTaskStatus = async () => {
    const {projectId, contractId, pkeyId, date} = pageNode.value
    const { error, code, data } = await mainApi.checkTheLogTaskStatus({
        projectId: projectId,
        contractId: contractId,
        nodePrimaryKeyId: pkeyId,
        recordTime: date,
    })
    //处理数据
    const res = isNullES(data) ? '' : data || ''
    if (!error && code === 200 && res) {
        //1和2的时候所有按钮皆可操作，废除 除外
        //3和4时, 除了预览和废除 都不行
        taskStatus.value = data
    } else {
        taskStatus.value = 1
    }
}

const setWebViewStyle = async () => {
    // #ifdef APP-PLUS
    await initWebview()
    // #endif
    const {height: appHeight} = await querySelect(instance, 'app-sys')
    const {height: navHeight} = await querySelect(instance,'hc-nav-bar')
    const {height: titleHeight} = await querySelect(instance,'title-bar')
    webViewStyle.value.top = (navHeight + titleHeight) + 'px'
    //底部
    const {height: actionHeight} = await querySelect(instance,'action-bar')
    webViewStyle.value.height = (appHeight - navHeight - titleHeight - actionHeight - 1) + '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);
    })
}

//接收webview消息
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') {
        console.log('收到web消息', msg)
        setMsgData(msg)
    }
}

// 处理接收到的消息
const isFormRender = ref(false)
const setMsgData = ({type, data}) => {
//表格数量
    if (type === 'formRender') {
        isFormRender.value = true
    }
    //表格数量
    if (type === 'formLength') {
        pageTotal.value = Number(data)
    }
    //当前表格
    if (type === 'formIndex') {
        const {id, page} = getObjValue(data)
        itemFormId.value = id       //当前表格id
        currentPage.value = page    //当前页码
    }
    //pdf预览
    if (type === 'formPdfUrl') {
        previewPdf(data)
    }
    //保存结果
    if (type === 'saveRes') {
        uni.hideLoading();
        saveResData(data)
    }
}

//页码
const pageTotal = ref(0)
const currentPage = ref(0)
const itemFormId = ref('')

//切换页码
const pageClick = (item) => {
    tooltipRef.value?.close()
    if (item !== currentPage) {
        postMsg({
            type: 'pageTap',
            data: item -1,
            fun: `pageTap('${item -1}')`
        })
    }
}

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

//切换显示模式
const editType = ref('form')
const editTypeClick = () => {
    const type = editType.value === 'form' ? 'table' : 'form'
    postMsg({
        type: 'editTypeClick',
        data: type,
        fun: `editTypeClick('${type}')`
    })
    editType.value = type
}

//关联工序
const linkTabClick = () => {
    uni.navigateTo({
        url: '/pages/ledger/linkTab?id=' + itemFormId.value,
        events: {
            finish: (data) => {
                linkTabFinish(data)
            }
        }
    });
}

//通知更新关联工序数据
const linkTabFinish = (data) => {
    const ids = data.length > 0 ? JSON.stringify(data) : ''
    postMsg({
        type: 'linkIds',
        data: ids,
        fun: `linkIdsTap('${ids}')`
    })
}

//新增表格
const addFormClick = () => {
    postMsg({
        type: 'addForm',
        fun: `addFormTap()`
    })
}

//复制当前表格及内容
const copyTableFormClick = () => {
    if (!isFormRender.value || taskStatus.value === 3 || taskStatus.value === 4) {
        errorToast('当前状态不可操作');
        return
    }
    postMsg({
        type: 'copyFormData',
        fun: `copyFormData()`
    })
}

//复制任意时间
const copyTimeLogModal = () => {
    if (!isFormRender.value || taskStatus.value === 3 || taskStatus.value === 4) {
        errorToast('当前状态不可操作');
        return
    }
    uni.navigateTo({
        url: '/pages/ledger/copyTime?node=' + encodeURIComponent(JSON.stringify(pageNode.value)),
        events: {
            finish: () => {
                flushedPage()
            }
        }
    })
}

//删除当前页
const delCurrentPage = () => {
    postMsg({
        type: 'delForm',
        fun: `delFormTap()`
    })
}

//预览表单PDF
const previewTap = () => {
    if (!isFormRender.value || taskStatus.value === 1) {
        errorToast('当前状态不可操作');
        return
    }
    uni.showLoading({title: '获取数据中...', mask: true});
    postMsg({
        type: 'getPdfUrl',
        fun: `getPdfUrl()`
    })
}

//预览表单
const previewPdf = (data) => {
    uni.hideLoading();
    if (!data) {
        errorToast('暂无PDF，无法预览');
        return
    }
    //预览文件
    toPdfPreview(data)
}

//保存
const formSaveClick = () => {
    if (!isFormRender.value || taskStatus.value === 3 || taskStatus.value === 4) {
        errorToast('当前状态不可操作');
        return
    }
    uni.showLoading({title: '保存中...', mask: true})
    postMsg({
        type: 'formSave',
        fun: `formSave()`
    })
}

//保存结果
const saveResData = (data) => {
    if (data === 'success') {
        uni.showLoading({title: '获取预览中...', mask: true})
        //flushedPage()
    }
}

//上报
const reportModalClick = () => {
    const status = taskStatus.value
    if (!isFormRender.value || status === 1 || status === 3 || status === 4) {
        errorToast('当前状态不可操作');
        return
    }
    const {projectId, contractId, pkeyId, date, taskName} = pageNode.value
    //路由跳转
    uni.navigateTo({
        url: '/pages/report/report',
        events:{
            finish: () => {
                flushedPage()
            }
        },
        success:(res) => {
            res.eventChannel.emit('reportProps', {
                type: "log",
                typeData: pkeyId,
                projectId: projectId,
                contractId: contractId,
                taskName: taskName,
                url: 'contractLog/startTaskTheLog',
                addition: {
                    nodePrimaryKeyId: pkeyId,
                    recordTime: date,
                },
            })
        }
    });
}


//发送消息
const postMsg = ({type, data, fun}) => {
    // #ifdef H5
    window.frames["exceliframe"].postMessage({
        type: type,
        source: 'app',
        data: data ?? {}
    }, envUrl);
    // #endif
    // #ifdef APP-PLUS
    if (fun) wv.evalJS(fun)
    // #endif
}

//刷新页面
const flushedPage = () => {
    webviewShow.value = false
    checkTheLogTaskStatus()
    setTimeout(() => {
        webviewShow.value = true
    }, 500);
}

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

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

<style lang="scss">
@import "@/style/ledger/edit-table.scss";
</style>
