<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"
                 @changesingSaveId="changesingSaveId"
                 @changeIscanclick="changeIscanclick"
                 :nodeIdvalue="nodeIdvalue"
                 :alllistData="alllistData"
                 @changesdate="changeorinsdate"
                 @chageorinData="chageorinData"
                 :NodeStatus="NodeStatus"
              
                />
            </el-scrollbar>
            <template #action>
                <div class="hc-table-form-action-tip">
                            <el-alert title="完善资料填写后记得一定要保存哦"
                                      show-icon
                                      type="warning"
                                      :closable="false"
                                      class="hc-alert"
                                      style=""/>
                </div>
                <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||nodeIdvalue)">
                    <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">
                        <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"/> -->
                          
                    
                               <DivisionTree1 
                               v-show="isSearchTree"
                               :datas="searchTreeData"
                                @nodeTap="divisionTreeClick" 
                                @nodeCheck="divisionTreeCheck" 
                                :defaultCheckarr="defaultCheckarrIds" 
                                :ElTreeProps="seaElTreeProps" 
                                :defaultExpandAll="true" 
                                :divisionLoading="searchlinksRelateTreeLoading"/>
                        
                            
                               <DivisionTree 
                                
                               ref="divisionTree"
                               v-show="!isSearchTree"
                               :datas="unmatchedTreeData" 
                               @nodeTap="divisionTreeClick"
                                @nodeCheck="divisionTreeCheck"
                                 :defaultCheckarr="defaultCheckarrIds"  
                                :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>
                        <test-tree-material :projectId="projectId" :wbsTempId="projectInfo?.referenceWbsTemplateIdTrial" :wbsType="2" :tenantId="userInfo?.tenant_id" @nodeTap="linksRawTreeClick" :fromType="true" :nodeId="nodeId"
                        :MixRatioTestTreeData="MixRatioTestTreeData"
                        />
                    </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.length>0?dataId:nodeIdvalue"  @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 samplingApi from "~api/tentative/material/sampling"
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 TestTreeMaterial from "../material/components/TestTreeMaterial.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 divisionTree=ref(null)
//获取模板标签数据
const isTableForm = ref(false)
//路由参数
const routerQuery = useRoutes?.query;
//存储目录格式 1按部位存储，2按日期存储
const dataId = routerQuery?.id || '';
const nodeId = routerQuery?.nodeId || '';
const dataType = routerQuery?.dataType || '1';
let isaddType = routerQuery?.isaddType || false;
const afterAdd=ref(false)
const dayDate = dayjs().format('YYYY-MM-DD')
const testTreeItem = ref(getStoreData('testTreeItem'));
const isMixRatioTestIds = ref(false);
const tabTypeKey = ref('')
const isopersampleIds=ref(false)
//渲染完成
onMounted(() => {
    tabTypeKey.value= routerQuery?.tabTypeKey || '1'
    const { title, mixRatioTestIds} = getObjValue(testTreeItem.value);
     const info = getStoreData('test-form') || {}
     console.log(info,'info');
    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.detectionCategory = info.detectionCategory||1
    listItemBaseData.value.trialUserName =info.trialUserName||(userInfo.value['nick_name'])

    listItemBaseData.value.projectPosition = info.projectPosition||''
    listItemBaseData.value.rawMaterialIds = info.rawMaterialIds||''
    listItemBaseData.value.sampleIds = info.sampleIds||''

    if(info&&info.detectionResult){
         listItemBaseData.value.detectionResult=info.detectionResult.toString()
    }
    if(info&&info.projectPosition){
        defaultCheckarrIds.value=info.projectPosition.split(',')
        
    }
    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()
     console.log(curform,'curform');
    setAllListData(curform)
    if( listItemBaseData.value.detectionResult===''&&tabTypeKey.value==2){
          window.$message?.warning('请选择报告单是否合格')
    }
    // 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.length>0?dataId:nodeIdvalue.value,
            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)
              listItemData.value.forEach((item)=>{
                if(item.pKeyId=== singSaveId.value){
                    item.isCancopy=true
                }
            }
                
            )
            
            // console.log( listItemData.value,' listItemData.value');
            // defaultCheckarrIds.value= listItemData.value.projectPosition.join(',')
        } 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)
            listItemData.value.forEach((item)=>{
                if(item.pKeyId=== singSaveId.value){
                    item.isCancopy=true
                }
            }
                
            )
        } else {
            listItemData.value = []
        }
    }
  
  
}
const getSearchNodeTablesall = async (type) => {
   orgAlllistData.value=[]
        const { error, code, data } = await dataApi.searchNodeTables({
            id: dataId.length>0?dataId:nodeIdvalue.value,
            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){
                            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 changeorinsdate=(pKeyId,isBussShow)=>{
    orgAlllistData.value.forEach((item)=>{
        if (item.pKeyId===pKeyId) {
             const isBussShows = isBussShow === 2 ? 1 : 2 //状态(1显示 2隐藏)
            item.isBussShow=isBussShows
        }
    })
    console.log( orgAlllistData.value,' orgAlllistData.value');
}
//复制本表改变原始数据
const chageorinData=()=>{
    getSearchNodeTablesall(1)
    getSearchNodeTablesall(2)
}
//设置滚动条位置
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 singSaveId=ref('')
const  iscanclick=ref(true)
const changeIscanclick=(id)=>{
     iscanclick.value=false
}
const changesingSaveId=(id)=>{
     singSaveId.value=id
     console.log(id,'idsave');
}
//关联工程用途及部位 树
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: 'fullName',
    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){
        isSearchTree.value=!isSearchTree.value
           
    }
   
},



)
const linksRelateTreeLoading = ref(false)
const searchTreeData = ref([])
const searchlinksRelateTreeLoading = ref(false)
const searchTreeKeyUp = (e) => {
    if (e.key === "Enter") {
        searchTreeClick()
    }
}


