<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 :name="`item-${index}-${item?.pKeyId}`" :disabled="item['isBussShow'] === 2" :id="`item-${index}-${item?.pKeyId}`">
                    <template #title>
                        <div class="hc-collapse-item-header">
                            <div class="text-lg truncate item-title">{{item.nodeName}}</div>
                            <div class="hc-extra-text-box">
                                <HcTooltip keys="wbs_del_table" v-if="item['isCopyTab'] === 1">
                                    <el-button type="danger" plain :disabled="item['isBussShow'] === 2" @click.stop="delClick(item,index)" :loading="delClickLoading">删除本表</el-button>
                                </HcTooltip>
                                <HcTooltip keys="wbs_copy_table">
                                    <el-button type="primary" plain :disabled="item['isBussShow'] === 2" @click.stop="copyClick(item,index)" :loading="copyClickLoading">复制本表</el-button>
                                </HcTooltip>
                                <HcTooltip keys="wbs_hide_table">
                                    <el-button type="primary" plain @click.stop="hideClick(item,index)">
                                        <template v-if="item['isBussShow'] === 1">隐藏本表</template>
                                        <template v-else>显示本表</template>
                                    </el-button>
                                </HcTooltip>
                                <HcTooltip keys="wbs_preview_table">
                                    <el-button type="info" plain disabled v-if="item['isBussShow'] === 2 || item['isTabPdf'] === 1">预览</el-button>
                                    <el-button type="primary" plain @click.stop="previewClick(item,index)" v-else>预览</el-button>
                                </HcTooltip>
                                <HcTooltip keys="wbs_upload_table">
                                    <el-button :type="item['tabFileType'] === 2?'success':'primary'" plain :disabled="item['isBussShow'] === 2" @click.stop="uploadClick(item,index)">
                                        <template v-if="item['tabFileType'] === 2">已上传</template>
                                        <template v-else>上传</template>
                                    </el-button>
                                </HcTooltip>
                            </div>
                        </div>
                    </template>
                    <div class="data-fill-list-item-content">
                        <div class="data-fill-table-form-box">
                            <div class="hc-excel-table-form-view" :id="`table-form-${item?.pKeyId}`"/>
                            <div class="hc-no-table-form" v-if="item?.isTableForm === false">
                                <div class="table-form-no">
                                    <img :src="notableform" alt=""/>
                                    <div class="desc">暂无表单数据</div>
                                </div>
                            </div>
                        </div>
                        <div class="data-fill-table-tip-box">
                            <div class="text-orange tip-title">
                                <HcIcon name="error" fill ui="text-2xl"/>
                                <span class="ml-1">提示</span>
                            </div>
                            <div class="text-gray-400 tip-item">1、灰色框代表可通过系统识别计算，公式自动引用，可通过公式计算少量数据，(表头数据及简单)，也可只填写白色框数据</div>
                            <div class="text-gray-400 tip-item">2、系统支持键盘中，shift + tab键向上一个填报框切换，tab向下一个填报框切换。暂不支持上下按键切换输入框</div>
                            <div class="table-tip-foot">
                                <div class="tip-left-btn">
                                    <HcTooltip keys="wbs_import_table">
                                        <div class="text-gray-400 dow-text">
                                            <HcIcon name="publish" ui="text-lg"/>
                                            <span class="ml-1">导入列表数据</span>
                                        </div>
                                    </HcTooltip>
                                    <HcTooltip keys="wbs_download_table">
                                        <div class="text-main dow-text">
                                            <HcIcon name="file_download" ui="text-lg"/>
                                            <span class="ml-1">下载导入模板</span>
                                        </div>
                                    </HcTooltip>
                                </div>
                                <div class="tip-right-btn">
                                    <HcTooltip keys="wbs_save_table">
                                        <el-button type="primary" hc-btn :disabled="NodeStatusval === '3'" :loading="tableFormSaveLoading" @click="tableFormSaveClick(item,index)">
                                            <HcIcon name="save"/>
                                            <span>保存</span>
                                        </el-button>
                                    </HcTooltip>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </template>
        </el-collapse>
    </div>

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

    <!--上传文件-->
    <HcDialog :show="uploadModal" title="上传文件" widths="38rem" :footer="false" @close="uploadModal = false">
        <HcUpload :fileList="fileListData" :datas="uploadData" @change='uploadChange' :tableTypeValue="tableTypeValue" :contractId="contractId" :baseData="baseData"/>
    </HcDialog>

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

    <!--引用容器参数-->
    <HcDialog :show="vesselModal" title="引用容器参数" widths="84%" saveText="确认引用" isTable @close="vesselModalClose" @save="vesselModalSave">
        <div class="adding-form-dialog-box">
            <div class="dialog-tree-box">
                 <el-scrollbar>
                      <HcMenuSimple :datas="menus" :props="menuProps" :keys="menuKey"  @change="menuChange"/>
                 </el-scrollbar>
            </div>
            <div class="dialog-table-box">
                <div class="dialog-table">
                        <HcTable ref="vesselTableRef" :column="vesselTableColumn" :datas="vesselTableData" :loading="vesselTableLoading" isCheck @selection-change="vesselTableSelection"/>
                </div>
                <div class="dialog-pages">
                        <HcPages :pages="vesselTablePage" @change="vesselTablePageChange"/>
                </div>
            </div>
       </div>
    </HcDialog>

    <!--引用设备仪器-->
    <HcDialog :show="deviceModal" title="引用设备仪器" widths="84%" saveText="确认引用" isTable @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" :props="equipmentmenuProps" :keys="equipmentmenuKey"  @change="equipmentmenuChange"/>
                 </el-scrollbar>
            </div>
            <div class="dialog-table-box">
                <div class="dialog-table">
                       <HcTable ref="deviceTableRef" :column="deviceTableColumn" :datas="deviceTableData" :loading="deviceTableLoading" isCheck @selection-change="deviceTableSelection"/>
                </div>
                <div class="dialog-pages">
                        <HcPages :pages="equipmentPage" @change="equipmentTablePageChange"/>
                </div>
            </div>
       </div>
    </HcDialog>

