<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="ActiveKey" accordion @change="CollapseChange">
            <template v-for="(item, index) in listDatas" :key="item?.pKeyId">
                <el-collapse-item :id="`item-${index}-${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 || delClickLoading" @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 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">
                            <div :id="`table-form-${item?.pKeyId}`" class="hc-excel-table-form-view" />
                            <div v-if="item?.isTableForm === false" class="hc-no-table-form">
                                <div class="table-form-no">
                                    <img :src="notableform" alt="">
                                    <div class="desc">
                                        暂无表单数据
                                    </div>
                                </div>
                            </div>
                            <el-tooltip :content="item.isWindow ? '关闭窗口并恢复' : '当前表单窗口化'" :hide-after="0" placement="top">
                                <div v-if="item.isWindow" class="form-window-icon" @click.stop="windowCloseClick(item, index)">
                                    <HcIcon name="fullscreen-exit" />
                                </div>
                                <div v-else class="form-window-icon" @click.stop="windowClick(item, index)">
                                    <HcIcon name="fullscreen" />
                                </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 v-loading="downloadLoading" class="link-action">
                                <HcTooltip keys="wbs_download_table">
                                    <el-link type="primary" @click="downModal(item)">下载导入模板</el-link>
                                </HcTooltip>
                                <HcTooltip keys="wbs_import_table">
                                    <el-link type="primary" @click="uploadFileClick(item)">导入表格数据</el-link>
                                </HcTooltip>
                                <HcUploadFile
                                    v-if="checkItem?.pKeyId"
                                    ref="dataHcUploadFileRef"
                                    :params="{ pKeyId: checkItem.pKeyId }"
                                    :options="UploadFileOptions"
                                    multiple="false"
                                    @success="HcUploadFileSuccess"
                                />
                            </div>
                            <div class="btn-action">
                                <HcTooltip keys="wbs_save_table">
                                    <el-button
                                        :disabled="NodeStatusval === '3'" :loading="tableFormSaveLoading"
                                        color="#3794FF" size="small" style="color: white"
                                        @click="tableFormSaveClick(item)"
                                    >
                                        仅保存本表数据
                                    </el-button>
                                </HcTooltip>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </template>
        </el-collapse>
    </div>

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

    <!-- 上传文件 -->
    <hc-new-dialog v-model="uploadModal" :footer="false" title="上传文件" widths="38rem">
        <HcUpload
            :base-data="baseData" :contract-id="contractId" :datas="uploadData" :file-list="fileListData"
            :table-type-value="tableTypeValue" @change="uploadChange"
        />
    </hc-new-dialog>

    <!-- 插入特殊字符 -->
    <hc-new-dialog v-model="specialModal" save-text="确认插入" title="插入特殊字符" widths="600px" @save="specialNodeClick">
        <el-form
            ref="specialFormRef" :model="specialFormModel" :rules="specialFormRules" class="mb-6" label-width="0px"
            size="large"
        >
            <el-form-item class="special-form-item" prop="val">
                <el-input
                    id="specialId" ref="specialRef" v-model="specialFormModel.val"
                    clearable placeholder="请选择特殊字符代码" @blur="specialInputBlur"
                />
            </el-form-item>
        </el-form>
        <el-row :gutter="20" style="margin: -10px;">
            <el-col v-for="item in specialCharacters" :key="item" :span="3" style="padding: 10px;">
                <div class="special-box" @click="specialClick">
                    <span :title="`字符代码(C):${item !== 'K̅' ? item.slice(2, 7) : 'K̅'}`" class="font-EUDC" v-html="item" />
                </div>
            </el-col>
        </el-row>
    </hc-new-dialog>

    <!-- 引用容器参数 -->
    <hc-new-dialog v-model="vesselModal" is-table save-text="确认引用" title="引用容器参数" widths="84%" @close="vesselModalClose" @save="vesselModalSave">
        <div class="adding-form-dialog-box">
            <div class="dialog-tree-box">
                <el-scrollbar>
                    <HcMenuSimple :datas="menus" :keys="menuKey" :props="menuProps" @change="menuChange" />
                </el-scrollbar>
            </div>
            <div class="dialog-table-box">
                <div class="dialog-table">
                    <HcTable
                        ref="vesselTableRef" :column="vesselTableColumn" :datas="vesselTableData" :loading="vesselTableLoading"
                        is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                        @selection-change="vesselTableSelection"
                    />
                </div>
                <div class="dialog-pages">
                    <HcPages :pages="vesselTablePage" @change="vesselTablePageChange" />
                </div>
            </div>
        </div>
    </hc-new-dialog>

    <!-- 引用设备仪器 -->
    <hc-new-dialog v-model="deviceModal" is-table save-text="确认引用" title="引用设备仪器" widths="84%" @close="deviceModalClose" @save="deviceModalSave">
        <!-- <HcTable ref="deviceTableRef" :column="deviceTableColumn" :datas="deviceTableData" :loading="deviceTableLoading" isCheck @selection-change="deviceTableSelection"/> -->
        <div class="adding-form-dialog-box">
            <div class="dialog-tree-box">
                <el-scrollbar>
                    <HcMenuSimple
                        :datas="equipmentmenus" :keys="equipmentmenuKey" :props="equipmentmenuProps"
                        @change="equipmentmenuChange"
                    />
                </el-scrollbar>
            </div>
            <div class="dialog-table-box">
                <div class="dialog-table">
                    <HcTable
                        ref="deviceTableRef" :column="deviceTableColumn" :datas="deviceTableData" :loading="deviceTableLoading"
                        is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                        @selection-change="deviceTableSelection"
                    />
                </div>
                <div class="dialog-pages">
                    <HcPages :pages="equipmentPage" @change="equipmentTablePageChange" />
                </div>
            </div>
        </div>
    </hc-new-dialog>

    <!-- 查看表单 -->
    <template v-for="(item, index) in DragModalTableForm">
        <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, true)" @closeIconTap="closeIconTap($event, item, index)"
        >
            <HcDragNode v-loading="item.tableFormSaveLoading" :more-menu="dragNodeMoreMenu" @menuTap="dragNodeMoreMenuTap($event, item, index)">
                <div :id="`table-form-${item?.item.pKeyId}`" class="hc-excel-table-form-view" :style="`width:${item.width};height:${item.height};`" />
                <div v-if="item?.isTableForm === false" class="hc-no-table-form">
                    <div class="table-form-no">
                        <img :src="notableform" alt="">
                        <div class="desc">
                            暂无表单数据
                        </div>
                    </div>
                </div>
            </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、系统支持键盘中，shift + tab键向上一个填报框切换，tab向下一个填报框切换。暂不支持上下按键切换输入框
            </div>
            <div class="text-orange-500 tip-item">3、完善资料填写后记得一定要保存哦</div>
        </div>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute } from 'vue-router'
