<template>
    <div class="hc-page-box">
        <HcCard actionUi="text-center">
            <template #header>
                <el-button :type="authBtnTabKey === '1'?'primary':''" hc-btn @click="authBtnTabClick('1')">
                    <HcIcon name="folder-user"/>
                    <span>施工自检</span>
                </el-button>
                <el-button :type="authBtnTabKey === '2'?'primary':''" hc-btn @click="authBtnTabClick('2')">
                    <HcIcon name="folder-shield"/>
                    <span>监理质检</span>
                </el-button>
            </template>
            <template #extra>
                <el-button type="primary" hc-btn @click="linksRelateModalClick" :disabled="listItemData.length <= 0">关联工程用途及部位</el-button>
                <el-button :type="isMixRatioTestIds ? 'primary' : ''" hc-btn :disabled="!isMixRatioTestIds" @click="linksRawModalClick">关联原材检测报告</el-button>
                <el-button type="primary" hc-btn @click="linksSampleModalClick">关联取样</el-button>
            </template>
            <template #search>
                <div class="flex-1">
                    <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange" size="default" :round="false"/>
                </div>
                <div class="hc-search-top-form">
                    <div class="w-40">
                        <el-input v-model="listItemBaseData.trialUserName" placeholder="请输入试验人员" clearable/>
                    </div>
                    <div class="w-36 ml-2" v-if="tabTypeKey === '2'">
                        <el-date-picker type="date" v-model="listItemBaseData.reportDate" class="block" value-format="YYYY-MM-DD" :clearable="false" placeholder="请选择报告日期"/>
                    </div>
                    <div class="w-28 ml-2" v-if="tabTypeKey === '2'">
                        <el-select v-model="listItemBaseData.detectionResult" placeholder="是否合格" block>
                            <el-option label="合格" value="1" />
                            <el-option label="不合格" value="0" />
                        </el-select>
                    </div>
                    <div class="w-36 ml-2">
                        <el-select v-model="listItemBaseData.detectionCategory" placeholder="选择检测类型" block>
                            <el-option v-for="item in categoryData" :label="item['dictValue']" :value="item['dictKey']"/>
                        </el-select>
                    </div>
                </div>
            </template>
            <!--清表列表-->
            <el-scrollbar ref="ListItemScrollRef" v-loading="isLoading" v-if="listItemData.length > 0">
                <ListItem ref="ListItemRef" :datas="listItemData" :status="1" :baseData="listItemBaseData" @offsetTop="ListItemOffsetTop" @renew="getTableDataAll" 
                :deviceUseIds="listDeviceUseIds"
                :authBtnTabKey="authBtnTabKey"
                :tabTypeKey="tabTypeKey"
                 @updeviceUseIds="updeviceUseIds"
                 @upcheckTableId="upcheckTableId"
                />
            </el-scrollbar>
            <template #action>
                <el-button type="primary" hc-btn :disabled="NodeStatus === '3' || listItemData.length <= 0" :loading="tableFormSaveLoading" @click="tableFormSaveClick">
                    <HcIcon name="save"/>
                    <span>保存</span>
                </el-button>
                <el-button hc-btn :loading="reportLoading" @click="reportModalClick" :disabled="NodeStatus === '3' || NodeStatus === '1'" >
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button>
                 <!-- <el-button hc-btn :loading="reportLoading" @click="reportModalClick"  >
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button> -->
                <el-button hc-btn :disabled="NodeStatus === '1'"  :loading="bussPdfsLoading" @click="bussPdfsClick(router.currentRoute.value.query.id)">
                    <HcIcon name="eye"/>
                    <span>预览</span>
                </el-button>
                <el-button hc-btn @click="abolishOneClick" v-if="NodeStatus === '3'">
                    <HcIcon name="arrow-go-back"/>
                    <span>撤回上报流程</span>
                </el-button>
                <el-button hc-btn @click="toBackClick">
                    <HcIcon name="delete-back"/>
                    <span>返回</span>
                </el-button>
            </template>
        </HcCard>

        <!--关联工程用途及部位-->
        <HcDialog :show="linksRelateModal" title="关联工程用途及部位" widths="50rem" isTable saveText="确认关联" @close="linksRelateModalClose" @save="linksRelateModalSave">
            <div class="hc-links-relate-tree-box">
                <div class="hc-search-tree-val">
                    <el-input v-model="linksRelateSearchTreeVal" block size="large" placeholder="请输入名称关键词检索" clearable @keyup="searchTreeKeyUp" @clear="clearSearch">
                        <template #suffix>
                            <HcIcon name="search-2" ui="text-xl"  @click="searchTreeClick"/>
                        </template>
                    </el-input>
                </div>
                <div class="hc-tree-scrollbar" v-loading="linksRelateTreeLoading" element-loading-text="获取数据中...">
                    <el-scrollbar>
                         <!-- <DivisionTree :datas="unmatchedTreeData" @nodeTap="divisionTreeClick" @nodeCheck="divisionTreeCheck" :defaultCheckarr="defaultCheckarrIds"/> -->
                          
                            <template v-if="isSearchTree">
                               <DivisionTree1 
                               :datas="searchTreeData"
                                @nodeTap="divisionTreeClick" 
                                @nodeCheck="divisionTreeCheck" 
                                :defaultCheckarr="defaultCheckarrIds" 
                                :ElTreeProps="seaElTreeProps" 
                                :defaultExpandAll="true" 
                                :check-strictly="true" 
                                :divisionLoading="searchlinksRelateTreeLoading"/>
                            </template>
                            
                               <DivisionTree 
                               v-show="!isSearchTree"
                               :datas="unmatchedTreeData" 
                               @nodeTap="divisionTreeClick"
                                @nodeCheck="divisionTreeCheck"
                                 :defaultCheckarr="defaultCheckarrIds"  
                                :check-strictly="true"  
                                :divisionLoading="isdivisionLoading"
                                :linksRelateSearchTreeVal="linksRelateSearchTreeVal"
                                />
                        
                    </el-scrollbar>
                </div>
            </div>
        </HcDialog>

        <!--关联原材检测报告-->
        <HcDialog :show="linksRawModal" title="关联原材检测报告" widths="75rem" isTable saveText="确认关联" @close="linksRawModalClose" @save="linksRawModalSave">
            <div class="hc-links-sample-modal-box">
                <div class="hc-links-sample-tree-box">
                    <el-scrollbar>
                        <TestTree :projectId="projectId" :wbsTempId="projectInfo?.referenceWbsTemplateIdTrial" :wbsType="2" :tenantId="userInfo?.tenant_id" @nodeTap="linksRawTreeClick"/>
                    </el-scrollbar>
                </div>
                <div class="hc-links-sample-table-box">
                    <HcTable ref="tableRawRef" :column="linksRawTableColumn" :datas="linksRawTableData" :loading="linksRawTableLoading" :isIndex="false" isCheck @selection-change="linksRawTableSelection"/>
                </div>
            </div>
        </HcDialog>

        <!--关联取样-->
        <HcDialog :show="linksSampleModal" title="关联取样信息" widths="75rem" isTable saveText="确认" @close="linksSampleModalClose" @save="linksSampleModalSave">
            <div class="hc-links-sample-modal-box">
                <div class="hc-links-sample-tree-box">
                    <el-scrollbar>
                        <TestTree :projectId="projectId" :wbsTempId="projectInfo?.referenceWbsTemplateIdTrial" :wbsType="2" :tenantId="userInfo?.tenant_id" @nodeTap="linksSampleTreeClick"/>
                    </el-scrollbar>
                </div>
                <div class="hc-links-sample-table-box">
                    <HcTable ref="tableSampleRef" :column="linksSampleTableColumn" :datas="linksSampleTableData" :loading="linksSampleTableLoading" :isIndex="false" isCheck @selection-change="linksSampleTableSelection"/>
                </div>
            </div>
        </HcDialog>
        
        <!--批量上报审批-->
        <HcReportModal  title="批量上报审批" url="informationWriteQuery/taskOne" :show="showReportModal" :projectId="projectId" :contractId="contractId" type="wbs" :typeData="reportTypeData"
        :taskName="reportTaskName" :ids="reportIds" :addition="reportAddition" :trialSelfInspectionRecordId="dataId" @hide="showReportModal = false" @finish="showReportFinish"/>
    </div>
