<template>
    <div class="radio-box">
        <el-radio-group v-model="fileModalradio" @change="radioChange">
            <el-radio value="test">试验检测</el-radio>
            <el-radio :value="1">第三方检测</el-radio>
            <el-radio :value="0">外委检测</el-radio>
        </el-radio-group>
    </div>
    <div class="adding-form-dialog-box">
        <div class="dialog-tree-box">
            <el-scrollbar>
                <!-- 试验检测树 -->
                <HcLazyTree
                    ref="ElTreeRefCy"
                    :auto-expand-keys="treeAutoExpandKeys"
                    tree-key="id"
                    :h-props="treeProps"
                    @load="treeLoadNode"
                    @node-tap="fileModalElTreeClick"
                />
            </el-scrollbar>
        </div>
        <div class="dialog-table-box">
            <div class="dialog-search">
                <div class="ml-2 w-64">
                    <HcDatePicker :dates="filebetweenTime" clearable @change="filebetweenTimeUpdate" />
                </div>
                <div class="ml-2">
                    <el-button type="primary" @click="filesearchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </div>
            <div class="dialog-table">
                <HcTable
                    ref="dialogTableRef1" :column="filedialogTableColumn"
                    :datas="filedialogTableData" :loading="filedialogTableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="filedialogTableSelection1"
                >
                    <template #reportNo="{ row }">
                        <span :class="[row?.isSelectedStatus == 1 ? 'text-green' : '']">{{ row?.reportNo }}</span>
                    </template>
                </HcTable>
            </div>
            <div class="dialog-pages">
                <HcPages :pages="filesearchFormPage" @change="filesearchFormPageChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue } from 'js-fast-way'

import thirdApi from '~api/tentative/detect/third'
import samplingApi from '~api/tentative/material/sampling'


const props = defineProps({
    projectId: [String, Number],
    contractId: [String, Number],
    wbsId: [String, Number],
    tenantId: [String, Number],
    wbsType: [String, Number],
    treeId: [String, Number],
  
})

const projectId = ref(props.projectId)
const contractId = ref(props.contractId)

const wbsTempId = ref(props.wbsId)
const tenant_id = ref(props.tenantId)
const wbs_type = ref(props.wbsType)
const isPrimaryKeyId = ref(props.treeId)
const treeProps = {
    label: 'name',
    children: 'children',
     isLeaf: function (data) {
          return !data.hasChildren
    },
}
const treeAutoExpandKeys = ref([])

const ElTreeRefCy = ref(null)


//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.wbsId,
    props.tenantId,
    props.wbsType,
    props.treeId,
 
], ([pid, cid, wbs_id, tid, type, treeId]) => {
    projectId.value = pid
    contractId.value = cid
    wbsTempId.value = wbs_id
    tenant_id.value = tid
    wbs_type.value = type
    isPrimaryKeyId.value = treeId
   
})


const treeLoadNode = async ({ node, item, level }, resolve) => {
   let parentId = '0'
    if (level !== 0) {
        parentId = item?.id
    }
    //获取数据
    const { data } = await thirdApi.getTreeCy({
       contractId: contractId.value,
        projectId: projectId.value,
        parentId,
      
    })
    resolve(getArrValue(data))

 
}

//关联试验文件
const filedialogTableData = ref([])
const fileModalradio = ref('test')
const radioChange = (val) => {
  
   getfileNodeData()

   
}

//节点被点击
//节点被点击
const filenodeItemInfo = ref({})
const filenodeDataInfo = ref({})


const fileModalElTreeClick = async ({ data, node }) => {
    filenodeItemInfo.value = node
    filenodeDataInfo.value = data
     getfileNodeData()


    
   
}






