<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="ActiveKey" accordion @change="CollapseChange">
            <el-collapse-item v-for="(item, index) in listDatas" :id="`item-${index}-${item?.pKeyId}`" :key="item?.pKeyId" :disabled="item.isBussShow === 2" :name="`item-${index}-${item?.pKeyId}`">
                <template #title>
                    <div class="hc-collapse-item-header">
                        <!-- div class="real-fill-rate">
                            <div class="tag" :class="item.realFillRate >= 80 ? 'yes' : ''">已填{{ item.realFillRate ?? 0 }}%</div>
                            <HcTooltip keys="wbs_preview_table">
                                <el-link v-if="item.isBussShow === 2 || item.isTabPdf === 1" type="primary" disabled>本 表 预 览</el-link>
                                <el-link v-else type="primary" @click.stop="previewClick(item)">本 表 预 览</el-link>
                            </HcTooltip>
                        </div -->
                        <div class="text-lg truncate item-title">{{ item.nodeName }}</div>
                        <div class="hc-extra-text-box">
                            <HcTooltip v-if="item.isCopyTab === 1" keys="wbs_del_table">
                                <el-link type="danger" :disabled="item.isBussShow === 2 || tableFormDelLoading" @click.stop="delClick(item, index)">删除本表</el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_copy_table">
                                <el-link type="primary" :disabled="item.isBussShow === 2 || copyClickLoading" @click.stop="copyClick(item, index)">复制本表</el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_preview_table">
                                <el-link v-if="item.isBussShow === 2 || item.isTabPdf === 1" type="primary" disabled>预览</el-link>
                                <el-link v-else type="primary" @click.stop="previewClick(item)">预览</el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_upload_table">
                                <el-link :disabled="item.isBussShow === 2" :type="item.tabFileType === 2 ? 'success' : 'primary'" @click.stop="uploadClick(item, index)">
                                    <template v-if="item.tabFileType === 2">已上传</template>
                                    <template v-else>附件上传</template>
                                </el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_hide_table">
                                <el-link type="primary" @click.stop="hideClick(item, index)">
                                    <template v-if="item.isBussShow === 1">隐藏本表</template>
                                    <template v-else>显示本表</template>
                                </el-link>
                            </HcTooltip>
                        </div>
                    </div>
                </template>
                <div style="height: calc(100vh - 222px);" class="data-fill-list-item-content">
                    <div v-if="item?.isWindow" class="data-fill-table-form-box is-window">
                        <div class="hc-window-tip">
                            <div class="table-form-no">
                                <img :src="NoDataSvg" alt="">
                                <div class="desc">当前表单处于窗口模式，关闭相关窗口后恢复</div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="data-fill-table-form-box">
                        <TableFormItem
                            v-if="item.isTableRender"
                            :ref="(el) => setItemRefs(el, item)"
                            :classify="classifys"
                            :datas="changeFormDatas(item?.pKeyId, 'collapse')"
                            :kid="item?.pKeyId"
                            :node-name="item.nodeName"
                            :pid="`table-form-${item?.pKeyId}`"
                            :tid="treeId"
                            @excelBodyTap="excelTableFormClick($event)"
                            @render="tableFormRender($event, item, index)"
                            @rightTap="tableFormRightTap($event, index)"
                        />
                        <el-tooltip :content="item.isWindow ? '关闭窗口并恢复' : '当前表单窗口化'" :hide-after="0" placement="top">
                            <div class="form-window-icon" @click.stop="windowClick(item, index)">
                                <template v-if="item.isWindow">
                                    <HcIcon name="fullscreen-exit" />
                                </template>
                                <template v-else>
                                    <HcIcon name="fullscreen" />
                                </template>
                            </div>
                        </el-tooltip>
                    </div>
                    <div class="data-fill-table-action">
                        <div class="text-orange tip-action" @click="actionTipModal = true">
                            <HcIcon fill name="information" ui="text-2xl" />
                        </div>
                        <div class="link-action">
                            <HcTooltip keys="wbs_download_table">
                                <el-link type="primary">下载导入模板</el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_import_table">
                                <el-link type="primary">导入表格数据</el-link>
                            </HcTooltip>
                        </div>
                        <div class="btn-action">
                            <HcTooltip keys="wbs_save_table">
                                <el-button
                                    :disabled="!item?.isTableForm" :loading="tableFormSaveLoading"
                                    color="#3794FF" size="small" style="color: white"
                                    @click="tableFormSaveClick(item)"
                                >
                                    仅保存本表数据
                                </el-button>
                            </HcTooltip>
                        </div>
                    </div>
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>

    <!-- 右键菜单 -->
    <HcContextMenu ref="contextMenuRef" :datas="tableFormMenu" @item-click="handleMenuSelect" />

    <!-- 查看表单 -->
    <template v-for="(item, index) in DragModalTableForm" :key="index">
        <HcDragModal
            :close-icon-arr="closeIconArr" :eid="item.pKeyId" :height="DragModalHeight" :is-show="item.isShow"
            :loading="item.loading" :loading-text="item.loadingText" :title="item.title"
            is-sort-top
            @close="TableFormClose(item, index)" @closeIconTap="closeIconTap($event, item, index)"
        >
            <HcDragNode :more-menu="dragNodeMoreMenu" @menuTap="dragNodeMoreMenuTap($event, item)">
                <TableFormItem
                    :ref="(el) => setItemRefs(el, item)"
                    :classify="item.classify"
                    :datas="changeFormDatas(item?.pKeyId, 'window')"
                    :height="item.height"
                    :kid="item.pKeyId"
                    :node-name="item.title"
                    :pid="`table-form-${item?.pKeyId}`"
                    :scroll="false"
                    :tid="item.treeId"
                    :width="item.width"
                    @excelBodyTap="excelTableFormClick($event)"
                    @render="tableFormRender($event, item.item, item.index)"
                    @rightTap="tableFormRightTap($event, item.index)"
                />
            </HcDragNode>
        </HcDragModal>
    </template>

    <!-- 操作提示 -->
    <hc-new-dialog v-model="actionTipModal" :footer="false" title="操作提示" widths="38rem" @close="actionTipModalClose">
        <div class="data-fill-table-tip-box">
            <div class="text-gray-400 tip-item">1、灰色框代表可通过系统识别计算，公式自动引用，可通过公式计算少量数据，(表头数据及简单)，也可只填写白色框数据</div>
            <div class="text-gray-400 tip-item">
                2、先点击一下表单任一区域，再键盘按住 ⌘/ctrl +
                点击，选择输入框，变为绿色边框，选中成功。选择完毕后，键盘按 ⌘/ctrl + c 复制所选中的数据，
                再其它表内，或同一张表内，再次按住 ⌘/ctrl + 点击，选择输入框。键盘按 ⌘/ctrl + v
                依次粘贴所选的数据。（目前仅支持输入框和文本框的操作）
            </div>
            <div class="text-orange-500 tip-item">3、完善资料填写后记得一定要保存哦</div>
        </div>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '~src/store'