</template>

<script setup>
import {ref, watch, onMounted,nextTick} from "vue";
import {useAppStore} from "~src/store";
import {useRouter, useRoute} from 'vue-router'
import ListItem from "./components/ListItem.vue"
import DivisionTree from "./components/DivisionTree.vue"
import DivisionTree1 from "./components/DivisionTree1.vue"
import dataApi from "~api/tentative/detect/test";
import divisionApi from "~api/data-fill/division";
import queryApi from '~api/data-fill/query';
import {getStoreData,setStoreData} from '~src/utils/storage'
import TestTree from "../material/components/TestTree.vue"
import {getArrValue, getObjValue, getObjNullValue,isString} from "vue-utils-plus";
import {getDictionary} from "~api/other";
import {rowsToId} from "~uti/tools";
import dayjs from "dayjs"
import { Loading } from "element-plus/es/components/loading/src/service";
import { eVisaTaskCheckApi} from "~api/other"
import wbsApi from "~api/data-fill/wbs"


//变量

const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo);
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const contractInfo = ref(useAppState.getContractInfo);
//获取模板标签数据
const isTableForm = ref(false)
//路由参数
const routerQuery = useRoutes?.query;
//存储目录格式 1按部位存储，2按日期存储
const dataId = routerQuery?.id || '';
const nodeId = routerQuery?.nodeId || '';
const dataType = routerQuery?.dataType || '1';
const isaddType = routerQuery?.isaddType || false;