import wbsApi from '~api/data-fill/wbs'
import HcUpload from './HcUpload.vue'
import HTableForm from '~src/plugins/HTableForm'
import dataApi from '~api/tentative/detect/test'
import dataApi1 from '~api/tentative/parameter/container'
import dataApi2 from '~api/tentative/device/approach'
import { getClassList } from '~api/tentative'
import notableform from '~src/assets/view/notableform.svg'
import NoDataSvg from '~src/assets/view/no-data.svg'
import { setStoreValue } from '~uti/storage'
import {
    arrIndex,
    base64ToFile,
    clog,
    deepClone,
    downloadBlob,
    formValidate,
    getArrValue,
    getObjVal,
    getObjValue,
    isString,
    setPosInsert,
    setPosRange,
} from 'js-fast-way'
import ossApi from '~api/oss'
import { getTokenHeader } from '~src/api/request/header'

//初始
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
    status: {
        type: [String, Number],
        default: '',
    },
    baseData: {
        type: Object,
        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: () => ([]),
    },
    newlistdata: {
        type: Array,
        default: () => ([]),
    },
    nodeStatus: {
        type: String,
        default: () => (''),
    },
})
//事件
const emit = defineEmits(['renew', 'offsetTop', 'updeviceUseIds', 'upcheckTableId', 'changesdate', 'chageorinData', 'changeIscanclick', 'changesingSaveId', 'getList'])
const useRoutes = useRoute()
//路由参数
const routerQuery = useRoutes?.query
const isaddType = routerQuery?.isaddType || false
const listDatas = ref(props.datas)
const isStatus = ref(props.status)
const baseData = ref(props.baseData)
const authBtnTabKeyType = ref(props.authBtnTabKey)//所属方
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const tabTypeKeyInfo = ref(props.tabTypeKey)
const nodeIdvaluedata = ref(props.nodeIdvalue)
const alllistDataval = ref(props.alllistData)
const NodeStatusval = ref(props.NodeStatus)
const newlistdata = ref(props.newlistdata)

//监听
watch(() => [
    props.datas,
    props.tabTypeKey,
    props.alllistData,
    props.NodeStatus,
], ([datas, TabTypeKey, AlllistData, NodeStatus]) => {
    listDatas.value = datas
    listDatas.value.forEach((item) => {
        if (item.pKeyId === singleSaveid.value) {
            item.isCancopy = true
        }
    })
    tabTypeKeyInfo.value = TabTypeKey
    alllistDataval.value = AlllistData
    NodeStatusval.value = NodeStatus
    setFormDataNum(datas)

})

//监听
watch(() => [
    props.status,
    props.baseData,
    props.nodeIdvalue,
    props.newlistdata,
], ([val, base, NodeIdvalue, Newlistdata]) => {
    //1 未填报，2待上报，3已上报
    isStatus.value = val
    baseData.value = base
    nodeIdvaluedata.value = NodeIdvalue
    newlistdata.value = Newlistdata
})

//渲染完成
nextTick(() => {
    setFormDataNum(props.datas)
})

//获取pKeyId
const getValString = (val) => {
    return val ? val + '' : ''
}

//获取表单初始数据
const getFormDataInit = ({ projectId, cid, pKeyId, isBussShow }) => {
    const { nodeId, contractId } = baseData.value
    return {
        projectId: projectId,
        contractId: cid || contractId,
        pkeyId: getValString(pKeyId),
        nodeId: nodeId,
        isBussShow: isBussShow,
    }
}

//设置表单对象的数量
const formData = ref([])
const formLinkIdData = ref({})
const setFormDataNum = (datas) => {
    ActiveKey.value = ''


    let newArr = []
    for (let i = 0; i < datas.length; i++) {
        newArr.push({
            ...getFormDataInit(datas[i]),
            isCollapseLoad: false,
        })
    }
    formData.value = newArr
    //处理关联表
    let newDataObj = {}
    for (let i = 0; i < datas.length; i++) {
        const item = datas[i]
        newDataObj[item.pKeyId] = {
            tableId: item.initTableId,
            isMain: item.isCopyTab === 0,
            mainId: item.isCopyTab === 0 ? item.pKeyId : '',
            linkId: [],
        }
        //获取关联表
        datas.forEach((items) => {
            if (items.initTableId === item.initTableId && item.pKeyId !== items.pKeyId) {
                newDataObj[item.pKeyId].linkId.push(items.pKeyId)
                if (items.isCopyTab === 0) {
                    newDataObj[item.pKeyId].mainId = items.pKeyId
                }
            }
        })
    }
    formLinkIdData.value = newDataObj
}
const sampledata = ref([])
const positiondata = ref([])
//展开事件
const ActiveKey = ref('')
const formKeyIds = ref('')
const setCollapseKey = (key) => {
    CollapseChange(key)
}
const CollapseChange = async (name) => {
    setStoreValue('ActiveKey', name)
    ActiveKey.value = name
    const names = name ? name.split('-') : []
    formData.value.forEach((changeitem) => {
        if (changeitem.pkeyId === names[2]) {
            changeitem.isCollapseLoad = true
        }
    })
    if (names.length > 0) {
        getOffsetTop(name)
        const index = names[1]
        let item = listDatas.value[index]

        emit('upcheckTableId', item.pKeyId)
        emit('changeIscanclick', item.pKeyId)
        formKeyIds.value = getValString(item.pKeyId)
        alllistDataval.value.forEach((item1) => {
            // eslint-disable-next-line eqeqeq
            if (item1.pkeyId == item.pKeyId) {
                if (item1.oper) {
                    item.isTableFormRender = true
                    item = item1
                    item.pKeyId = item1.pkeyId
                }
            }
        })
        if (!item.isTableFormRender) {
            await getBussDataInfo(item, index)
        } else {
            await getBussDataInfo1(item, index)
        }
        //渲染表单
        await getExcelHtml(item, index)
        const { key, data } = await getChartConfig()
        if (key) formData.value[index][key] = data
    } else {
        // await getExcelHtml(item,index)
        getOffsetTop()
        formKeyIds.value = ''
    }
}