import HTableForm from '~src/plugins/HTableForm'
import wbsApi from '~api/data-fill/wbs'
import TableFormItem from './table-form.vue'
import NoDataSvg from '~src/assets/view/no-data.svg'
import { arrIndex, deepClone, getArrValue, getObjVal, getObjValue, isNullES } from 'js-fast-way'
import dataApi from '~api/tentative/detect/test'

//参数
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
    baseData: {
        type: Object,
        default: () => ({}),
    },
    status: {
        type: [String, Number],
        default: '',
    },
    deviceUseIds: {
        type: String,
        default: () => (''),
    },
    authBtnTabKey: {
        type: String,
        default: () => (''),
    },
    checkTableId: {
        type: String,
        default: () => (''),
    },
    tabTypeKey: {
        type: String,
        default: () => (''),
    },
    nodeIdvalue: {
        type: String,
        default: () => (''),
    },
    alllistData: {
        type: Array,
        default: () => ([]),
    },
    nodeStatus: {
        type: String,
        default: () => (''),
    },
})

//事件
const emit = defineEmits(['renew', 'offsetTop', 'updeviceUseIds', 'upcheckTableId', 'changesdate', 'chageorinData', 'changeIscanclick', 'changesingSaveId'])

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

//路由参数
const routerQuery = useRoutes?.query
const isaddType = routerQuery?.isaddType || false

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)