const dayDate = dayjs().format('YYYY-MM-DD')
const testTreeItem = ref(getStoreData('testTreeItem'));
const isMixRatioTestIds = ref(false);
const tabTypeKey = ref('')
//渲染完成
onMounted(() => {
    tabTypeKey.value= routerQuery?.tabTypeKey || '1'
    const { title, mixRatioTestIds} = getObjValue(testTreeItem.value);
     const info = getStoreData('test-form') || {}
    isMixRatioTestIds.value = !(!mixRatioTestIds || mixRatioTestIds <= 0);
    listItemBaseData.value.contractId = contractId.value
    listItemBaseData.value.trialProjectName = title
    listItemBaseData.value.reportDate = dayDate
    listItemBaseData.value.detectionCategory = Number(dataType)
    listItemBaseData.value.trialUserName =info.trialUserName||(userInfo.value['nick_name'])
    if(info&&info.detectionResult){
         listItemBaseData.value.detectionResult=info.detectionResult.toString()
    }
   
    getSearchNodeTables()
    getSearchNodeTablesall(1)
    getSearchNodeTablesall(2)
    getCategoryData()
})

//身份按钮切换数据
const authBtnTabKey = ref(dataType)
const authBtnTabClick = (val) => {
    if (val !== authBtnTabKey.value) {
        authBtnTabKey.value = val
        listItemBaseData.value.type = val
        listItemBaseData.value.detectionCategory = Number(val)
        getSearchNodeTables()
    }
}

//类型tab数据和相关处理
const leftFormData=ref([]) 
const rightFormData=ref([]) 
const allFormData=ref([])
const tabTypeTab = ref([
    {key:'1',  name: '记录表'},
    {key:'2', name: '报告单'},
]);
const tabTypeChange = ({key}) => {
    console.log(key,'切换key');
    // console.log(ListItemRef.value?.getFormData(),'ListItemRef.value?.getFormData()');
    tabTypeKey.value = key
     let curform=ListItemRef.value?.getFormData()
    setAllListData(curform)
    // if(tabTypeKey.value==='2'){
    //     leftFormData.value=ListItemRef.value?.getFormData()
    // }else{
    //       rightFormData.value=ListItemRef.value?.getFormData()
    // }

   
    getSearchNodeTables()
}

//获取检测类别类型
const categoryData = ref([])
const getCategoryData = async () => {
    const { data } = await getDictionary({
        code: 'trial_detection_category'
    })
    const arrData = getArrValue(data)
    arrData.forEach(item => {
        item.dictKey = Number(item.dictKey)
    })
    categoryData.value = arrData
}

//顶部表单
const ListItemRef = ref(null);
const listItemBaseData = ref({
    sampleIds: '', contractId: null, nodeId: nodeId, trialProjectName: null, type: dataType, tableType: '1',
    detectionCategory: '', detectionResult: '', reportDate: '', trialUserName: '', id: dataId,
})

