<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="ActiveKey" accordion @change="CollapseChange">
            <template v-for="(item, index) in listDatas" :key="item?.id">
                <el-collapse-item :id="`item-${index}-${item?.id}`" :name="`item-${index}-${item?.id}`">
                    <template #title>
                        <div class="hc-collapse-item-header">
                            <div class="text-lg truncate item-title">
                                {{ item.tableName }}
                            </div>
                            <div class="hc-extra-text-box">
                                <el-button :loading="copyClickLoading" plain type="primary" @click.stop="copyClick(item, index)">
                                    复制本表
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="data-fill-list-item-content">
                        <TableFormItem
                            v-if="item.isTableRender"
                            :ref="(el) => setItemRefs(el, item)"
                            :classify="classifys"
                            :datas="changeFormDatas(item?.id, 'collapse')"
                            :kid="item?.id"
                            :node-name="item.nodeName"
                            :node-type="item.nodeType"
                            :pid="`table-form-${item?.id}`"
                            :area-id="areaId"
                            :table-id="item.tableId"
                            :agreement-id="agreementId"
                            style="width: 100%;"
                            @excelBodyTap="excelTableFormClick($event)"
                            @render="tableFormRender($event, item, index)"
                            @rightTap="tableFormRightTap($event, index)"
                        />
                    </div>
                </el-collapse-item>
            </template>
        </el-collapse>
    </div>
</template>

