<template>
    <div class="hc-uni-app-table-form" :class="[editType]">
        <hc-table-form ref="tableFormRef" :form="tableFormInfo" :html="excelHtml" :scroll="false" :pkey="appItem.pkeyId" @render="tableFormRender" />
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import wbsApi from '~api/data-fill/wbs'
import { useAppStore } from '~src/store'
import { getObjVal, getObjValue, isString } from 'js-fast-way'

const props = defineProps({
    option: {
        type: Object,
        default: () => ({}),
    },
})

//初始变量
const useAppState = useAppStore()

//基础变量
const appItem = ref(props.option)
const tableFormRef = ref(null)
const editType = ref('form')

//深度监听
watch(() => [
    props.option,
], ([option]) => {
    appItem.value = getObjValue(option)
    getInitData()
}, { deep: true })

//渲染完成
onMounted(() => {
    //设置主题
    useAppState.setTheme('light')
    useAppState.setThemeVal('light')
    if (getObjVal(appItem.value)) {
        getInitData()
    }
    //接受app传递过来的消息
    window.addEventListener('message', (event) => {
        const { source, data, type } = event.data
        if (source === 'app') {
            if (type === 'editTypeClick') {
                editTypeClick(data)
            } else if (type === 'formSave') {
                toSaveClick()
            }
        }
    })
})

const getInitData = () => {
    //获取相关数据
    getWbsContractById()
    getDataApi()
    editTypeClick('form')
}

const getDataApi = async () => {
    if (appItem.value.pkeyId) {
        await getTableFormInfo()
        await getExcelHtml()
    }
}

//获取详情
const wbsInfo = ref({})
const getWbsContractById = async () => {
    const { data } = await wbsApi.getWbsContractById({
        pKeyId: appItem.value.pkeyId,
    })
    wbsInfo.value = getObjValue(data)
}

//获取表单初始数据
const getFormDataInit = (data = {}) => {
    const { projectId, contractId, classify, treeId, pkeyId } = appItem.value
    return {
        projectId: projectId,
        contractId: contractId,
        classify: classify,
        pkeyId: pkeyId,
        nodeId: treeId,
        isRenderForm: false,
        ...data,
    }
}

//获取已填写的数据
const tableFormInfo = ref({})
const getTableFormInfo = async () => {
    const { error, code, data } = await wbsApi.getBussDataInfo({
        pkeyId: appItem.value.pkeyId,
    }, false)
    const resData = getObjVal(data)
    if (!error && code === 200 && resData) {
        tableFormInfo.value = getFormDataInit(resData)
    } else {
        tableFormInfo.value = getFormDataInit()
    }
}

//获取模板标签数据
const excelHtml = ref('')
const getExcelHtml = async () => {
    const { error, code, data } = await wbsApi.getExcelHtml({
        pkeyId: appItem.value.pkeyId,
    }, false)
    const resData = isString(data) ? data || '' : ''
    if (!error && code === 200 && resData) {
        excelHtml.value = resData
    } else {
        excelHtml.value = ''
        tableFormInfo.value.isRenderForm = false
        postMsg('暂无表单', 'error')
    }
}

//渲染完成
const tableFormRender = (form) => {
    tableFormInfo.value = form
    window?.postMessage({
        type: 'formRender',
        source: 'web',
        data: {},
    })
}


//切换显示模式
const tableWidth = ref(0)
const editTypeClick = (type) => {
    let metaEle = document.getElementsByName('viewport')[0]
    if (type === 'form') {
        metaEle.setAttribute('content', 'width=device-width,user-scalable=no,initial-scale=1.0')
        tableWidth.value = 0
    } else if (type === 'table') {
        metaEle.setAttribute('content', 'width=1080, initial-scale=0.5,user-scalable=yes')
        tableWidth.value = document.body.offsetWidth
    }
    editType.value = type
}

//保存表单
const toSaveClick = async () => {
    const { pkeyId, status } = appItem.value
    if (!pkeyId) {
        postMsg('pkeyId为空', 'error')
        return
    } else if (status === '3') {
        postMsg('已上报的资料，不允许保存。', 'error')
        return
    }
    const formData = tableFormRef.value?.getFormData()
    const { error, code, msg } = await wbsApi.saveExcelBussData(formData, false)
    if (!error && code === 200) {
        postForm('saveSuccess')
        postMsg('保存成功', 'success')
    } else {
        window?.$message?.error(msg)
    }
}

//发送消息
const postForm = (name, data = {}) => {
    window?.postMessage({
        type: name,
        source: 'web',
        data: data,
    })
}

//弹出提示
const postMsg = (title, icon) => {
    window?.postMessage({
        type: 'msg',
        source: 'web',
        data: {
            title: title,
            icon: icon,
        },
    })
}
</script>

<style lang="scss">
@import "~src/styles/uni-app/table-form.scss";
</style>