//树搜索
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()
        if( checkrelationString.value.length>0){
               listItemBaseData.value.projectPosition=checkrelationString.value
        }

        let infodata= await getpositiondata()
        ListItemRef.value.changePositionInput(infodata)
      window.$message?.success('操作成功')
     linksRelateModal.value = false
   
          
}
const linksRelateModalClose = () => {
    linksRelateModal.value = false
}


//关联原材检测报告
const linksRawModal = ref(false)
const MixRatioTestTreeData=ref([])
const linksRawModalClick = () => {
    linksRawModal.value = true
    getTreeData()
}
const getTreeData=async(node,reslove)=>{
        const {error, code, data} = await samplingApi.getMixRatioTestTree({
            pKeyId: nodeId,
        })
         MixRatioTestTreeData.value = getArrValue(data)
}

const linkNodeid=ref('')
//树被点击
const linksRawTreeClick = ({data}) => {
    linkNodeid.value=data.pKeyId
    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 () => {
     linksRawModal.value = false
     listItemBaseData.value.rawMaterialIds=tableRawCheckedKeysid.value
       window.$message?.success('操作成功')
    //     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) || '';
        window.$message?.success('操作成功')
        isopersampleIds.value=true
         let infodata= await getrecordsamplegetData()
        ListItemRef.value.changeSimpleInput(infodata,checkTabId.value)
        tableSampleCheckedKeys.value = [];
       
        linksSampleModal.value = false
    
}
//获取关联取样信息key值
const getrecordsamplegetData = async() => {
    const { error, code, data } = await dataApi.recordsamplegetData({
        sampleIds:   listItemBaseData.value.sampleIds,
        nodePKeyId:routerQuery?.nodeId,
        contractId:contractId.value
        
    })
    return data
}
//获取关联工程部位key值
const getpositiondata = async() => {
    const { error, code, data } = await dataApi.recordprojectPositiongetData({
        projectPositionIds: listItemBaseData.value.projectPosition,
        nodePKeyId:routerQuery?.nodeId,
        contractId:contractId.value
        
    })
    return data
}
//关闭关联取样
const linksSampleModalClose = () => {
    linksSampleModal.value = false
}

//保存
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async () => {
    // console.log(listItemBaseData.value,'.listItemBaseData.value');
  
    //false是编辑

    
    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, "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.length > 0 ? setTypes[0] : "";
            
           if (isaddType) { //新增
                if (setTypes.length > 1) {
                    FormData = alllistData.value;
                    listItemBaseData.value.tableType = "1,2"
                } else {
                   
                    // FormData = alllistData.value.filter(e => e.type == type); 
                    if(!afterAdd.value){
                         FormData = alllistData.value.filter(e => e.type == type); 
                    }else{
                        let filterType=type?type:tabTypeKey.value
                        //   FormData =alllistData.value.filter(e => e.type == type);
                         FormData =alllistData.value.filter(e => e.type == filterType);
                                  orgAlllistData.value.forEach((item1)=>{
                                    if(item1.tableType.toString()!==tabTypeKey.value){
                                            let data1 = {
                                                projectId: item1.projectId,
                                                contractId: contractId.value,
                                                pkeyId: item1.pKeyId,
                                                nodeId: routerQuery?.nodeId,
                                                isCollapseLoad: false,
                                                isBussShow:item1.isBussShow
                                            }
                                            // 过滤存在的key_的键值
                                            let ishasKey=  Object.keys(item1).filter(e => e.indexOf("key_") >= 0)
                                            if (ishasKey.length > 0) {
                                                ishasKey.forEach(key => {
                                                    data1[key] = item1[key]
                                                })
                                            }
                                        FormData.push(data1)
                                    }
                                })
                    }
                    listItemBaseData.value.tableType = type
                }
           } 
           else { //编辑
           console.log(alllistData.value,'alllistData.value');
                FormData = alllistData.value;

                const info = getStoreData('test-form')
                let recordNo = info.recordNo
                let reportNo = info.reportNo

                //组装type
                if (recordNo ==='' && reportNo !=='') {
                    listItemBaseData.value.tableType = "2"
                } else if (recordNo !=='' && reportNo ==='') {
                    listItemBaseData.value.tableType = "1"
                } else {
                     listItemBaseData.value.tableType = "1,2"
                }

                console.log(listItemBaseData.value.tableType,"listItemBaseData.value.tableType ");

                let notChangeData = []
                if (setTypes.length == 0) { //没操作过页面数据
                    FormData = []
                    notChangeData = orgAlllistData.value //默认就是原始左右全部数据
                    if (listItemBaseData.value.tableType.length === 1) { //从原始数据过滤当前页面数据
                        notChangeData = orgAlllistData.value.filter(e => e.tableType === listItemBaseData.value.tableType);
                    }
    
                } 
                else if (setTypes.length == 1) {// 操作过一边的数据
                console.log(FormData,'FormData1');
                 orgAlllistData.value.forEach((item1)=>{
                     if(item1.tableType.toString()!==tabTypeKey.value){
                            let data1 = {
                                projectId: item1.projectId,
                                contractId: contractId.value,
                                pkeyId: item1.pKeyId,
                                nodeId: routerQuery?.nodeId,
                                isCollapseLoad: false,
                                isBussShow:item1.isBussShow
                            }
                             // 过滤存在的key_的键值
                            let ishasKey=  Object.keys(item1).filter(e => e.indexOf("key_") >= 0)
                            if (ishasKey.length > 0) {
                                ishasKey.forEach(key => {
                                    data1[key] = item1[key]
                                })
                            }
                         FormData.push(data1)
                     }
                 })
                  console.log(FormData,'FormData22222222');
                    let tableTypeArr = listItemBaseData.value.tableType.split(",");
                    if (tableTypeArr[0] != type) { //两边都有数据/当前操作的数据不是进来时的选项，筛选另一边的数据
                        listItemBaseData.value.tableType = "1,2"
                    }
                } else { //两边都操作
                    listItemBaseData.value.tableType = "1,2"
                }
                notChangeData.forEach(item => {
                    let data = {
                        projectId: item.projectId,
                        contractId: contractId.value,
                        pkeyId: item.pKeyId,
                        nodeId: routerQuery?.nodeId,
                        isCollapseLoad: false,
                        isBussShow:item.isBussShow
                    }
                    // 过滤存在的key_的键值
                    let ishasKey=  Object.keys(item).filter(e => e.indexOf("key_") >= 0)
                    if (ishasKey.length > 0) {
                        ishasKey.forEach(key => {
                            data[key] = item[key]
                        })
                    }
                    FormData.push(data)
                })
           }
        
            let FormRegExpJson = ListItemRef.value?.getFormRegExpJson()
               console.log(isaddType,'isaddType');
               console.log(FormData,'FormData1111111111');

                if(isaddType&&FormData.length==0||!isaddType&&FormData.length==0){
                    console.log('什么都不操作新增或者编辑');
                    if(tabTypeKey.value ==1){
                      FormData=alllistData.value.filter((itenel)=>{
                           return itenel.type==1
                      })

                  }else if(tabTypeKey.value ==2){
                       FormData=alllistData.value.filter((itenel)=>{
                           return itenel.type==2
                      })
                  }else{
                      FormData=alllistData.value
                  }
                   listItemBaseData.value.tableType=tabTypeKey.value
                }
            //效验数据
            if (FormData.length > 0) {
              if(  listItemBaseData.value.detectionResult===''&& listItemBaseData.value.tableType == "1,2"){
                   window.$message?.warning('请选择报告单是否合格')
              }else{
                    tableFormSaveLoading.value = true
                    console.log(listItemData.value,'listItemData.value');
                    if(listItemData.value.id&&listItemData.value.id.length<0){
                        listItemData.value.id=dataId
                    }
                    console.log(FormData,'lastFormData');
                    //过滤掉已经隐藏表的数据
                   FormData= FormData.filter((item)=>{
                        if(item.isBussShow!==2){
                            return item
                        }
                    })
                    console.log(FormData,'lastFormData1');
                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)
                        //   toBackClick()
                         getSearchNodeTables()
                         getSearchNodeTablesall(1)
                         getSearchNodeTablesall(2)
                    }else{
                          listItemBaseData.value.id=data
                    bussPdfsClick(nodeIdvalue.value)
                     getSearchNodeTables()
                     getSearchNodeTablesall(1)
                     getSearchNodeTablesall(2)
                        afterAdd.value=true
                    // toBackClick()
                    //  setTimeout(() => {
                    //         window?.location?.reload()  //刷新页面
                    //  }, 1000);
                       
                    }
                
                    getTableDataAll()
                }
              }
              
            }   
             
    }
    
}