const listDatas = ref(props.datas)
const isStatus = ref(props.status)
const baseData = ref(props.baseData)
const authBtnTabKeyType = ref(props.authBtnTabKey)//所属方
const tabTypeKeyInfo = ref(props.tabTypeKey)
const nodeIdvaluedata = ref(props.nodeIdvalue)
const alllistDataval = ref(props.alllistData)
const NodeStatusval = ref(props.nodeStatus)

//表单变量
const formDataList = ref([])
const formKeyIds = ref('')
const formparentId = ref('')

//处理ref
const itemRefs = ref([])
const setItemRefs = (el, { pKeyId }) => {
    if (el) {
        let index = arrIndex(itemRefs.value, 'pKeyId', pKeyId)
        if (index !== -1) {
            itemRefs.value[index].ref = el
        } else {
            itemRefs.value.push({
                pKeyId: pKeyId,
                ref: el,
            })
        }
    }
}

//处理表单的ref
const setSpliceItemRefs = async ({ pKeyId }) => {
    const refs = itemRefs.value
    let index = arrIndex(refs, 'pKeyId', pKeyId)
    if (index !== -1) {
        refs.splice(index, 1)
        itemRefs.value = refs
    }
}

const closeIconArr = [{ key: 'reduction', icon: 'picture-in-picture-2', name: '还原到面板内，并自动展开面板' }]

//深度监听数据
watch(() => [
    props.datas,
], ([datas]) => {
    setFormDataNum(datas)
}, { deep: true })

//监听变量值
watch(() => [
    props.status,
    props.baseData,
    props.nodeIdvalue,
    props.tabTypeKey,
    props.alllistData,
    props.nodeStatus,
], ([val, base, NodeIdvalue, TabTypeKey, AlllistData, NodeStatus]) => {
    //1 未填报，2待上报，3已上报
    isStatus.value = val
    baseData.value = base
    nodeIdvaluedata.value = NodeIdvalue
    tabTypeKeyInfo.value = TabTypeKey
    alllistDataval.value = AlllistData
    NodeStatusval.value = NodeStatus
})

//渲染完成
onMounted(() => {
    setFormDataNum(props.datas)
    const { offsetHeight } = document.body
    DragModalHeight.value = offsetHeight - 200
    setMountOnEventKey()
})

//处理变动的数据
const changeFormData = ref({
    window: [],
    collapse: [],
})
const changeFormDatas = (pKeyId, type) => {
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pKeyId', pKeyId)
    if (index !== -1) {
        return changeData[index]
    } else {
        return {}
    }
}

//设置变动的数据
const setChangeFormDatas = async (pKeyId, type) => {
    const refs = await getFormRef(pKeyId)
    const formData = refs?.getFormData()
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pKeyId', pKeyId)
    if (index !== -1) {
        changeData[index] = formData
    } else {
        changeData.push(formData)
    }
    changeFormData.value[type] = changeData
}

//展开事件
const ActiveKey = ref('')
const CollapseChange = (name) => {
    ActiveKey.value = name
    let index = getCollapseItemIndex(name)
    if (index > -1) {
        getOffsetTop(name)
        const item = listDatas.value[index]
        formKeyIds.value = setToString(item.pKeyId)
        formparentId.value = setToString(item.parentId)
        nextTick(() => {
            if (!item.isTableRender) {
                item.isTableRender = true
            }
        })
    } else {
        getOffsetTop()
        formKeyIds.value = ''
        formparentId.value = ''
    }
}

//初始设置
const setFormDataNum = (datas) => {
    itemRefs.value = []
    ActiveKey.value = ''
    let newArr = []
    for (let i = 0; i < datas.length; i++) {
        newArr.push({ isCollapseLoad: false })
    }
    formDataList.value = newArr
    listDatas.value = deepClone(datas)
}

//渲染完成
const tableFormRender = (form, item, index) => {
    console.log(form)
    formDataList.value[index] = form
    formDataList.value[index].isCollapseLoad = form.isRenderForm
    item.isTableForm = form.isRenderForm
}


//菜单数据
const contextMenuRef = ref(null)
const tableFormMenu = ref([
    { label: '容器参数', key: 'vessel' },
    { label: '引用设备仪器', key: 'device' },
    { label: '插入特殊字符', key: 'special' },
])