const filebetweenTime = ref([])
const filesearchFormPage = ref({
    startTime: null, lastTime: null, wbsId: null, current: 1, size: 20, total: 0,
})
const filesearchFormPageChange = ({ current, size }) => {
    filesearchFormPage.value.current = current
    filesearchFormPage.value.size = size
    // getDialogTableData()
       getfileNodeData()
}
const filebetweenTimeUpdate = ({ arr }) => {
    filebetweenTime.value = arr
    filesearchFormPage.value.startTime = arr[0]
    filesearchFormPage.value.lastTime = arr[1]
}

const filesearchClick = () => {
    filesearchFormPage.value.current = 1
    getfileNodeData()
}
const filedialogTableLoading = ref(false)

const filedialogTableColumn = ref([
    // reportNo
    { key: 'reportNo', name: '报告编号' },
    { key: 'reportDate', name: '报告日期' },
    { key: 'projectPositionName', name: '工程用途及部位' },
    { key: 'detectionResultName', name: '检测结果' },
])


//多选
const filetableCheckedKeys = ref([])
const filedialogTableSelection1 = (rows) => {
    filetableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}


//试验文件节点下的数据

const getfileNodeData = async () => {
    if (!filenodeDataInfo.value?.pkeyId) {
        window.$message.warning('请先选择节点')
        return
    }
    // 获取数据
    filedialogTableLoading.value = true
   
    
    let apiResponse
    if (fileModalradio.value === 'test') {
        // 调用试验检测报告接口
        apiResponse = await thirdApi.getTrialDetectionReport({
            contractId: contractId.value,
            nodeId: filenodeDataInfo.value.pkeyId,
            current: filesearchFormPage.value.current,
            size: filesearchFormPage.value.size,
            startTime: filesearchFormPage.value.startTime,
            endTime: filesearchFormPage.value.lastTime,
        })
    } else {
        // 调用第三方报告接口
        apiResponse = await thirdApi.getThirdReport({
            contractId: contractId.value,
            nodeId: filenodeDataInfo.value.pkeyId,
            current: filesearchFormPage.value.current,
            size: filesearchFormPage.value.size,
            startTime: filesearchFormPage.value.startTime,
            endTime: filesearchFormPage.value.lastTime,
            type: fileModalradio.value,

        })
    }
    
    const { error, code, data } = apiResponse
    
    // 处理数据
    if (!error && code === 200) {
        filedialogTableData.value = getArrValue(data['records'])
        filesearchFormPage.value.total = data.total || 0
        filedialogTableLoading.value = false
        
        let defaultarr = []
        filedialogTableData.value.forEach((item) => {
            if (item.isSelectedStatus === 1) {
                defaultarr.push(item)
            }
            tabtoggleSelection(defaultarr)
        })
    } else {
        filedialogTableData.value = []
        filesearchFormPage.value.total = 0
        filedialogTableLoading.value = false // 修正了这里的赋值错误
    }
}

const dialogTableRef1 = ref(null)


const tabtoggleSelection = (rows) => {
    if (rows) {
        rows.forEach(row => {
            nextTick(() => {
                dialogTableRef1.value?.toggleRowSelection(row, true)
            })
        })
    } else {
        dialogTableRef1.value?.clearSelection()

    }
}

//确认关联试验文件
const savefileSubmit = async () => {
    const idarr = []
    filetableCheckedKeys.value.forEach((item) => {
        idarr.push(item.id)
    })
    const idval = idarr.join(',')
    await savesubmitRelationFile(idval)
}

//关联试验文件
const savesubmitRelationFile = async (ids) => {
    const { error, code, data, msg } = await samplingApi.submitRelationFile({
        projectId: projectId.value,
        contractId: contractId.value,
        nodeId: filenodeDataInfo.value?.pkeyId,
        type: fileModalradio.value === 'test' ? 11 : fileModalradio.value === 1 ? 12 : 13,
        ids,
        qualityTestPKeyld:isPrimaryKeyId.value,
       
    })
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

// 暴露出去
defineExpose({
    savefileSubmit,
})
</script>

<style lang="scss">

</style>