//获取模板标签数据
const formRegExpJson = ref({})
const getExcelHtml = async (item, index) => {
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        const { id } = baseData.value
        const { error, code, data } = await dataApi.getExcelHtml({
            id: id || nodeIdvaluedata.value || newaddId.value,
            primaryKeyId: pkeyIds,
        }, false)
        const resData = isString(data) ? data || '' : ''
        if (!error && code === 200 && resData) {
            item.isTableForm = true
            //渲染表单
            HTableForm.createForm({
                template: resData,
                tableForm: formData.value[index],
                appId: `#table-form-${pkeyIds}`,
                onChartRefs: (el, pKeyId, key) => {
                    setChartRefs(el, pKeyId, key)
                },
                onRight: (event, KeyName) => {
                    onRightClick(event, KeyName, index)
                },
                //表单正则效验
                onBlur: (event, key, reg, val, msg, type) => {
                    setTableFormBlurReg(pkeyIds, event, key, reg, val, msg, item, index)
                    if (type === 'chart') {
                        chartKey.value = formData.value[index].formchartKeyShow
                        getBlurChartConfig(formData.value[index])
                    }
                },
            })
            item.isTableFormRender = true
            item.isRenderTableForm = true
        } else {
            item.isTableForm = false
            item.isRenderTableForm = true
            window?.$message?.warning('暂无表单')
        }
    } else {
        item.isTableForm = false
        item.isRenderTableForm = false
        window?.$message?.warning('pkeyId为空')
    }
}

//图表ref
const chartRefs = ref([])
const setChartRefs = async (el, pKeyId, key) => {
    if (el) {
        const { index } = await getChartRef(pKeyId, key)
        if (index !== -1) {
            chartRefs.value[index].ref = el
        } else {
            chartRefs.value.push({ pKeyId: pKeyId, key: key, ref: el })
        }
    }
}
//获取图表的ref
const getChartRef = async (pKeyId, key) => {
    let refs = chartRefs.value, refVal, index = -1
    for (let i = 0; i < refs.length; i++) {
        if (refs[i].pKeyId === pKeyId && refs[i].key === key) {
            refVal = refs[i].ref
            index = i
            break
        }
    }
    return { ref: refVal, index: index }
}

//图表信息
const chartKey = ref('')
const getBlurChartConfig = async (form = {}) => {
    if (chartKey.value) {
        let { formChartKey } = form, formKeys = {}, keyId = formKeyIds.value
        formKeys[keyId] = {}
        const chartKeys = formChartKey ? formChartKey.split(',') : []
        chartKeys.forEach((item) => {
            formKeys[keyId][item] = form[item] ?? ''
        })
        //关联表单的key
        const { linkId } = formLinkIdData.value[keyId]
        for (let i = 0; i < linkId.length; i++) {
            const newKey = linkId[i]
            formKeys[newKey] = {}
            formKeys = await getFormChartKey(formKeys, newKey)
        }
        //更新图表配置
        const { key, data } = await getChartConfig(formKeys)
        if (key) {
            form[key] = data
            const { ref } = await getChartRef(keyId, key)
            ref?.setOptions(data)
        }
    } else {
        console.log('formchartKeyShow 为空')
    }
}

//获取表单的图表数据
const getFormChartKey = async (formKeys, key) => {
    const index = formData.value.findIndex((item) => item.pkeyId === key)
    const form = formData.value[index], { formChartKey } = form
    const chartKeys = formChartKey ? formChartKey.split(',') : []
    chartKeys.forEach((item) => {
        formKeys[key][item] = form[item] ?? ''
    })
    return formKeys
}


//获取图片配置
const getChartConfig = async (form = {}) => {
    if (chartKey.value) {
        const { id } = baseData.value
        const { data } = await dataApi.getChartInit({
            id: id || nodeIdvaluedata.value || newaddId.value,
            pkeyId: formKeyIds.value,
            data: form,
        })
        return {
            key: chartKey.value,
            data: getObjValue(data),
        }
    } else {
        console.log('formchartKeyShow 为空')
        return { key: '', data: {} }
    }
}

//正则效验
const setTableFormBlurReg = (pkeyId, event, key, reg, val, msg, item, index) => {
    const dom = document.getElementById(key)?.parentElement ?? ''
    if (dom) {
        if (val && reg) {
            let regx = new RegExp(reg)
            let state = regx.test(val)
            if (state) {
                delete formRegExpJson.value[pkeyId]
                dom.style = ''
            } else {
                formRegExpJson.value[pkeyId] = {
                    key,
                    reg,
                    val,
                    msg,
                    state,
                    nodeName: item.nodeName,
                    itemId: `item-${index}-${item?.pKeyId}`,
                }
                dom.style = '--el-input-border-color: #fe0000; box-shadow: 0 0 0 2px #fe0000 inset;'
                window?.$message?.warning(msg)
            }
        } else {
            delete formRegExpJson.value[pkeyId]
            dom.style = ''
        }
    }
}
//关联取样成功改变所有表格取样名称数据
const getsampleData = () => {
    if (sampledata.value.length > 0) {
        formData.value.forEach((ele) => {
            sampledata.value.forEach((item) => {
                if (item.tabPKeyId === ele.pkeyId) {
                    for (let i in item) {
                        ele[i] = item[i]
                    }
                }
            })
        })
    }
}
//getPositionData关联取样成功改变所有表格工程部位数据
const getPositionData = () => {
    if (positiondata.value.length > 0) {
        formData.value.forEach((ele) => {
            positiondata.value.forEach((item) => {
                if (item.tabPKeyId === ele.pkeyId) {
                    for (let i in item) {
                        ele[i] = item[i]
                    }
                }
            })
        })
    }
}
const changeSimpleInput = (infodata) => {
    sampledata.value = infodata
    getsampleData()
}
const changePositionInput = (infodata) => {
    positiondata.value = infodata
    getPositionData()
}