const setAllListData = (curform) => {
    if(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 orgData = orgAlllistData.value.filter(e => e.pKeyId === pkeyId);
        item.type = orgData[0]?.tableType;
        alllistData.value = alllistData.value.filter(e => e.pkeyId != pkeyId); //去掉老数据
        
        ishasKey=  Object.keys(orgData[0]).filter(e => e.indexOf("key_") >= 0)
        if (!item.isCollapseLoad && ishasKey.length>0) { //没操作过，并且存在KEY
            ishasKey.forEach(key => {
                item[key] = orgData[0][key]
            })
        }

        alllistData.value.push(item) //加入新数据
    })
    }
     

}

//效验数据
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.length>0?dataId:nodeIdvalue.value,
        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.length>0?dataId:nodeIdvalue.value
            reportAddition.value = {
                classify: authBtnTabKey.value,
                contractIdRelation: info['contractIdRelation'],
            }
            showReportModal.value = true
            //请求文件题名
            const {data} = await wbsApi.queryDocumentTitle({
                // primaryKeyId: info['primaryKeyId'],
                 primaryKeyId:dataId.length>0?dataId:nodeIdvalue.value,
                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.length>0?dataId:nodeIdvalue.value,
        classify: authBtnTabKey.value
    })
    if (!error && code === 200) {
        window.$message?.success('撤回成功')
        getTableDataAll()
    }
}
//返回
const toBackClick = () => {
    router.push({
        path: '/tentative/detect/test',
        query: {}
    })
      setTimeout(() => {
                            window?.location?.reload()  //刷新页面
      }, 1000);
}
const updeviceUseIds = (val) => {
    listItemBaseData.value.deviceUseIds=val
}

</script>

<style lang="scss" scoped>
@import "../../../styles/tentative/detect/test-form.scss";
.hc-table-form-action-tip {
    position: absolute;
    bottom: 77px;
    width: 100%;
}
.hc-table-form-action-tip .hc-alert {
    background-color:#f1f5f8;
    display: inline;
    vertical-align: middle;
    box-shadow: -2px 0 10px 0 rgba(32,37,50,0.03), 0 10px 21px 20px rgba(32,37,50,0.03);
}
</style>