//获取数据
const isLoading = ref(false)
const listItemData = ref([])
const listDeviceUseIds=ref('')
const reportData=ref([])
const testData=ref([])
const alllistData=ref([])
const orgAlllistData=ref([])
const getSearchNodeTables = async () => {
    isLoading.value = true
    if(isaddType){
        const { error, code, data } = await dataApi.searchNodeTables({
            id: dataId,
            projectId: projectId.value,
            contractId: contractId.value,
            primaryKeyId: nodeId,
            type: authBtnTabKey.value,
            tableType: tabTypeKey.value,
            isAdd: 1
        })
          //处理数据
        isLoading.value = false
        if (!error && code === 200) {
            listItemData.value = getArrValue(data)
        } else {
            listItemData.value = []
        }
    }else{
        queryNodeStatus()//查询按钮状态
        const { error, code, data } = await dataApi.searchNodeTables({
            id: dataId,
            projectId: projectId.value,
            contractId: contractId.value,
            primaryKeyId: nodeId,
            type: authBtnTabKey.value,
            tableType: tabTypeKey.value,
            
        })
          //处理数据
        isLoading.value = false
        if (!error && code === 200) {
            listItemData.value = getArrValue(data)
        } else {
            listItemData.value = []
        }
    }
  
  
}
const getSearchNodeTablesall = async (type) => {
  
        const { error, code, data } = await dataApi.searchNodeTables({
            id: dataId,
            projectId: projectId.value,
            contractId: contractId.value,
            primaryKeyId: nodeId,
            type: authBtnTabKey.value,
            tableType: type,
            // isAdd: 1
            isAdd:isaddType?1:''
        })
          //处理数据
        isLoading.value = false
        if (!error && code === 200) {
            // listItemData.value = getArrValue(data)
              if(type===1){
                testData.value= getArrValue(data)
                testData.value.forEach((item)=>{
                    let bussDataInfoTrialData=item.bussDataInfoTrial
                        if(bussDataInfoTrialData&&Object.keys(bussDataInfoTrialData).length!==0){
                            for(var key in bussDataInfoTrialData){
                            console.log(key,bussDataInfoTrialData[key])
                            item[key]=bussDataInfoTrialData[key]
                        }
                    }
                  
                    orgAlllistData.value.push(item)
               
              
                })
            }else{
                 reportData.value= getArrValue(data)
                 reportData.value.forEach((item)=>{
                let bussDataInfoTrialData=item.bussDataInfoTrial
                      if(bussDataInfoTrialData&&Object.keys(bussDataInfoTrialData).length!==0){
                            for(var key in bussDataInfoTrialData){
                            console.log(key,bussDataInfoTrialData[key])
                            item[key]=bussDataInfoTrialData[key]
                        }
                    }
                  
                    orgAlllistData.value.push(item)
                })
            }
        } else {
            // listItemData.value = []
             if(type==1){
                testData.value= []
                 alllistData.value=[]
            }else{
                reportData.value=  []
                alllistData.value=[]
            }
        }
   
  
  
}
//获取数据
const getTableDataAll = () => {
    getSearchNodeTables()
    queryNodeStatus()
}

//设置滚动条位置
const ListItemScrollRef = ref(null)
const ListItemOffsetTop = (offsetTop) => {
    if (offsetTop > 0) {
        setTimeout(() => {
            ListItemScrollRef.value?.setScrollTop(offsetTop)
        }, 350)
    } else {
        ListItemScrollRef.value?.setScrollTop(offsetTop)
    }
}
const checkTabId=ref('')
const upcheckTableId = (val) => {
    checkTabId.value=val
}
//关联工程用途及部位 树
const linksRelateModal = ref(false)
const linksRelateModalClick = () => {
    linksRelateModal.value = true
    linksRelateSearchTreeVal.value=''
    getContractInfoTreeApi()
}

//获取导入树
const unmatchedTreeData = ref([])
const defaultCheckarrIds=ref([])
const isdivisionLoading=ref(false)
const getContractInfoTreeApi = async () => {
    isdivisionLoading.value=true
    const {error, code, data} = await divisionApi.getengineerInfoTree1({
        projectId: projectId.value,
        contractId: contractId.value,
        wbsId: projectInfo?.value.referenceWbsTemplateId,
        selfId:dataId
    })
    //判断状态
    if (!error && code === 200) {
        unmatchedTreeData.value = getArrValue(data['treeContractAll'])
        searchTreeData.value = getArrValue(data['treeContractAll'])
          setStoreData('unmatchedTreeData',  unmatchedTreeData.value)
        
        defaultCheckarrIds.value=getArrValue(data['isSelectedStatus'])
        checkrelationId.value=getArrValue(data['isSelectedStatus'])
    } else {
        unmatchedTreeData.value = []
    }
     isdivisionLoading.value=false
}