//鼠标右键事件
const tableFormItemNode = ref({}) //临时信息
const tableFormRightTap = ({ event, KeyName, startPos, endPos, pKeyId }, index) => {
    //存储临时信息
    tableFormItemNode.value = { KeyName, index, startPos, endPos, pKeyId }
    contextMenuRef.value?.showMenu(event, false) //展开菜单
}

//鼠标右键菜单被点击
const handleMenuSelect = async ({ key }) => {
    console.log(key)
}


//窗口化
const DragModalTableForm = ref([])
const DragModalHeight = ref(600)
const windowClick = async (item, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    let index = arrIndex(list, 'pKeyId', item.pKeyId)
    if (!item.isWindow) {
        const formSize = getTableFormSize(item?.pKeyId)
        const newTableForm = {
            ...setInitDragModalTableForm(item, indexs),
            ...formSize,
        }
        await setChangeFormDatas(item?.pKeyId, 'window')
        item.isWindow = true
        //处理表单的ref
        await setSpliceItemRefs(item)
        //弹窗表单的排序
        if (index === -1) {
            list.push(newTableForm)
        } else if (index !== list.length - 1) {
            //检查是否在最上层，不在则置顶，可以解决多次点击时，频繁更改全局状态的问题
            list.splice(index, 1)
            list.push(newTableForm)
        }
        DragModalTableForm.value = list
        ActiveKey.value = ''
    } else {
        await setChangeFormDatas(item?.pKeyId, 'collapse')
        //处理表单的ref
        await setSpliceItemRefs(item)
        if (index !== -1) {
            list.splice(index, 1)
            DragModalTableForm.value = list
        }
        item.isWindow = false
    }
}

//初始拖动表单的内容
const setInitDragModalTableForm = (item, index) => {
    return {
        projectId: projectId.value,
        contractId: contractId.value,
        /*wbsTempId: wbsTemp_id.value,
        tenantId: tenant_id.value,
        wbsType: wbs_type.value,
        classify: classifys.value,
        treeId: treeId.value,*/
        pKeyId: item.pKeyId,
        height: '100%',
        width: '100%',
        title: item.nodeName,
        isShow: true,
        index: index,
        item: item,
    }
}

//关闭窗口
const TableFormClose = async ({ pKeyId, index }, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    //取表单的数据
    await setChangeFormDatas(pKeyId, 'collapse')
    //关闭窗口
    list.splice(indexs, 1)
    DragModalTableForm.value = list
    listDatas.value[index].isWindow = false
}

const dragNodeMoreMenu = [
    { key: 'save', icon: 'save-2', name: '保存' },
    { key: 'preview', icon: 'eye', name: '预览' },
]

//还原窗口
const closeIconTap = async (event, item, indexs) => {
    const { index, pKeyId } = item
    let KeyId = `item-${index}-${pKeyId}`
    await TableFormClose(item, indexs)
    ActiveKey.value = KeyId
}

//菜单被点击
const dragNodeMoreMenuTap = ({ key }, items) => {
    const { item } = items
    if (key === 'save') {
        if (item?.isTableForm) {
            tableFormSaveClick(item, items)
        } else {
            window.$message.warning('此表单暂无数据和文件')
        }
    } else if (key === 'preview') {
        if (item['isBussShow'] === 2 || item['isTabPdf'] === 1 || item['pdfUrl'] === '' || item['pdfUrl'] === null) {
            window.$message.warning('此表单暂无可预览文件')
        } else {
            previewClick(item, items)
        }
    }
}

//删除本表
const tableFormDelLoading = ref(false)
const delClick = async ({ pKeyId }, index) => {
    if (pKeyId) {
        if (isStatus.value !== 3) {
            tableFormDelLoading.value = true
            const { error, code } = await wbsApi.removeBussTabInfo({
                pKeyId: pKeyId,
                classify: classifys.value,
            })
            tableFormDelLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success('操作成功')
                //判断是否存在窗口，如果存在，就删除窗口
                delWindowRefs(pKeyId)
                // renewData()
                listDatas.value.splice(index, 1)
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许删除')
        }
    } else {
        window?.$message?.warning('pKeyId为空')
    }
}

//复制表
const copyClickLoading = ref(false)
const copyClick = () => {

}