<script setup>
import { nextTick, onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue'
import HTableForm from '~src/plugins/HTableForm'
import { useAppStore } from '~src/store'
import landApi from '~api/agree/land.js'
import TableFormItem from './form-item.vue'
import {
    arrIndex, deepClone, getArrValue,
    getObjVal, getObjValue, isNullES, setPosRange,
} from 'js-fast-way'

//参数
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
    classify: {
        type: [String, Number],
        default: '',
    },
    status: {
        type: [String, Number],
        default: '',
    },
    primaryKeyId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    drawType: {
        type: Boolean,
        default: false,
    },
    wbsTempId: {
        type: [String, Number],
        default: '',
    },
    tenantId: {
        type: [String, Number],
        default: '',
    },
    wbsType: {
        type: [String, Number],
        default: '',
    },
    areaId:{
        type: String,
        default: '',
    }, //当前树节点
    agreementId:{
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['renew', 'offsetTop'])

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

//全局变量
const projectId = ref(useAppState.projectId)
const contract_id = ref(props.contractId)
const treeId = ref(props.primaryKeyId)
const classifys = ref(props.classify)
const wbsTemp_id = ref(props.wbsTempId)
const tenant_id = ref(props.tenantId)
const wbs_type = ref(props.wbsType)
const isStatus = ref(parseInt(props.status))
const listDatas = ref([])
const draw_type = ref(props.drawType)
const areaId = ref(props.areaId)
const agreementId = ref(props.agreementId)


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

//处理ref
const itemRefs = ref([])
const setItemRefs = (el, { id }) => {
    if (el) {
        let index = arrIndex(itemRefs.value, 'pKeyId', id)
        if (index !== -1) {
            itemRefs.value[index].ref = el
        } else {
            itemRefs.value.push({
                pKeyId: id,
                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: '还原到面板内，并自动展开面板' },
]

//组件参数变量
// const apis = ref({
//     dataInfo: wbsApi.getBussDataInfo,
//     bussCols: wbsApi.getHtmlBussCols,
//     excelHtml: wbsApi.getExcelHtml,
// })

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

//监听变量值
watch(() => [
    useAppState.projectId,
    props.contractId,
    props.wbsTempId,
    props.tenantId,
    props.wbsType,
    props.status,
    props.classify,
    props.primaryKeyId,
    props.areaId,
    props.agreementId,
], ([pid, cid, temp_id, tid, type, status, class_id, tree_id, area_id, agreement_id]) => {
    projectId.value = pid
    contract_id.value = cid
    wbsTemp_id.value = temp_id
    tenant_id.value = tid
    wbs_type.value = type
    isStatus.value = parseInt(status)
    classifys.value = class_id
    treeId.value = tree_id
    areaId.value = area_id
    agreementId.value = agreement_id
})

//渲染完成
onMounted(() => {
    setFormDataNum(props.datas)
    setTableFormMenu(useAppState.projectInfo)
    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.id)
        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([])
const tableFormItemNode = ref({}) //临时信息

//设置菜单权限数据
const setTableFormMenu = (info) => {
    let newArr = [], infos = getObjValue(info)
    const isOpen = infos['isOpenRandomNumber'] ?? 0
    if (isOpen === 1 && isStatus.value !== 3) {
        newArr.push({ label: '插入设计值/频率', key: 'design' })
    }
    newArr.push({ label: '插入特殊字符', key: 'special' })
    newArr.push({ label: '关联试验数据', key: 'test' })
    newArr.push({ label: '关联试验文件', key: 'file' })
    newArr.push({ label: '公式参数', key: 'formula' })
    tableFormMenu.value = newArr
}

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

//鼠标右键菜单被点击
const handleMenuSelect = ({ key }) => {
    if (key === 'design') {
        setInitDesignForm()
        designModalLoading.value = false
        designModal.value = true
    } else if (key === 'special') {
        specialModalShow()
    } else if (key === 'test') {
        testModalLoading.value = false
        testModal.value = true
    } else if (key === 'file') {
        fileModalLoading.value = false
        fileModal.value = true
    } else if (key === 'formula') {
        formulaModalLoading.value = false
        formulaModal.value = true
    }
}

//插入设计值
const designModal = ref(false)
const formDesignRef = ref(null)
const formDesignModel = ref()

//初始设计值/频率表单
const setInitDesignForm = () => {
    formDesignModel.value = {
        type: 1, design: '', size: '',
        dev: '', key: '', capacity: '',
        pass: '', pkId: '',
    }
}

//设计值频率计算
const designModalLoading = ref(false)
const designModalSave = async () => {
    const { pkeyId, KeyName } = tableFormItemNode.value
    if (pkeyId) {
        designModalLoading.value = true
        //const {design, size} = formDesignModel.value
        const { error, code, data } = await wbsApi.queryFormulaRange({
            ...formDesignModel.value,
            // dev: (!design && !size) ? '±5': '',
            key: KeyName,
            pkId: pkeyId,
        })
        //处理数据
        const res = getObjVal(data)
        if (!error && code === 200 && res) {
            try {
                const refs = await getFormRef(pkeyId)
                const itemFormData = refs?.getFormData()
                Object.keys(data).forEach(key => {
                    itemFormData[key] = data[key]
                })
                refs?.setFormData(itemFormData)
            } catch {
            }
            designModalLoading.value = false
            designModal.value = false
        } else {
            designModalLoading.value = false
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
//关闭设计值/频率弹窗
const closeDesignModal = () => {
    designModal.value = false
    setInitDesignForm()
}


//插入特殊字符
const specialModal = ref(false)
const specialModalLoading = ref(false)
const specialModalShow = () => {
    specialFormValue.value = ''
    specialModalLoading.value = false
    specialModal.value = true
}

//监听特殊符号输入框的内容
const specialFormValue = ref('')
const specialDiaolgChange = (val) => {
    specialFormValue.value = val
}

//确认插入
const specialRef = ref(null)
const specialNodeClick = async () => {
    specialModalLoading.value = true
    const itemNode = tableFormItemNode.value
    const { KeyName, pkeyId } = itemNode
    try {
        const refs = await getFormRef(pkeyId)
        const itemFormData = refs?.getFormData()
        const { code, val, posVal } = await specialRef.value?.getSpecialNode(itemNode, itemFormData[KeyName])
        if (code === 200 && val) {
            itemFormData[KeyName] = val
            refs?.setFormData(itemFormData)
            specialModalLoading.value = false
            specialModal.value = false
            await nextTick(() => {
                setPosRange(KeyName, posVal)
            })
        } else {
            specialModalLoading.value = false
        }
    } catch (e) {
        specialModalLoading.value = false
    }
}

//关闭插入特殊字符
const specialModalClose = () => {
    specialModalLoading.value = false
    specialModal.value = false
}

//关联试验数据
const testModal = ref(false)
const testModalLoading = ref(false)

//关联试验数据被点击
const itinsertTableId = ref('')
const itinsertTreeId = ref('')
const testTableRowName = ({ row, treeId }) => {
    itinsertTableId.value = row.id
    itinsertTreeId.value = treeId
    insertDataLoading.value = false
    insertDataShow.value = true
}

//关闭弹窗
const testModalClose = () => {
    testModal.value = false
    testModalLoading.value = false
}

//选择要插入的实验数据
const insertDataShow = ref(false)
const insertDataLoading = ref(false)

//确定关联试验数据数据
const insertDataRef = ref(null)
const submitinsertData = async () => {
    insertDataLoading.value = true
    const itemNode = tableFormItemNode.value
    const { KeyName, pkeyId } = itemNode
    try {
        const refs = await getFormRef(pkeyId)
        const itemFormData = refs?.getFormData()
        const { code, val, posVal } = await insertDataRef.value?.submitinsertData(itemNode, itemFormData[KeyName])
        if (code === 200 && val) {
            itemFormData[KeyName] = val
            refs?.setFormData(itemFormData)
            insertDataLoading.value = false
            insertDataShow.value = false
            testModal.value = false
            await nextTick(() => {
                setPosRange(KeyName, posVal)
            })
        }
    } catch {
        insertDataLoading.value = false
    }
}

//取消关联数据
const cancelinsertData = async () => {
    insertDataShow.value = false
    insertDataLoading.value = false
}


//关联试验文件
const fileModal = ref(false)
const testFileRefs = ref(null)
//确认关联文件
const fileModalLoading = ref(false)
const savefileModal = async () => {
    fileModalLoading.value = true
    await testFileRefs.value?.savefileSubmit()
    fileModalLoading.value = false
    fileModal.value = false
}

//关闭弹窗
const fileModalClose = () => {
    fileModal.value = false
    fileModalLoading.value = false
}

//公式参数配置
const formulaModal = ref(false)
const formulaRefs = ref(null)

//保存
const formulaModalLoading = ref(false)
const formulaSaveClick = async () => {
    formulaModalLoading.value = true
    await formulaRefs.value?.panelSave()
    formulaModalLoading.value = false
    formulaModal.value = false
}


//关闭
const formulaModalClose = () => {
    formulaModal.value = false
    formulaModalLoading.value = false
}


//窗口化
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: contract_id.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'] === '') {
            window.$message.warning('此表单暂无可预览文件')
        } else {
            previewClick(item, items)
        }
    }
}

//删除本表
const tableFormDelLoading = ref(false)
const delClick = async ({ pkeyId }) => {
    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()
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许删除')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
//复制本表相关
const showcopyModal = ref(false)
const copyRefs = ref(null)
const copyModalClose = ()=>{
    // copyModal.value=false
}
const CopyModalType = ref('1')

const copySaveClick = async ()=>{
    //本节点复制
   if (CopyModalType.value === '2') {
        const { pkeyId, isTableRender, isTableForm } = copyItems.value
        if (pkeyId) {
            if (isStatus.value !== 3) {
                if (!isTableRender) {
                    await copeBussTab(pkeyId)
                } else if (!isTableForm) {
                    window?.$message?.warning('暂无表单数据')
                } else if (isTableRender) {
                    copyClickLoading.value = true
                    const isSave = await saveExcelBussData(items, null, false)
                    if (isSave) {
                        await copeBussTab(pkeyId)
                    } else {
                        copyClickLoading.value = false
                        window?.$message?.warning('复制本表操作失败')
                    }
                } else {
                    window?.$message?.warning(`数据异常了, isRenderTableForm: ${isTableRender}, isTableForm: ${isTableForm}, pkeyIds：${pkeyId}`)
                }
            } else {
                window?.$message?.warning('已上报的资料，不允许复制')
            }
        } else {
            window?.$message?.warning('pkeyId为空')
    }
   } else {
    window?.$message?.warning('暂无相关接口')
   }
}
//复制本表
const copyClickModalLoading = ref(false)
const copyClickLoading = ref(false)
const copyClick = async (items) => {
    const { id, isTableRender, isTableForm } = items
    if (id) {
        if (isStatus.value !== 3) {
            if (!isTableRender) {
                await copeBussTab(id)
            } else if (!isTableForm) {
                window?.$message?.warning('暂无表单数据')
            } else if (isTableRender) {
                copyClickLoading.value = true
                const isSave = await saveExcelBussData(items, null, false)
                if (isSave) {
                    await copeBussTab(id)
                } else {
                    copyClickLoading.value = false
                    window?.$message?.warning('复制本表操作失败')
                }
            } else {
                window?.$message?.warning(`数据异常了, isRenderTableForm: ${isTableRender}, isTableForm: ${isTableForm}, pkeyIds：${id}`)
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许复制')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
 }
const copyItems = ref([])
//跨节点复制弹窗
// const copyClick =  (items) => {
//     showcopyModal.value=true
//     copyItems.value=items

// }

//复制表的请求
const copeBussTab = async (pkeyId) => {
    copyClickLoading.value = true
    const { error, code } = await landApi.copeTab({
        id: pkeyId,
    })
    copyClickLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        renewData()
    }
}


//预览本表
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) => {
    const { pkeyId, isTableForm, isTableRender } = items
    const keyName = `item-${index}-${pkeyId}`
    if (pkeyId) {
        if (isStatus.value !== 3 && isTableForm) {
            uploadModal.value = true
            uploadData.value = {
                projectId: projectId.value,
                contractId: contract_id.value,
                classify: classifys.value,
                pkeyId: pkeyId,
                nodeId: treeId.value,
            }
            //获取文件列表
            getBussFileList(pkeyId)
        } else if (!isTableRender) {
            CollapseChange(keyName)
            window?.$message?.warning('请再次点击上传')
        } else if (!isTableForm) {
            window?.$message?.warning('暂无表单数据')
        } else {
            window?.$message?.warning('已上报的资料，不允许上传')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//获取文件列表
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 uploadChange = async ({ type }) => {
    if (type === 'success') {
        uploadModal.value = false
        renewData()
    } else if (type === 'del') {
        renewData()
    }
}

//关闭上传附件窗口
const uploadModalClose = () => {
    uploadModal.value = false
}

//单个保存
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 ({ id }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '保存中...', true)
    const refs = await getFormRef(id)
    const isRegExp = await refs?.isFormRegExp()
    if (isRegExp) {
        const formData = refs?.getFormData()
        const { error, code } = await landApi.saveBussData(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 ({ id }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '获取pdf中...', true)
    const { error, code, data } = await landApi.getBussPdfInfo({
        id: id,
    }, 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 = itemRefs.value
    const index = arrIndex(itemRef, 'pKeyId', pkeyId)
    return itemRef[index].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 (!draw_type.value) {
            if (dom?.offsetTop >= 583 && key) {
                emit('offsetTop', dom?.offsetTop - 583)
            } else {
                emit('offsetTop', dom?.offsetTop)
            }
        } else {
            if (dom.offsetTop >= 424 && key) {
                emit('offsetTop', dom?.offsetTop - 424)
            } 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.linkId ?? '') !== '' && item.isCollapseLoad
    })
}

//获取表单数据
const getFormData = async () => {
    const formArr = await getFilterFormData()
    //获取表单数据
    let newArr = []
    for (let i = 0; i < formArr.length; i++) {
        const pkeyId = formArr[i].linkId
        const refs = await getFormRef(pkeyId)
        const form = refs?.getFormData()
        newArr.push({ ...form })
    }
    console.log('表单数据1111', 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].linkId
        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
}

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

<style lang="scss" scoped>
@import "../../components/collapse-form.scoped.scss";
</style>

<style lang="scss">
@import "../../components/collapse-form.scss";
</style>