//关联树
const divisionTreeItemInfo = ref({})
const divisionTreeClick = ({data}) => {
    divisionTreeItemInfo.value = data
}
const checkrelationId=ref([])
const checkrelationString=ref([])

const divisionTreeCheck = (data) => {
   checkrelationId.value=data
}
const seaElTreeProps = ref({
    label: 'title',
    children: 'children'
})
const linksRelateSearchTreeVal = ref('')
// watch(tabTypeKey, (val) => {
//     if(val){
//          console.log(val);
//         if (val==='1') {
           
//              leftFormData.value=ListItemRef.value?.getFormData()
//         }else{
//              rightFormData.value= ListItemRef.value?.getFormData()
//         }
//     }
   
// },



// )
watch(linksRelateSearchTreeVal, (val) => {
    if(!val.length){
       clearSearch()
    }
   
},



)
const linksRelateTreeLoading = ref(false)
const searchTreeData = ref([])
const searchlinksRelateTreeLoading = ref(false)
const searchTreeKeyUp = (e) => {
    if (e.key === "Enter") {
        searchTreeClick()
    }
}
const clearSearch = (e) => {
      isSearchTree.value=true
      searchlinksRelateTreeLoading.value = true
      setTimeout(()=>{
          searchlinksRelateTreeLoading.value = false
      },3000)
        
}

//树搜索
const isSearchTree = ref(false)
const searchTreeClick = async () => {
    if (linksRelateSearchTreeVal.value) {
          nextTick(()=> {
            isSearchTree.value=false
            
         
        }) 
        
    //   const {error, code, data} = await queryApi.searchContractTree({
    //         contractId: contractId.value,
    //         queryValue: linksRelateSearchTreeVal.value
    //     })
    //     //判断状态
    //     if (!error && code === 200) {
          
    //         searchlinksRelateTreeLoading.value = false
    //     } else {
    //         searchlinksRelateTreeLoading.value = false
    //         searchTreeData.value = []
    //     }
    } 
}
//确认关联
const linksRelateModalSave =async () => {
        let idarr=[]
        checkrelationId.value.forEach((item)=>{
            idarr.push(item.primaryKeyId)
        })
        checkrelationString.value=idarr.toString()
        // listItemBaseData.value.projectPosition=checkrelationString.value
         linksRelateModal.value = false
        //  const { error, code, data } = await dataApi.projectpositionSubmit({
        //     id: dataId,
        //     projectPosition:checkrelationString.value,
        // })
        // if (!error && code === 200) {
        //     window.$message?.success('操作成功')
        //    linksRelateModal.value = false
        // }else {
        //     window.$message?.warning(error)
        //      linksRelateModal.value = false 
        // }   
          
}
const linksRelateModalClose = () => {
    linksRelateModal.value = false
}


//关联原材检测报告
const linksRawModal = ref(false)
const linksRawModalClick = () => {
    linksRawModal.value = true
}
const linkNodeid=ref('')
//树被点击
const linksRawTreeClick = ({data}) => {
    linkNodeid.value=data.primaryKeyId
    getrawMaterialList()
}


//原材检测报告数据
const tableRawRef = ref(null)
const linksRawTableColumn = ref([
    {key:'reportNo', name: '报告编号'},
    {key:'trialProjectName', name: '试验项目名称'},
    {key:'projectPositionName', name: '工程部位及用途'},
    {key:'reportDate', name: '报告日期'}
])
const linksRawTableData = ref([])
const linksRawTableLoading = ref(false)

//多选
const tableRawCheckedKeys = ref([]);
const tableRawCheckedKeysid = ref('');
const linksRawTableSelection = (rows) => {
    tableRawCheckedKeys.value = rows
    let arr=[]
     tableRawCheckedKeys.value.forEach((item)=>{
         arr.push(item.id)
     })
    tableRawCheckedKeysid.value=arr.join()
}

const linksRawModalSave =async () => {
    console.log(tableRawCheckedKeysid.value,'tableRawCheckedKeysid.value');
    //     const { error, code, data } = await dataApi.rawMaterialSubmit({
    //     id: dataId,
    //     ids:tableRawCheckedKeysid.value,
    //     projectId: projectId.value,
    //     contractId: contractId.value,
    //     primaryKeyId: nodeId,
    //     type: authBtnTabKey.value,
    //  })
    // if (!error && code === 200) {
    //         window.$message?.success('操作成功')
    //         tableRawCheckedKeys.value=[]
    //         linksRawModal.value = false
    //         tableRawRef.value?.clearSelection();
    //  }
    //  else {
    //     window.$message?.warning(error)
    //  }   
     
}