//隐藏本表
const tableFormHideLoading = ref(false)
const hideClick = async ({ pKeyId, isBussShow }, index) => {
    if (pKeyId) {
        if (isStatus.value !== 3) {
            tableFormHideLoading.value = true
            const bussShow = isBussShow === 2 ? 1 : 2 //状态(1显示 2隐藏)
            const { error, code } = await wbsApi.showBussTab({
                pKeyId: pKeyId,
                status: bussShow,
                classify: classifys.value,
                nodeId: treeId.value,
            })
            tableFormHideLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success('操作成功')
                if (isBussShow === 2) {
                    listDatas.value[index]. isBussShow = 1
                } else {
                    listDatas.value[index]. isBussShow = 2
                }
                if (bussShow === 2) {
                    //判断是否存在窗口，如果存在，就删除窗口
                    delWindowRefs(pKeyId)
                }
                // renewData()
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许隐藏')
        }
    } else {
        window?.$message?.warning('pKeyId为空')
    }
}

//预览本表
const tableFormPreviewLoading = ref(false)
const previewClick = async (item, dragItem = null) => {
    tableFormPreviewLoading.value = true
    await getBussPdfInfo(item, dragItem)
    tableFormPreviewLoading.value = false
}

//上传变量
const uploadModal = ref(false)
const fileListData = ref([])
const uploadData = ref({})

//上传附件
const uploadClick = (items, index) => {
    console.log(111)
}

//获取文件列表
const getBussFileList = async (pKeyId) => {
    const { error, code, data } = await wbsApi.getBussFileList({
        pKeyId: pKeyId,
    })
    if (!error && code === 200) {
        fileListData.value = getArrValue(data)
    } else {
        fileListData.value = []
    }
}


//单个保存
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async (item, dragItem = null) => {
    if (isStatus.value !== 3) {
        tableFormSaveLoading.value = true
        const isSave = await saveExcelBussData(item, dragItem)
        if (isSave) {
            // await getBussPdfInfo(item, dragItem)
            tableFormSaveLoading.value = false
            renewData()
        } else {
            tableFormSaveLoading.value = false
        }
    } else {
        window?.$message?.warning('已上报的资料，不允许保存。')
    }
}

//保存表单数据
const saveExcelBussData = async ({ pKeyId }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '保存中...', true)
    const refs = await getFormRef(pKeyId)
    const isRegExp = await refs?.isFormRegExp()
    if (isRegExp) {
        const formData = refs?.getFormData()
        const { error, code } = await wbsApi.saveExcelBussData(formData)
        setDragModalLoading(dragItem)
        if (!error && code === 200) {
            if (showTip) {
                window?.$message?.success('保存成功')
            }
            return true
        } else {
            return false
        }
    } else {
        setDragModalLoading(dragItem)
        return false
    }
}

//预览PDF
const getBussPdfInfo = async ({ pKeyId }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '获取pdf中...', true)
    const { error, code, data } = await wbsApi.getBussPdfInfo({
        pKeyId: pKeyId,
    }, false)
    setDragModalLoading(dragItem)
    if (!error && code === 200) {
        if (data) {
            window.open(data, '_blank')
        } else if (showTip) {
            window?.$message?.warning('PDF错误')
        }
    } else {
        if (showTip) {
            window?.$message?.warning(data.msg || '获取PDF失败')
        }
    }
}


//通知数据更新
const renewData = () => {
    emit('renew')
    ActiveKey.value = ''
}

//设置表单的加载状态
const setDragModalLoading = (dragItem, text = '保存中...', show = false) => {
    if (dragItem && show) {
        dragItem.loading = true
        dragItem.loadingText = text
    }
    if (dragItem && !show) {
        dragItem.loading = false
    }
}

//获取表单的ref
const getFormRef = async (pKeyId) => {
    const itemRef = getArrValue(itemRefs.value)
    if (itemRef.length <= 0) return ''
    const index = arrIndex(itemRef, 'pKeyId', pKeyId)
    if (index === -1) return ''
    const obj = getObjValue(itemRef[index])
    return obj?.ref
}

//删除打开的窗口
const delWindowRefs = (pKeyId) => {
    //判断是否存在窗口，如果存在，就删除窗口
    const list = DragModalTableForm.value
    const index = arrIndex(list, 'pKeyId', pKeyId)
    if (index !== -1) {
        list.splice(index, 1)
        DragModalTableForm.value = list
    }
}