</template>

<script setup>
import {ref,watch,nextTick} from "vue";
import {useAppStore} from "~src/store";
import {useRouter, 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 {utilsText, isType, formValidate, deepClone} from "vue-utils-plus"

const router = useRouter()
const useRoutes = useRoute()
//路由参数
const routerQuery = useRoutes?.query;
const isaddType = routerQuery?.isaddType || false;
//初始
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: () => ([])
    },
    NodeStatus:{
        type: String,
        default: () => ('')
    }
 

    
})

const {isString, getObjNullValue, getArrValue} = isType()
const {setPosInsert, setPosRange} = utilsText()
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)

//监听
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
], ([val, base,NodeIdvalue]) => {
    //1 未填报，2待上报，3已上报
    isStatus.value = val
    baseData.value = base
    nodeIdvaluedata.value=NodeIdvalue
})

//渲染完成
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 setFormDataNum = (datas) => {
    ActiveKey.value = ''
    let newArr = [];
    for (let i = 0; i < datas.length; i++) {
        newArr.push({
            ...getFormDataInit(datas[i]),
            isCollapseLoad: false,
        })
    }
    formData.value = newArr
}
const sampledata=ref([])
const positiondata=ref([])
//展开事件
const ActiveKey = ref('')
const formKeyIds = ref('')
const CollapseChange = async (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)
        console.log(alllistDataval.value,'alllistDataval');
        alllistDataval.value.forEach((item1)=>{
            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)
    } else {
        // await getExcelHtml(item,index)
        getOffsetTop()
        formKeyIds.value = ''
    }
}