//关闭原材检测报告
const linksRawModalClose = () => {
    linksRawModal.value = false
    linksRawTableData.value=[]
    tableRawRef.value?.clearSelection();
}



//关联取样
const linksSampleModal = ref(false)
const linksSampleModalClick = () => {
    linksSampleTableData.value = [];
    linksSampleModal.value = true
}

//搜索表单
const linksSampleSearchForm = ref({
    nodeId: null, current: 1, size: 20, total: 0
})

//树被点击
const linksSampleTreeClick = ({data}) => {
    linksSampleSearchForm.value.nodeId = data.primaryKeyId;
    linksSampleSearchForm.value.current = 1;
    getLinksSampleData()
}

//关联取样数据
const tableSampleRef = ref(null)
const linksSampleTableColumn = ref([
    {key:'materialName', name: '样品名称'},
    {key:'samplingDate', name: '取样日期'},
    {key:'specificationModel', name: '规格型号'},
    {key:'proposedPosition', name: '拟用部位'},
    {key:'userName', name: '取样人'},
])
const linksSampleTableData = ref([])

//获取关联数据
const linksSampleTableLoading = ref(false)
const getLinksSampleData = async () => {
    linksSampleTableLoading.value = true
    const { error, code, data } = await dataApi.sampleListInfo({
        ...linksSampleSearchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
        id:dataId
    })
    //处理数据
    linksSampleTableLoading.value = false
    if (!error && code === 200) {
        linksSampleTableData.value = getArrValue(data)
         linksSampleTableData.value.forEach((iten)=>{
             if(iten.isRelation===1){
                 nextTick(()=>{
                    tableSampleRef.value?.toggleRowSelection(iten,true);
                })
                    
             }
         })
        //searchForm.value.total = data.total || 0
    } else {
        linksSampleTableData.value = []
        //searchForm.value.total = 0
    }
}
//获取关联原材料检测报告
const getrawMaterialList = async () => {
    linksRawTableLoading.value = true
    const { error, code, data } = await dataApi.rawMaterialList({
        nodeId: linkNodeid.value,
        contractId: contractId.value,
        id:dataId
    })
    //处理数据
    linksRawTableLoading.value = false
    if (!error && code === 200) {
        linksRawTableData.value = getArrValue(data)
         linksRawTableData.value.forEach((iten)=>{
             if(iten.isRawMaterialRelation===1){
                 nextTick(()=>{
                    tableRawRef.value?.toggleRowSelection(iten,true);
                })
                    
             }
         })
        //searchForm.value.total = data.total || 0
    } else {
        linksRawTableData.value = []
        //searchForm.value.total = 0
    }
}
//多选
const tableSampleCheckedKeys = ref([]);
const linksSampleTableSelection = (rows) => {
    tableSampleCheckedKeys.value = rows
}

//保存关联
const linksSampleModalSave =async () => {
    const rows = tableSampleCheckedKeys.value
    
        listItemBaseData.value.sampleIds = rowsToId(rows) || '';
        console.log( rowsToId(rows),' rowsToId(rows)');
         const { error, code, data } = await dataApi.recordsampleSubmit({
            id: dataId,
            sampleIds:rowsToId(rows) || '',
        })
         if (!error && code === 200) {
            window.$message?.success('操作成功')
            tableSampleRef.value?.clearSelection();
     }
     else {
        // window.$message?.warning(error)
     }  
        
        tableSampleCheckedKeys.value = [];
        linksSampleModal.value = false
    
}

//关闭关联取样
const linksSampleModalClose = () => {
    linksSampleModal.value = false
}