//计算展开高度和滚动位置
const getOffsetTop = (key = '') => {
    if (key) {
        const dom = document.getElementById(key)
        if (dom?.offsetTop >= 583 && key) {
            emit('offsetTop', dom?.offsetTop - 583)
        } else {
            emit('offsetTop', dom?.offsetTop)
        }
    } else {
        emit('offsetTop', 0)
    }
    ActiveKey.value = key
}

//获取折叠面板的索引
const getCollapseItemIndex = (name) => {
    const keys = name.split('-')
    if (keys.length > 0) {
        return keys[1]
    } else {
        return -1
    }
}

//获取表单的大小
const getTableFormSize = (pKeyId) => {
    let formId = `table-form-${pKeyId}`
    try {
        const { clientWidth, clientHeight } = document.getElementById(formId).children[0]
        return {
            width: (clientWidth + 40) + 'px',
            height: (clientHeight + 80) + 'px',
        }
    } catch {
        return {
            width: '100%',
            height: '100%',
        }
    }
}

//转字符串
const setToString = (val) => {
    return val ? val + '' : ''
}

//表单被点击
const presentId = ref('')
const excelTableFormClick = (key) => {
    presentId.value = key
}

//缓存被激活时
onActivated(() => {
    setMountOnEventKey()
})

//缓存时被移除
onDeactivated(() => {
    HTableForm.unmountEventKey()
})

//页面被卸载
onUnmounted(() => {
    HTableForm.unmountEventKey()
})

const setMountOnEventKey = () => {
    HTableForm.setOnEventKey({
        //按下ctrl键 或 control 键
        onCtrlDown: async () => {
            //window.$HcLog('全局按键', '按下ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(true)
        },
        //按下复制快捷键
        onCtrlDownC: async (event) => {
            //window.$HcLog('全局按键', '按下复制快捷键')
            const refs = await setOnFuncFormRef()
            refs?.setCopyKeyList(event)
        },
        //按下粘贴快捷键
        onCtrlDownV: async (event) => {
            //window.$HcLog('全局按键', '按下粘贴快捷键')
            const refs = await setOnFuncFormRef()
            await refs?.setPasteKeyList(event)
        },
        //放开ctrl键 或 control 键
        onCtrlUp: async () => {
            //window.$HcLog('全局按键', '放开ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(false)
        },
    })
}

//获取表单的ref
const setOnFuncFormRef = async () => {
    const pKeyId = presentId.value
    if (!isNullES(pKeyId)) {
        return await getFormRef(pKeyId)
    } else {
        return
    }
}


//获取已渲染的表单
const getFilterFormData = async () => {
    const formArr = formDataList.value
    return formArr.filter((item) => {
        return (item.pKeyId ?? '') !== '' && item.isCollapseLoad
    })
}

//获取表单数据
const getFormData = async () => {
    const formArr = await getFilterFormData()
    //获取表单数据
    let newArr = []
    for (let i = 0; i < formArr.length; i++) {
        const pKeyId = formArr[i].pKeyId
        const refs = await getFormRef(pKeyId)
        const form = refs?.getFormData()
        newArr.push({ ...form })
    }
    console.log('表单数据', newArr)
    return newArr
}

//获取表单效验数据
const getFormRegExpJson = async () => {
    const formArr = await getFilterFormData()
    const list = listDatas.value
    //获取表单数据
    let formRegExpJson = {}
    for (let i = 0; i < formArr.length; i++) {
        const pKeyId = formArr[i].pKeyId
        const refs = await getFormRef(pKeyId)
        const regExp = refs?.getRegExpJson()
        const nodeName = refs?.getNodeName()
        if (getObjVal(regExp)) {
            const index = arrIndex(list, 'pKeyId', pKeyId)
            formRegExpJson[pKeyId] = {
                ...regExp,
                itemId: `item-${index}-${pKeyId}`,
                nodeName: nodeName,
            }
        }
    }
    return formRegExpJson
}

//获取当前展开项
const getActiveKey = () => {
    return ActiveKey.value
}

//设置当前展开项
const setActiveKey = (key) => {
    return ActiveKey.value = key
}


//操作提示
const actionTipModal = ref(false)
const actionTipModalClose = () => {
    actionTipModal.value = false
}

// 暴露出去
defineExpose({
    getFormData,
    getFormRegExpJson,
    getActiveKey,
    setActiveKey,
})
</script>

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

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