//获取模板标签数据
const formRegExpJson = ref({})
const getExcelHtml = async (item,index) => {
    console.log('获取模板数据');
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        const { id } = baseData.value
        console.log(nodeIdvaluedata.value,'nodeIdvaluedata.value');
        const {error, code, data} = await dataApi.getExcelHtml({
            id: id||nodeIdvaluedata.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}`,
                onRight: (event, KeyName) => {
                    onRightClick(event, KeyName, index)
                },
                //表单正则效验
                onBlur: (event, key, reg, val, msg) => {
                    setTableFormBlurReg(pkeyIds, event, key, reg, val, msg, item, 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为空')
    }
}

//正则效验
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=()=>{
    console.log(sampledata.value,'sampledata.value');
      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=()=>{
    console.log(positiondata.value,'positiondata.value');
      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]
                                } 
                            }
                        })
                    })
        console.log(formData.value,'formData.value');
     }
}
const changeSimpleInput=(infodata,id)=>{
    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,
            pkeyId: pkeyIds,
            contractId:contractId
        }, false)
        console.log(item,'item2222');
          emit('changesingSaveId', pkeyIds)
        if(item.oper){
            console.log(11111111);
             HTableForm.setPickerKey([item])
             formData.value[index] = {
                        ...item,
                        isCollapseLoad: true
            }
             getsampleData()
             getPositionData() 
        }else{
            console.log(2222222222);
            data.forEach((item1)=>{
                const resData = getObjNullValue(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() 
                }
            })
 
        }

        // data.forEach((item1)=>{
        //      const resData = getObjNullValue(item1)
        //     if (!error && code === 200 && resData) {
        //         HTableForm.setPickerKey(resData)
        //         const InitObj = getFormDataInit(item) //有数据，关联数据
        //         formData.value[index] = {
        //             ...resData, ...InitObj,
        //             isCollapseLoad: true
        //         }
        //     }else {
        //         formData.value[index] = {
        //             ...getFormDataInit(item),
        //             isCollapseLoad: true
        //         }
        //     }
        // })


        // if (!error && code === 200 && resData) {
        //     HTableForm.setPickerKey(resData)
        //     const InitObj = getFormDataInit(item) //有数据，关联数据
        //     formData.value[index] = {
        //         ...resData, ...InitObj,
        //         isCollapseLoad: true
        //     }
        // } else {
        //     formData.value[index] = {
        //         ...getFormDataInit(item),
        //         isCollapseLoad: true
        //     }
        // }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
const getBussDataInfo1 = async (item, index) => {
    console.log(item,'item');
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        const { id } = baseData.value
        // const {error, code, data} = await dataApi.getBussDataInfo({
        //     id: id||nodeIdvaluedata.value,
        //     pkeyId: pkeyIds
        // }, false)
       
        if(item.oper){
             HTableForm.setPickerKey([item])
             formData.value[index] = {
                        ...item,
                        isCollapseLoad: true
            }
           
        }
        // data.forEach((item1)=>{
        //      const resData = getObjNullValue(item1)
        //     if (!error && code === 200 && resData) {
        //         HTableForm.setPickerKey(resData)
        //         const InitObj = getFormDataInit(item) //有数据，关联数据
        //         formData.value[index] = {
        //             ...resData, ...InitObj,
        //             isCollapseLoad: true
        //         }
        //     }else {
        //         formData.value[index] = {
        //             ...getFormDataInit(item),
        //             isCollapseLoad: true
        //         }
        //     }
        // })


        // if (!error && code === 200 && resData) {
        //     HTableForm.setPickerKey(resData)
        //     const InitObj = getFormDataInit(item) //有数据，关联数据
        //     formData.value[index] = {
        //         ...resData, ...InitObj,
        //         isCollapseLoad: true
        //     }
        // } else {
        //     formData.value[index] = {
        //         ...getFormDataInit(item),
        //         isCollapseLoad: true
        //     }
        // }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
const toBackClick = () => {
    router.push({
        path: '/tentative/detect/test',
        query: {}
    })
    setTimeout(() => {
                            window?.location?.reload()  //刷新页面
      }, 1000);
}
//单个保存
const tableFormSaveLoading = ref(false)
const singleSaveid=ref('')
const tableFormSaveClick = async (item,index) => {
    if (isStatus.value !== '3') {
        console.log(item,'单个保存');
        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{
                    //返回
                    toBackClick()
                }
            
                renewData()
            }
        }
       
    } else {
        window?.$message?.warning('已上报的资料，不允许保存。')
    }
}

//保存表单数据
const saveExcelBussData = async (item, index, showTip = true) => {
    if (!getObjNullValue(formRegExpJson.value)) {
        tableFormSaveLoading.value = true
        const InitObj = getFormDataInit(item)
       baseData.value.tableType= tabTypeKeyInfo.value
       console.log(  baseData.value.tableType,'  baseData.value.tableType');
        const {error, code} = await dataApi.saveExcelBussData({
            ...baseData.value,
            isBatchSave:0,
            dataInfo: {
                orderList: [{...formData.value[index], ...InitObj}]
            }
        })
        //处理数据
        tableFormSaveLoading.value = false
        if (!error && code === 200) {
            if(showTip) window?.$message?.success('保存成功')
            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,
            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}) => {
    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()
            delClickLoading.value=false
        }else{
             delClickLoading.value=false
        }
    } else {
        window?.$message?.warning('pkeyId为空')
         delClickLoading.value=false
    }
}
const copyClickLoading=ref(false)
//复制本表
const copyClick = async (item,index) => {
    console.log(item,'复制item');
    const pkeyIds = getValString(item.pKeyId)
    if (pkeyIds) {
        if (isStatus.value !== '3') {
            if(item.isRenderTableForm&&!item.isCancopy){
                window.$message.warning('请先保存数据再复制本表')
            }else{
                     if (!item.isRenderTableForm) {
                        await copeBussTab(pkeyIds)
                    } else if (!item.isTableForm) {
                        window?.$message?.warning('暂无表单数据')
                    } else if (item.isRenderTableForm) {
                        // const res = await saveExcelBussData(item,index,false)
                        // if (res) {
                        //     await copeBussTab(pkeyIds)
                        // } else {
                        //     window?.$message?.warning('复制本表操作失败')
                        // }
                        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,
        pKeyId: pkeyIds,
        contractId:contractId
    })
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        renewData()
        chageOrinData()
    }
     copyClickLoading.value=false
}

//隐藏本表
const hideClick = async ({pKeyId, isBussShow}) => {
    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()
                changeisHide(pkeyIds,isBussShow)
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许隐藏')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//预览
const previewClick = async (item,index) => {
    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
            console.log(  uploadData.value,'  uploadData.value');
            //获取文件列表
            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}) => {
    if(type === 'success') {
        uploadModal.value = false
        renewData()
    } else if (type === 'del') {
        renewData()
    }
}

//相关变量
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 {id, 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()
}
//数组去重
 var temp = [];
const getnewArr=(tempArr)=> {
   
     tempArr.forEach(function(a) {
        var 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 emit = defineEmits(['renew','offsetTop','updeviceUseIds','upcheckTableId','changesdate','chageorinData','changeIscanclick','changesingSaveId'])

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

//通知数据更新
const renewData = () => {
    emit('renew')
    ActiveKey.value = ''
}
const changeisHide=(pKeyId,isBussShow)=>{
     emit('changesdate',pKeyId,isBussShow)
}
const chageOrinData=()=>{
     emit('chageorinData')
}
//获取表单数据
const getFormData = () => {
    const formArr = formData.value;
    console.log( formData.value,' formData.value');
    // return  formArr.filter(({pkeyId, isCollapseLoad}) => {
    //     return (pkeyId ?? '') !== '' && isCollapseLoad;
    // })
       return  formArr.filter((item) => {
        // return (pkeyId ?? '') !== '' && isCollapseLoad;
       return item
    })
}

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

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

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

// 暴露出去
defineExpose({
    getFormData,
    getFormRegExpJson,
    getActiveKey,
    setActiveKey,
    changeSimpleInput,
    changePositionInput

})

</script>

<style lang="scss" scoped>
.data-fill-list-box {
    position: relative;
    //margin-bottom: 25%;
    .hc-collapse-item-header {
        flex: 1;
        position: relative;
        margin-left: 46px;
        display: flex;
        align-items: center;
        .item-title {
            flex: 1;
            position: relative;
            user-select: none;
            color: #50545E;
            font-size: 16px;
            font-weight: 400;
            cursor: pointer;
        }
        .hc-extra-text-box {
            position: relative;
            padding-right: 24px;
        }
    }
    .data-fill-list-item-content {
        position: relative;
        display: flex;
        height: calc(100vh - 428px);
        .data-fill-table-form-box {
            position: relative;
            padding: 24px 20px;
            height: 100%;
            overflow: auto;
            flex: 1;
            .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-tip-box {
            width: 240px;
            position: relative;
            border-left: 1px solid #E9E9E9;
            padding: 20px 15px 80px;
            .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;
                    }
                }
            }
        }
    }
}
.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;
    }
}
</style>

<style lang="scss">
.data-fill-list-box {
    .el-collapse {
        --el-collapse-header-height: 60px;
        border: 0;
        .el-collapse-item {
            margin: 0 0 16px;
            background-color: #f1f5f8;
            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 {
                position: absolute;
                color: #50545E;
                cursor: pointer;
                left: 20px;
                margin: 0;
            }
        }
        .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;
            }
        }
    }
}

//插入特殊字符弹窗的输入框
.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: "EUDC", 宋体, v-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;
        }
    }
}
</style>