//保存
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async () => {
    // console.log(listItemBaseData.value,'.listItemBaseData.value');
  
    //false是编辑
    //编辑要传记录和报告单
      if(checkrelationString.value.length>0){
        listItemBaseData.value.projectPosition=checkrelationString.value
      }
    if(tabTypeKey.value==='2'&&listItemBaseData.value.detectionResult===''){
         window.$message?.warning('请选择报告单是否合格')
    }else{
            // let FormData = ListItemRef.value?.getFormData()
  
   
          
            let FormData
         
            let curform=ListItemRef.value?.getFormData()
            setAllListData(curform)
            // alllistData.value.forEach((item)=>{
            //    if(item.pKeyId===item1.pkeyId){
                
            console.log(orgAlllistData.value, "orgAlllistData");
            let operTrue = alllistData.value.filter(e => e.oper); //操作的数据
            let types = []
            operTrue.forEach(e => {
                    types.push(e.type);
            })
            let setTypes = Array.from(new Set(types))
            let type = setTypes[0];
            if (setTypes.length > 1 || !isaddType) {
                 FormData = alllistData.value;
                 listItemBaseData.value.tableType = "1,2"

                 if (!isaddType && setTypes.length <= 1) { //没有切换的时候，需要添加没切换的数据
                   //编辑的时候，什么都不操作，原有type为undefined，需取当前页面type
                    type = setTypes.length == 0 ? alllistData.value[0].type : type; 

                    let notChangeData = orgAlllistData.value.filter(e => e.tableType !== type);
                    notChangeData.forEach(item => {
                        let data = {
                            projectId: item.projectId,
                            contractId: contractId.value,
                            pkeyId: item.pKeyId,
                            nodeId: routerQuery?.nodeId,
                            isCollapseLoad: false
                        }
                        // 过滤存在的key_的键值
                        let ishasKey=  Object.keys(item).filter(e => e.indexOf("key_") >= 0)
                        if (ishasKey.length > 0) {
                            ishasKey.forEach(key => {
                                data[key] = item[key]
                            })
                        }

                        console.log(data, "notChangeData");
                        FormData.push(data)
                    })
                 }
            } else {
                FormData = alllistData.value.filter(e => e.type == type); 
                listItemBaseData.value.tableType = type
            }
                
        
            let FormRegExpJson = ListItemRef.value?.getFormRegExpJson()
               console.log(isaddType,'isaddType');
            //效验数据
          
            if (FormData.length > 0) {
              if(  listItemBaseData.value.detectionResult===''&& listItemBaseData.value.tableType == "1,2"){
                   window.$message?.warning('请选择报告单是否合格')
              }else{
                    tableFormSaveLoading.value = true
                const {error, code,data} = await dataApi.saveExcelBussData({
                    ...listItemBaseData.value,
                    isBatchSave:1,
                    dataInfo: {orderList: FormData},
                    // deviceUseIds:listDeviceUseIds.value
                })
             
                nodeIdvalue.value=data
                tableFormSaveLoading.value = false
                if (!error && code === 200) {
                    window?.$message?.success('保存成功')
                    listItemBaseData.value.deviceUseIds=''
                    checkTabId.value=''
                    // alllistData.value.forEach(e => e.oper = false)
                     alllistData.value=[]
                    if(!isaddType){
                        bussPdfsClick(router.currentRoute.value.query.id)
                    }else{
                        bussPdfsClick(nodeIdvalue.value)
                        // toBackClick()
                    }
                
                    getTableDataAll()
                }
              }
              
            } else {
                
                if(!isaddType){
                        window.$message?.warning('请先选择你需要编辑的表格')
                    bussPdfsClick(router.currentRoute.value.query.id)
                }else{
                    window.$message?.warning('请先选择你需要新增的表格')
                }
                
            
            }
    }
    
}

const setAllListData = (curform) => {
    console.log(curform,'setAllListData curform');
     curform.forEach((item)=>{
        let pkeyId = item.pkeyId;
        item.oper = false
        let ishasKey=  Object.keys(item).filter(e => e.indexOf("key_") >= 0)
        if (ishasKey.length>0) { //筛出当前编辑过的数据
            item.oper = true
        } 

        let types = orgAlllistData.value.filter(e => e.pKeyId === pkeyId);
        item.type = types[0].tableType;
        alllistData.value = alllistData.value.filter(e => e.pkeyId != pkeyId); //去掉老数据
        alllistData.value.push(item) //加入新数据
    })

   console.log(alllistData.value,'setAllListData alllistData');
}

