<template>
    <div class="radio-box">
        <el-radio-group v-model="fileModalradio" @change="radioChange">
            <el-radio :label="1">试验检测</el-radio>
            <el-radio :label="2">第三方检测</el-radio>
            <el-radio :label="3">外委检测</el-radio>
        </el-radio-group>
    </div>
    <div class="adding-form-dialog-box">
        <div class="dialog-tree-box">
            <el-scrollbar>
                <!-- 试验检测树 -->
                <TestTree
                    v-if="fileModalradio == 1"
                    :contract-id="contractId"
                    :project-id="projectId"
                    :tenant-id="tenant_id"
                    :wbs-id="wbsTempId"
                    :wbs-type="wbs_type"
                    @nodeTap="fileModalElTreeClick"
                />
                <!-- 第三方树 -->
                <ElTree
                    v-else ref="ElTreeRef2" :data="thirdtreeDatas" :indent="0" :props="thirdElTreeProps"
                    accordion class="hc-tree-node" highlight-current
                    node-key="id" @node-click="thirdtreeDatasElTreeClick"
                />
            </el-scrollbar>
        </div>
        <div class="dialog-table-box">
            <div class="dialog-search">
                <div class="w-64 ml-2">
                    <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
                    v-if="fileModalradio == 1" 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>
                <HcTable
                    v-if="fileModalradio == 2" ref="dialogTableRef2" :column="filedialogTableColumn1"
                    :datas="filedialogTableData" :loading="filedialogTableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="filedialogTableSelection"
                >
                    <template #reportNo="{ row }">
                        <span :class="[row?.isSelectedStatus === 1 ? 'text-green' : '']">{{ row?.reportNo }}</span>
                    </template>
                    <template #status="{ row }">
                        <span>{{ row?.status == 1 ? '合格' : '不合格' }}</span>
                    </template>
                </HcTable>
                <HcTable
                    v-if="fileModalradio == 3" ref="dialogTableRef" :column="filedialogTableColumn1"
                    :datas="filedialogTableData" :loading="filedialogTableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="filedialogTableSelection"
                >
                    <template #reportNo="{ row }">
                        <span :class="[row?.isSelectedStatus === 1 ? 'text-green' : '']">{{ row?.reportNo }}</span>
                    </template>
                    <template #status="{ row }">
                        <span>{{ row?.status == 1 ? '合格' : '不合格' }}</span>
                    </template>
                </HcTable>
            </div>
            <div class="dialog-pages">
                <HcPages :pages="filesearchFormPage" @change="filesearchFormPageChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { getArrValue } from 'js-fast-way'
import { getTreeAll } from '~api/tentative/detect'
import thirdApi from '~api/tentative/detect/third'
import samplingApi from '~api/tentative/material/sampling'
import TestTree from './testTree.vue'

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)

//监听
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 CTDTreeAutoExpandKeys = ref([])
const defaultExpandedCids = ref([])
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    isLeaf: 'hasChildren',
})


//关联试验文件
const filedialogTableData = ref([])
const fileModalradio = ref(1)
const radioChange = (val) => {
    if (val !== 1) {
        getthirdTreeDatas(val)
    }
}
//获取试验文件树树数据
const fileModaltreeDatas = ref([])
//节点被点击
//节点被点击
const filenodeItemInfo = ref({})
const filenodeDataInfo = ref({})
const fileTableData1 = ref([])
const fileTableColumn = ref([
    { key: 'recordNo', name: '报告编号' },
    { key: 'reportDate', name: '报告日期' },
    { key: 'projectPositionName', name: '工程用途及部位' },
    { key: 'detectionResultName', name: '检测结果' },
])

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

//获取第三方树试验文件

//获取树数据
const thirdtreeDatas = ref([])
const thirdElTreeProps = ref({
    label: 'nodeName',
    children: 'children',
    isLeaf: function (data) {
          return !data.hasChildren
    },
})
const getthirdTreeDatas = async (type) => {
    const { error, code, data } = await getTreeAll({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    if (!error && code === 200) {
        if (type == 2) {
            thirdtreeDatas.value = getArrValue(data['rightTree'])
        } else {
            thirdtreeDatas.value = getArrValue(data['leftTree'])
        }


    } else {
        thirdtreeDatas.value = []
    }
}
const thirdfilenodeItemInfo = ref({})
const thirdfilenodeDataInfo = ref({})
//获取第三方树节点下的数据
const getthirdTreetavleDatas = async () => {
    filedialogTableLoading.value = true
    const { error, code, data } = await thirdApi.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        nodeId: thirdfilenodeDataInfo.value.id,
        current: filesearchFormPage.value.current,
        size: filesearchFormPage.value.size,
        startTime: filesearchFormPage.value.startTime,
        endTime: filesearchFormPage.value.lastTime,
        qualityTestPKeyId: isPrimaryKeyId.value,


    })
    //处理数据
    if (!error && code === 200) {
        filedialogTableData.value = getArrValue(data['records'])
        filesearchFormPage.value.total = data.total || 0
        filedialogTableLoading.value = false
        if (filedialogTableData.value.length > 0) {
            let defaultarr = []
            filedialogTableData.value.forEach((item) => {
                if (item.isSelectedStatus === 1) {
                    defaultarr.push(item)

                }
                if (fileModalradio.value === 2) {
                    outtabtoggleSelection(defaultarr)
                } else {
                    thirdtabtoggleSelection(defaultarr)
                }

            })
        }
    } else {
        filedialogTableData.value = []
        filesearchFormPage.value.total = 0
        filesearchFormPage.value = false
    }
    filedialogTableLoading.value = false
}
const thirdtreeDatasElTreeClick = (data, node) => {
    thirdfilenodeItemInfo.value = node
    thirdfilenodeDataInfo.value = data
    getthirdTreetavleDatas()
}

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()
}
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 filedialogTableColumn1 = ref([
    // reportNo
    { key: 'reportNo', name: '报告编号' },
    { key: 'reportDate', name: '报告日期' },
    { key: 'projectPosition', name: '工程用途及部位' },
    { key: 'status', name: '检测结果' },
])

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

//试验文件节点下的数据
const getfileNodeData = async () => {
    //获取数据
    filedialogTableLoading.value = true
    const { error, code, data } = await samplingApi.gettrialPage({
        contractId: contractId.value,
        nodeId: filenodeDataInfo.value.primaryKeyId,
        current: filesearchFormPage.value.current,
        size: filesearchFormPage.value.size,
        startTime: filesearchFormPage.value.startTime,
        endTime: filesearchFormPage.value.lastTime,
        qualityTestPKeyId: isPrimaryKeyId.value,
    })
    //处理数据
    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
        filesearchFormPage.value = false
    }
}

const dialogTableRef = ref(null)
const dialogTableRef1 = ref(null)
const dialogTableRef2 = 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 } = await samplingApi.submitRelationFile({
        projectId: projectId.value,
        contractId: contractId.value,
        nodeId: isPrimaryKeyId.value,
        type: fileModalradio.value,
        ids,
    })
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
    }
}

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

<style lang="scss">

</style>