//获取已填写的数据
const getBussDataInfo = async (item, index) => {
    const pkeyIds = getValString(item.pKeyId)
    const { contractId } = baseData.value
    if (pkeyIds) {
        const { id } = baseData.value
        const { error, code, data } = await dataApi.getBussDataInfo({
            id: id || nodeIdvaluedata.value || newaddId.value,
            pkeyId: pkeyIds,
            contractId: contractId,
        }, false)
        emit('changesingSaveId', pkeyIds)
        if (item.oper) {
            HTableForm.setPickerKey([item])
            formData.value[index] = {
                ...item,
                isCollapseLoad: true,
            }
            getsampleData()
            getPositionData()
        } else {
            data.forEach((item1) => {
                const resData = getObjVal(item1)
                if (!error && code === 200 && resData) {
                    HTableForm.setPickerKey(resData)
                    const InitObj = getFormDataInit(item) //有数据，关联数据
                    formData.value[index] = {
                        ...resData, ...InitObj,
                        isCollapseLoad: true,
                    }
                    getsampleData()
                    getPositionData()
                } else {
                    formData.value[index] = {
                        ...getFormDataInit(item),
                        isCollapseLoad: true,
                    }
                    getsampleData()
                    getPositionData()
                }
            })
        }
        chartKey.value = formData.value[index].formchartKeyShow
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
const getBussDataInfo1 = async (item, index) => {
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        if (item.oper) {
            HTableForm.setPickerKey([item])
            formData.value[index] = {
                ...item,
                isCollapseLoad: true,
            }
        }
        chartKey.value = formData.value[index].formchartKeyShow
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//单个保存
const tableFormSaveLoading = ref(false)
const singleSaveid = ref('')
const tableFormSaveClick = async (item, index) => {
    if (isStatus.value !== '3') {
        singleSaveid.value = item.pKeyId
        emit('changesingSaveId', item.pKeyId)
        if (tabTypeKeyInfo.value === '2' && baseData.value['detectionResult'] === '') {
            window.$message?.warning('请选择是否合格')
        } else {
            const res = await saveExcelBussData(item, index)
            if (res) {
                // if (!isaddType) {
                //     await getBussPdfInfo(item)
                // } else {
                //     await getBussPdfInfo(item)
                // }
                renewData(newaddId.value)
            }
        }
    } else {
        window?.$message?.warning('已上报的资料，不允许保存。')
    }
}

//上传图表的图片
const uploadChartImgFile = async (base64) => {
    let fileOfBlob = base64ToFile(base64)
    let formData = new FormData()
    formData.append('file', fileOfBlob)
    //上传文件
    const { error, code, data } = await ossApi.putFile(formData, false)
    if (!error && code === 200) {
        let res = getObjValue(data)
        if (res?.link) {
            return res.link
        } else {
            return ''
        }
    } else {
        return ''
    }
}

const newaddId = ref('')
//保存表单数据
const saveExcelBussData = async (item, index, showTip = true) => {
    let saveItem = {}
    formData.value.forEach((ele)=>{
        if (ele.pkeyId === item.pKeyId) {
            saveItem = ele
        }
    })
    if (!getObjVal(formRegExpJson.value)) {
        tableFormSaveLoading.value = true
        const InitObj = getFormDataInit(item)
        if (chartKey.value) {
            const { ref } = await getChartRef(item.pKeyId, chartKey.value)
            const url = await uploadChartImgFile(ref?.getImage())
            const name = `${chartKey.value}_url`
            InitObj[name] = url
        }
        baseData.value.tableType = tabTypeKeyInfo.value
        if (newaddId.value.length > 0) {
            baseData.value.id = newaddId.value
        }

        const { error, code, data } = await dataApi.saveExcelBussData({
            ...baseData.value,
            isBatchSave: 0,
            dataInfo: {
                // orderList: [{ ...formData.value[index], ...InitObj }],
                orderList: [{ ...saveItem, ...InitObj }],
            },
        })
        //处理数据
        tableFormSaveLoading.value = false
        if (!error && code === 200) {
            if (showTip) window?.$message?.success('保存成功')
            newaddId.value = data
            return true
        } else {
            return false
        }
    } else {
        window?.$message?.warning('请先修改完红色输入框的数据')
        return false
    }
}

//预览PDF
const getBussPdfInfo = async ({ pKeyId }, showTip = true) => {
    const pkeyIds = getValString(pKeyId)
    if (pkeyIds) {
        const { id } = baseData.value
        const { error, code, data } = await dataApi.getBussPdf({
            id: id.length > 0 ? id : newaddId.value,
            pKeyId: pkeyIds,
        }, false)
        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失败')
            }
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
const delClickLoading = ref(false)
//删除本表
const delClick = async ({ pKeyId }, index) => {
    const pkeyIds = getValString(pKeyId)
    if (pkeyIds) {
        const { id } = baseData.value
        delClickLoading.value = true
        const { error, code } = await dataApi.removeBussTabInfo({
            // id: id,
            pKeyId: pkeyIds,
        })
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            // renewData(id)
            listDatas.value.splice(index, 1)
            formData.value.splice(index, 1)
            chageOrinData()
            delClickLoading.value = false
        } else {
            delClickLoading.value = false
        }
    } else {
        window?.$message?.warning('pkeyId为空')
        delClickLoading.value = false
    }
}
const copyClickLoading = ref(false)
//复制本表
const copyClick = async (item, index) => {
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        if (isStatus.value !== '3') {
            if (item.isRenderTableForm && !item.isCancopy) {
                // window.$message.warning('请先保存数据再复制本表')
                copyClickLoading.value = true
                const res = await saveExcelBussData(item, index)
                     if (res) {
                        // renewData(newaddId.value)
                        await copeBussTab(pkeyIds)

                    } else {
                        copyClickLoading.value = false
                        window?.$message?.warning('复制本表操作失败')
                    }
            } else {
                if (!item.isRenderTableForm) {
                    await copeBussTab(pkeyIds)
                } else if (!item.isTableForm) {
                    window?.$message?.warning('暂无表单数据')
                } else if (item.isRenderTableForm) {
                    await copeBussTab(pkeyIds)
                } else {
                    window?.$message?.warning(`数据异常了, isRenderTableForm: ${item.isRenderTableForm}, isTableForm: ${item.isTableForm}, pKeyId：${pkeyIds}`)
                }
            }

        } else {
            window?.$message?.warning('已上报的资料，不允许复制')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

const copeBussTab = async (pkeyIds) => {
    const { id, contractId } = baseData.value
    copyClickLoading.value = true
    const { error, code } = await dataApi.copyBussTab({
        id: id || newaddId.value,
        pKeyId: pkeyIds,
        contractId: contractId,
    })
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        // renewData(id)
       chageOrinData()
        getNewList( )
    }
    copyClickLoading.value = false
}
//获取表单列表
const getNewList = (id)=>{
    emit('getList', id)
   setTimeout(() => {
    let newObj = newlistdata.value
    let oldObj = listDatas.value
    const addedObject = newObj.find(obj => !oldObj.some(oldObj => oldObj.pKeyId === obj.pKeyId))
    let index = arrIndex(newlistdata.value, 'pKeyId', addedObject.pKeyId) // 1
    listDatas.value.splice(index, 0, addedObject)
    formData.value.splice(index, 0, addedObject)
   }, 1000)
}
//隐藏本表
const hideClick = async ({ pKeyId, isBussShow }, index) => {
    if (isBussShow === 1) {
        ActiveKey.value = ''
    }
    const pkeyIds = getValString(pKeyId)
    if (pkeyIds) {
        if (isStatus.value !== '3') {
            const { id } = baseData.value
            const isBussShows = isBussShow === 2 ? 1 : 2 //状态(1显示 2隐藏)
            const { error, code } = await dataApi.showBussTab({
                id: id,
                pKeyId: pkeyIds,
                status: isBussShows,
            })
            if (!error && code === 200) {
                window?.$message?.success('操作成功')
                // renewData(id)
                listDatas.value[index].isBussShow = isBussShows
                changeisHide(pkeyIds, isBussShow, id)
                formData.value[index].isBussShow = isBussShows
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许隐藏')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//预览
const previewClick = async (item) => {
    await getBussPdfInfo(item)
}

//上传变量
const uploadModal = ref(false)
const fileListData = ref([])
const uploadData = ref({})
const tableTypeValue = ref('')
//上传被点击
const uploadClick = (item, index) => {
    const pkeyIds = item.pKeyId ? item.pKeyId + '' : ''
    const { id } = baseData.value
    const tableType = item.tableType ? item.tableType : ''
    tableTypeValue.value = item.tableType ? item.tableType : ''
    const classify = authBtnTabKeyType.value
    const keyName = `item-${index}-${pkeyIds}`
    if (pkeyIds) {
        if (isStatus.value !== '3' && item.isTableForm) {
            uploadModal.value = true
            uploadData.value = getFormDataInit(item, pkeyIds)
            uploadData.value.tableType = tableType
            uploadData.value.classify = classify
            uploadData.value.id = id
            //获取文件列表
            getBussFileList(pkeyIds)
        } else if (!item.isRenderTableForm) {
            CollapseChange(keyName)
            window?.$message?.warning('请再次点击上传')
        } else if (!item.isTableForm) {
            window?.$message?.warning('暂无表单数据')
        } else {
            window?.$message?.warning('已上报的资料，不允许上传')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

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

//上传文件
const uploadChange = async ({ type }) => {
    const { id } = baseData.value
    if (type === 'success') {
        uploadModal.value = false
        renewData(id)
    } else if (type === 'del') {
        renewData(id)
    }
}

//相关变量
const tableFormItemNode = ref({})

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

//鼠标右键事件
const contextMenuRef = ref(null)
const onRightClick = (event, KeyName, index) => {
    //取光标位置
    const specialDom = document.getElementById(KeyName + '')
    const startPos = specialDom?.selectionStart || 0
    const endPos = specialDom?.selectionEnd || 0
    //存储临时信息
    tableFormItemNode.value = { KeyName, index, startPos, endPos, pkeyId: formKeyIds.value }
    contextMenuRef.value?.showMenu(event) //展开菜单
}

//鼠标右键菜单被点击
const handleMenuSelect = ({ key }) => {
    if (key === 'vessel') {
        vesselModal.value = true
        getMenusData()
    } else if (key === 'special') {
        specialModalShow()
    } else if (key === 'device') {
        deviceModal.value = true
        nextTick(() => {
            deviceTableRef.value?.clearSelection()

        })
        getequipmentMenusData()
    }
}

//引用容器参数
const vesselModal = ref(false)
const vesselTableRef = ref(null)

//引用容器参数菜单数据
const menuProps = {
    key: 'id',
    label: 'containerName',
}
//引用容器参数菜单数据
const equipmentmenuProps = {
    key: 'id',
    label: 'className',
}
const menus = ref([])
const getMenusData = async () => {
    const { data } = await dataApi1.queryClassification({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const arr = getArrValue(data)
    menus.value = arr
    if (arr.length > 0) {
        const item = arr[0]
        menuItem.value = item
        menuKey.value = item?.id
        vesselTableColumn.value = []
        if (item?.fieldList && item?.fieldList.length > 0) {
            item?.fieldList.forEach((item1) => {
                vesselTableColumn.value.push(({
                    key: item1?.fieldKey,
                    name: item1?.fieldName,
                }))
            })
        }
        getVesselTableData()
    }
}

//菜单被点击
const menuKey = ref()
const menuItem = ref({})
const menuChange = (item) => {
    menuItem.value = item
    menuKey.value = item?.id
    vesselTableColumn.value = []
    item?.fieldList.forEach((item1) => {
        vesselTableColumn.value.push(({
            key: item1?.fieldKey,
            name: item1?.fieldName,
        }))
    })
    getVesselTableData()
}

//表格数据
const vesselTableColumn = ref([
    // {key:'key_1', name: '容器编号'},
])
const vesselTableData = ref([])
const vesselTablePage = ref({ current: 1, size: 20, total: 0 })
const vesselTablePageChange = ({ current, size }) => {
    vesselTablePage.value.current = current
    vesselTablePage.value.size = size
    getVesselTableData()
}
//获取表格数据
const vesselTableLoading = ref(false)
const getVesselTableData = async () => {
    const { fieldList } = menuItem.value
    const fieldLists = getArrValue(fieldList)
    if (fieldLists.length > 0) {
        vesselTableLoading.value = true
        const { error, code, data } = await dataApi1.queryPage({
            projectId: projectId.value,
            contractId: contractId.value,
            containerId: menuKey.value,
            fieldKey: fieldList[0].fieldKey,
            size: vesselTablePage.value.size,
            current: vesselTablePage.value.current,
        })
        //处理数据
        vesselTableLoading.value = false
        if (!error && code === 200) {
            vesselTableData.value = getArrValue(data['records'])
            vesselTablePage.value.total = data.total || 0
        } else {
            vesselTableData.value = []
            vesselTablePage.value.total = 0
        }
    }
}
//多选
const vesselTableKeys = ref([])
const vesselTableSelection = (rows) => {
    vesselTableKeys.value = rows
}

//确认引用
const vesselModalSave = () => {
    if (vesselTableKeys.value.length > 0) {
        const item = tableFormItemNode.value
        const form = formData.value[item.index]
        const val = []
        vesselTableKeys.value.forEach((item) => {
            val.push(item.key_2)
        })
        const newval = val.join('、')
        formData.value[item.index][item.KeyName] = setPosInsert(item.startPos, item.endPos, form[item.KeyName], newval)
        vesselModal.value = false
        let posVal = item.startPos + newval.length
        nextTick(() => {
            setPosRange(item.KeyName, posVal)
        })
    } else {
        window?.$message?.warning('请先选择引用容器参数')
    }

}
//关闭
const vesselModalClose = () => {
    vesselModal.value = false
}


const equipmentmenus = ref([])
const getequipmentMenusData = async () => {
    const { data } = await getClassList({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const arr = getArrValue(data)
    equipmentmenus.value = arr
    if (arr.length > 0) {
        const item = arr[0]
        equipmentmenuItem.value = item
        equipmentmenuKey.value = item?.id
        getDeviceTableData()
    }
}

//菜单被点击
const equipmentmenuKey = ref()
const equipmentmenuItem = ref({})
const equipmentmenuChange = (item) => {
    equipmentmenuItem.value = item
    equipmentmenuKey.value = item?.id
    getDeviceTableData()
}

//引用设备仪器
const deviceModal = ref(false)
const deviceTableRef = ref(null)

//表格数据
const deviceTableColumn = ref([
    { key: 'deviceNumber', name: '设备编号' },
    { key: 'deviceName', name: '设备仪器名称' },
])
const deviceTableData = ref([])
const equipmentPage = ref({ current: 1, size: 20, total: 0 })
const equipmentTablePageChange = ({ current, size }) => {
    equipmentPage.value.current = current
    equipmentPage.value.size = size
    getDeviceTableData()
}
//数组去重
let temp = []
const getnewArr = (tempArr) => {
    tempArr.forEach(function (a) {
        let check = temp.every(function (b) {
            return a.id !== b.id
        })
        check ? temp.push(a) : ''
    })
    return temp
}


//获取表格数据
const deviceTableLoading = ref(false)
const getDeviceTableData = async () => {
    deviceTableLoading.value = true
    const { error, code, data } = await dataApi2.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        deviceClassId: equipmentmenuKey.value,
        size: equipmentPage.value.size,
        current: equipmentPage.value.current,

    })
    //处理数据
    deviceTableLoading.value = false
    if (!error && code === 200) {
        deviceTableData.value = getArrValue(data['records'])
        equipmentPage.value.total = data.total || 0

        //去重
        let uniqueArray = getnewArr(checkList.value)
        deviceTableKeys.value = uniqueArray

        if (uniqueArray.length > 0) {
            uniqueArray.forEach((item) => {
                if (item.deviceClassId === equipmentmenuKey.value) {
                    deviceTableData.value.forEach((ele) => {
                        if (ele.id === item.id) {
                            item = ele
                        }
                    })
                    nextTick(() => {
                        deviceTableRef.value?.toggleRowSelection(item, true)
                    })
                }
            })


        }
    } else {
        deviceTableData.value = []
        equipmentPage.value.total = 0
    }
}


//多选
const deviceTableKeys = ref([])
//选中的设备仪器
const checkList = ref([])
const deviceTableSelection = (rows) => {

    // deviceTableKeys.value = rows
    if (rows.length > 0) {
        rows.forEach((item) => {
            checkList.value.push(item)
        })
        //去重
        let uniqueArray = getnewArr(checkList.value)
        deviceTableKeys.value = uniqueArray

    }


}

//确认引用
const deviceModalSave = () => {
    if (deviceTableKeys.value.length > 0) {
        const item = tableFormItemNode.value
        const form = formData.value[item.index]
        const val = []
        const idarr = []
        const listr = []
        deviceTableKeys.value.forEach((item) => {
            val.push(item.deviceNumber)
            idarr.push(item.id)
            listr.push(item.deviceNumber + '_' + item.deviceName)
        })
        const newval = listr.join('、')
        const idval = idarr.join(',')

        formData.value[item.index][item.KeyName] = setPosInsert(item.startPos, item.endPos, form[item.KeyName], newval)
        vesselModal.value = false
        let posVal = item.startPos + newval.length
        nextTick(() => {
            setPosRange(item.KeyName, posVal)
        })
        deviceModal.value = false
        emit('updeviceUseIds', idval)

    } else {
        window?.$message?.warning('请先选择引用容器设备')

    }
    deviceTableKeys.value = []
    checkList.value = []
    temp = []

}
//关闭
const deviceModalClose = () => {
    deviceModal.value = false
    deviceTableKeys.value = []
    checkList.value = []
    temp = []
}


//插入特殊字符
const specialModal = ref(false)
const specialCharacters = ref([
    '&#57344;', '&#57345;', '&#57346;', '&#57347;', '&#8804;', '&#8805;', '&#8451;',
    '&#9312;', '&#9313;', '&#9314;', '&#9315;', '&#9316;', '&#9317;', '&#9318;', '&#9319;', '&#9320;', '&#9321;', '&#9322;', '&#9323;',
    '&#9324;', '&#9325;', '&#9326;', '&#9327;', '&#9328;', '&#9329;', '&#9330;', '&#9331;',
    '&#8544;', '&#8545;', '&#8546;', '&#8547;', '&#8548;', '&#8549;', '&#8550;', '&#8551;', '&#8552;', '&#8553;', '&#8554;', '&#8555;', 'K̅',
])

//输入框验证
const specialFormRef = ref(null)
const specialFormModel = ref({ val: '' })
const specialFormRules = {
    val: {
        required: true,
        trigger: 'blur',
        message: '请选择特殊字符代码',
    },
}
//显示插入特殊字符
const specialRef = ref(null)
const specialModalShow = () => {
    specialFormModel.value.val = ''
    specialModal.value = true
    nextTick(() => {
        specialRef.value?.focus()
    })
}
//失去焦点
const specialPos = ref({ start: 0, end: 0 })
const specialInputBlur = (e) => {
    specialPos.value = {
        start: e?.target?.selectionStart || 0,
        end: e?.target?.selectionEnd || 0,
    }
}
//点击符号
const specialClick = (event) => {
    const text = event?.target?.innerText ?? ''
    const start = specialPos.value.start
    const end = specialPos.value.end
    const form = specialFormModel.value.val
    specialFormModel.value.val = setPosInsert(start, end, form, text)
    specialRef.value?.focus()
    let posVal = start + text.length
    nextTick(() => {
        setPosRange('specialId', posVal)
    })
}

//确认插入
const specialNodeClick = async () => {
    const res = await formValidate(specialFormRef.value)
    if (res) {
        const item = tableFormItemNode.value
        const form = formData.value[item.index]
        const val = specialFormModel.value.val ?? ''
        formData.value[item.index][item.KeyName] = setPosInsert(item.startPos, item.endPos, form[item.KeyName], val)
        specialModal.value = false
        specialRef.value?.focus()
        let posVal = item.startPos + val.length
        nextTick(() => {
            setPosRange(item.KeyName, posVal)
        })
    }
}

//被点击
const getOffsetTop = (key = '') => {
    if (key) {
        const dom = document.getElementById(key)
        emit('offsetTop', dom.offsetTop)
    } else {
        emit('offsetTop', 0)
    }
}

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


}
const changeisHide = (pKeyId, isBussShow, id) => {
    emit('changesdate', pKeyId, isBussShow, id)
}
const chageOrinData = () => {
    emit('chageorinData')
}
//获取表单数据
const getFormData = () => {
    const formArr = formData.value
    return formArr.filter((item) => {
        return item
    })
}

const setFormChart = async () => {
    const form = getFormData()
    for (let i = 0; i < form.length; i++) {
        const { pkeyId, formchartKeyShow } = form[i]
        if (formchartKeyShow) {
            const { ref } = await getChartRef(pkeyId, formchartKeyShow)
            if (ref) {
                const url = await uploadChartImgFile(ref?.getImage())
                const name = `${formchartKeyShow}_url`
                form[i][name] = url
            }
        }
    }
    return form
}

//获取表单效验数据
const getFormRegExpJson = () => {
    return deepClone(formRegExpJson.value)
}

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

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


//打开窗口
const windowClick = (item, indexs)=>{
   if (!item.isWindow) {
    console.log(item, 'item')
    const formSize = getTableFormSize(item?.pKeyId)
    console.log(formSize, 'formSize')
    const list = deepClone(DragModalTableForm.value)
    let index = arrIndex(list, 'pKeyId', item.pKeyId)
    const newTableForm = {
            ...setInitDragModalTableForm(item, indexs),
            ...formSize,

        }
        console.log(newTableForm, 'newTableForm')
    item.isWindow = true
      //弹窗表单的排序
      if (index === -1) {
            list.push(newTableForm)
        } else if (index !== list.length - 1) {
            //检查是否在最上层，不在则置顶，可以解决多次点击时，频繁更改全局状态的问题
            list.splice(index, 1)
            list.push(newTableForm)
        }
        DragModalTableForm.value = list
        ActiveKey.value = ''


            const { pKeyId } = item
    let KeyId = `item-${indexs}-${pKeyId}`
        CollapseChange(KeyId)
   }


}
//获取表单的大小
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 setInitDragModalTableForm = (item, index) => {
    console.log(item, 'item1111')
    return {
        projectId: projectId.value,
        contractId: contractId.value,

        pkeyId: item.pKeyId,
        height: '100%',
        width: '100%',
        title: item.nodeName,
        isShow: true,
        index: index,
        item: item,
    }
}
//关闭窗口
const windowCloseClick = (item, indexs)=>{

    ActiveKey.value = ''


}
const DragModalTableForm = ref([])
const DragModalHeight = ref(600)
const closeIconArr = [
    { key: 'reduction', icon: 'picture-in-picture-2', name: '还原到面板内，并自动展开面板' },
]
//关闭窗口
const TableFormClose = async ({ pkeyId, index }, indexs, type) => {
    const list = deepClone(DragModalTableForm.value)
    //取表单的数据
    // await setChangeFormDatas(pkeyId, 'collapse')
    //关闭窗口
    list.splice(indexs, 1)
    DragModalTableForm.value = list
    listDatas.value[index].isWindow = false
  if (type) {
    ActiveKey.value = ''


  }

}

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

//还原窗口
const closeIconTap = async (event, item, indexs) => {
    item.isShow = false
    item.isWindow = false
    const { index, pkeyId } = item
    let KeyId = `item-${index}-${pkeyId}`
    await TableFormClose(item, indexs, false)

    console.log(item, 'KeyId')
    CollapseChange(KeyId)
    item.isWindow = false

}
//菜单被点击
const dragNodeMoreMenuTap = async ({ key }, items, indexs) => {
    const { item } = items
    console.log(item, 'item')
    console.log(items, 'items')
    if (key === 'save') {
        if (item?.isTableForm) {
            items.tableFormSaveLoading = true
            await tableFormSaveClick(item, indexs)
            items.tableFormSaveLoading = false
        } else {
            window.$message.warning('此表单暂无数据和文件')
        }
    } else if (key === 'preview') {
        if (item.isBussShow === 2 || item.isTabPdf === 1) {
            window.$message.warning('此表单暂无可预览文件')
        } else {
            previewClick(item, items)
        }
    }
}
//清空窗口表单列表
const clearDragModalTableForm = ()=>{
    DragModalTableForm.value = []
}

//下载导入模板
const downloadLoading = ref(false)
const getdownloadExcel = async (pKeyId)=>{
    downloadLoading.value = true
    const { error, disposition, res } = await wbsApi.downloadExcel({ pKeyId: pKeyId })
      //处理数据
      downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}
//下载模板
const downModal = (item)=>{
    const { pKeyId } = item
    getdownloadExcel(pKeyId)
}
//导入表格数据
//导入模板
const dataHcUploadFileRef = ref(null)
const checkItem = ref({})
//打开文件选择框
const uploadFileClick = (item) => {
    checkItem.value = item
    dataHcUploadFileRef?.value[0]?.cancelUpload()
    dataHcUploadFileRef?.value[0].selectFile()
}
//上传配置
const UploadFileOptions = {
    //此处设置header
    headers: getTokenHeader(),
    url: '/api/blade-manager/wbsTreeContract/import-excel',
}



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



// 文件上传成功的回调
const HcUploadFileSuccess = async (res) => {
   const { resData } = res
   const { pKeyId } = checkItem.value
   if (resData) {
       let changeitem = formData.value.filter(item=>item.pkeyId === pKeyId)
       let obj = changeitem[0]
       for (let i in resData) {
            obj[i] = resData[i]
        }
   }

    dataHcUploadFileRef.value[0]?.setModalShow(false)

}

// 暴露出去
defineExpose({
    setFormChart,
    getFormData,
    getFormRegExpJson,
    getActiveKey,
    setActiveKey,
    changeSimpleInput,
    changePositionInput,
    clearDragModalTableForm,
    setCollapseKey,
})
</script>

<style lang="scss" scoped>
.data-fill-list-box {
    position: relative;
    //margin-bottom: 25%;
    .hc-collapse-item-header {
        flex: 1;
        position: relative;
        margin-left: 10px;
        display: flex;
        align-items: center;
        .real-fill-rate {
            position: relative;
            height: 100%;
            line-height: initial;
            margin-right: 18px;
            padding-right: 18px;
            &::after {
                content: "";
                background: #bfc8cf;
                position: absolute;
                right: 0;
                height: 100%;
                width: 1px;
                top: 0;
            }
            .tag {
                position: relative;
                background: white;
                font-size: 12px;
                color: #BD3124;
                padding: 1px 6px;
                border-radius: 3px;
                border: 1px solid #BD3124;
                margin-bottom: 2px;
                margin-top: 2px;
            }
            .tag.yes {
                color: #88CF65;
                border-color: #88CF65;
            }
        }
        .item-title {
            flex: 1;
            position: relative;
            user-select: none;
            color: #591BB7;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
        }
        .hc-extra-text-box {
            position: relative;
            padding-right: 24px;
            line-height: initial;
        }
    }
    .data-fill-list-item-content {
        position: relative;
        height: calc(100vh - 265px);
        .data-fill-table-form-box {
            position: relative;
            padding: 24px 20px;
            height: calc(100% - 36px);
            overflow: auto;
            border: 4px solid #c4c4c4;
            &.is-window {
                border: 0;
                .hc-window-tip {
                    position: relative;
                    height: 100%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    .table-form-no {
                        position: relative;
                        img {
                            width: 380px;
                        }
                        .desc {
                            text-align: center;
                            font-size: 20px;
                            color: #aaa;
                        }
                    }
                }
            }
            .form-window-icon {
                position: absolute;
                top: 10px;
                right: 10px;
                background: #3794FF;
                color: white;
                font-size: 20px;
                width: 32px;
                height: 32px;
                display: flex;
                justify-content: center;
                align-items: center;
                border-radius: 30px;
                cursor: pointer;
                &:hover {
                    background: #204DA0;
                }
            }
            .hc-no-table-form {
                position: relative;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                .table-form-no {
                    position: relative;
                    img {
                        width: 350px;
                    }
                    .desc {
                        text-align: center;
                        font-size: 20px;
                        color: #aaa;
                    }
                }
            }
        }
        .data-fill-table-action {
            position: relative;
            display: flex;
            align-items: center;
            padding: 4px 10px;
            .tip-action {
                cursor: pointer;
                margin-right: 24px;
            }
            .link-action {
                position: relative;
                flex: 1;
            }
            .btn-action {
                position: relative;
            }
        }
    }
}
.special-box {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #eee;
    border-radius: 3px;
    height: 52px;
    width: 52px;
    cursor: pointer;
    user-select: none;
    transition: color .3s, background-color .3s;
    &:hover {
        color: var(--el-color-primary);
        background-color: var(--el-color-primary-light-8);
    }
    .font-EUDC {
        font-size: 22px;
    }
}

.data-fill-table-tip-box {
    position: relative;
    .tip-title {
        font-size: 16px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }
    .tip-item {
        margin-bottom: 20px;
    }
    .table-tip-foot {
        position: absolute;
        bottom: 15px;
        right: 0;
        left: 0;
        display: flex;
        align-items: center;
        padding: 0 15px;
        .tip-left-btn {
            flex: 1;
            .dow-text {
                cursor: pointer;
                display: flex;
                align-items: center;
            }
        }
    }
}
</style>

<style lang="scss">
.data-fill-list-box {
    .el-collapse {
        --el-collapse-header-height: 50px;
        border: 0;
        .el-collapse-item {
            margin: 0 0 6px;
            background-color: #E6EEF4;
            border: 1px solid #E9E9E9;
            border-radius: 4px;
        }
        .el-collapse-item__header {
            background-color: transparent;
            font-weight: 400;
            border-bottom: 0;
            cursor: default;
            font-size: 14px;
            .el-collapse-item__arrow {
                display: none;
            }
        }
        .el-collapse-item.is-active .el-collapse-item__header.is-active {
            background-color: #E7EEF4;
        }
        .el-collapse-item__wrap {
            background-color: transparent;
            border-bottom: 0;
            .el-collapse-item__content {
                position: relative;
                padding-bottom: 0;
                font-size: 14px;
                color: #50545E;
                line-height: initial;
            }
        }
    }
    .hc-collapse-item-header .real-fill-rate .el-link {
        font-size: 12px;
    }
    .el-link {
        text-decoration: underline;
        &:hover {
            text-decoration: auto;
        }
    }
    .el-link + .el-link {
        margin-left: 20px;
    }
}

//插入特殊字符弹窗的输入框
.data-fill-list-box .data-fill-table-form-box td,
.data-fill-list-box .data-fill-table-form-box td .el-input .el-input__wrapper .el-input__inner,
.el-form-item.special-form-item .el-form-item__content .el-input .el-input__wrapper .el-input__inner {
    font-family: "hc-eudc", hc-sans, 宋体, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
//引用容器参数弹窗

//关联试验数据
.adding-form-dialog-box {
    position: relative;
    height: 100%;
    display: flex;
    .dialog-tree-box {
        position: relative;
        border-right: 1px solid #EEEEEE;
        width: 500px;
        height: 100%
    }
    .dialog-table-box {
        position: relative;
        flex: 1;
        height: 100%;
        padding: 18px;
        .dialog-search {
            position: relative;
            display: flex;
        }
        .dialog-table {
            position: relative;
            height: calc(100% - 68px);
            padding: 18px 0;
        }
        .dialog-pages {
            position: relative;
        }
    }
}
.hc-window-switch-box {
            display: flex;
            align-items: center;
            position: absolute;
            top: 14px;
            right: 260px;
            .icon-btn-view {
                padding: 0 18px;
                height: 34px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #ffffff;
                cursor: pointer;
                user-select: none;
                border-radius: 80px;
                box-shadow: 4px 4px 8px 0 rgba(54, 92, 167, 0.15), -3px -2px 8px 0 #ffffff;
                background: linear-gradient(to right, var(--el-color-primary-light-5), var(--el-color-primary), var(--el-color-primary-dark-2));
                background-size: 200%;
                transition: background-position .5s;
                .icon {
                    font-size: 16px;
                }
                &:hover {
                    background-position: 100% 0;
                }
            }
        }
</style>