//效验数据
const setFormRegExpJson = (FormRegExpJson) => {
    let nodeName = '', itemId = '';
    Object.keys(FormRegExpJson).forEach(key => {
        const name = FormRegExpJson[key]?.nodeName ?? ''
        if (name) {
            if (nodeName) {
                nodeName += ',' + name
            } else {
                nodeName = name
                itemId = FormRegExpJson[key]?.itemId
            }
        }
    })
    //const activeKey = ListItemRef.value?.getActiveKey()
    //弹出提示
    const val = '<div style="font-size: 16px;">请先完善  <span style="color:#1ECC95;">' + nodeName + '</span>  的数据内容</div>'
    window?.$messageBox?.alert(val, '表单完善提醒', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        callback: (action) => {
            if (action === 'confirm') {
                ListItemRef.value?.setActiveKey(itemId)
                ListItemOffsetTop(0)
                setTimeout(() => {
                    const offsetTop = document.getElementById(itemId)?.offsetTop
                    ListItemOffsetTop(offsetTop)
                }, 350)
            }
        }
    })
}
//获取数据列表


const nodeItemInfo = ref({})
const nodeDataInfo = ref({})
//查询状态
const NodeStatus = ref('1')
const queryNodeStatus = async () => {
    const info = getStoreData('prenodeDataInfo') || {}
    const {error, code, data} = await wbsApi.queryNodeStatusTrial({
        // primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
        id: dataId,
        classify: authBtnTabKey.value
    })
    //1 未填报，2待上报，3已上报
    if (!error && code === 200) {
        NodeStatus.value = data ?? '1'
    } else {
        NodeStatus.value = '1'
    }
}
//批量上报
const reportIds = ref('')
const reportTaskName = ref('')
const reportAddition = ref({})
const showReportModal = ref(false)
const reportLoading = ref(false)
const reportTypeData = ref([])

// const reportModalClick = async () => {
//      showReportModal.value = true
// }

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableDataAll()
}


const reportModalClick = async () => {
    const info = getStoreData('prenodeDataInfo') || {}
    console.log(info,'info');
    const rows = listItemData.value;
    if (rows.length > 0) {
        reportLoading.value = true
        const taskCheck = await eVisaTaskCheckApi({
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
        let newArr = [];
        // console.log(rows,'rows');
        for (let i = 0; i < rows.length; i++) {
            newArr.push(rows[i]['pKeyId'])
        }
        reportTypeData.value = newArr
        reportLoading.value = false
        if (taskCheck) {
            //初始弹出弹窗，防呆
            // reportIds.value = info['primaryKeyId'] dataId
             reportIds.value = dataId
            reportAddition.value = {
                classify: authBtnTabKey.value,
                contractIdRelation: info['contractIdRelation'],
            }
            showReportModal.value = true
            //请求文件题名
            const {data} = await wbsApi.queryDocumentTitle({
                // primaryKeyId: info['primaryKeyId'],
                 primaryKeyId:dataId,
                classify: authBtnTabKey.value
            })
            reportTaskName.value = isString(data)? data : ''
        }
    } else {
        window.$message?.warning('暂无相关数据')
    }
}
//多表预览
const bussPdfsLoading = ref(false)
const nodeIdvalue=ref('')
const bussPdfsClick = async (nodeId) => {
    bussPdfsLoading.value = true
    const {error, code, data} = await dataApi.getBussPdfs({
        projectId: projectId.value,
        contractId: contractId.value,
        classify: authBtnTabKey.value,
        tableType: tabTypeKey.value,
        // nodeId: router.currentRoute.value.query.id,
          nodeId: nodeId,
    })
    bussPdfsLoading.value = false
    if (!error && code === 200) {
        window.open(data,'_blank')
    } else {
        window.$message?.warning('获取PDF失败')
    }
}

//撤回上报流程
// const abolishOneClick = () => {
//     window.$message?.warning('暂无接口')
// }
//撤回上报流程
const abolishOneClick = () => {
    window?.$messageBox?.alert('请谨慎考虑后，是否确定撤回？', '撤回上报', {
        showCancelButton: true,
        confirmButtonText: '确定撤回',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                abolishOneSave()
            }
        }
    })
}
//撤回请求
const abolishOneSave = async () => {
    const info = getStoreData('prenodeDataInfo') || {}
    const {error, code} = await wbsApi.abolishOne({
        // primaryKeyId:  info?.primaryKeyId || '',
          primaryKeyId: dataId,
        classify: authBtnTabKey.value
    })
    if (!error && code === 200) {
        window.$message?.success('撤回成功')
        getTableDataAll()
    }
}
//返回
const toBackClick = () => {
    router.push({
        path: '/tentative/detect/test',
        query: {}
    })
}
const updeviceUseIds = (val) => {
    listItemBaseData.value.deviceUseIds=val
}

</script>

<style lang="scss" scoped>
@import "../../../styles/tentative/detect/test-form.scss";
</style>
