<!--  -->
<template>
    <hc-new-dialog v-model="qualityMoadal" is-table title="关联质检资料" widths="1200px" @close="qulModalClose" @save="saveQualModal">
        <hc-new-card>
            <div class="relative h-full flex">
                <div :id="`hc_tree_card_${uuid}`" v-loading="treeLoading" class="hc_tree_card_border relative">
                    <hc-body scrollbar padding="0px">
                        <hc-lazy-tree tree-key="id" @load="treeLoadNode" @node-tap="nodeElTreeClick" />
                    </hc-body>
                </div>
                <div :id="`hc_table_card_${uuid}`" class="relative flex-1">
                    <HcTable ref="qualTable" :column="tableColumn" :datas="tableData" is-new is-check is-reserve-selection :loading="tableLoading" @selection-change="tableSelection">
                        <template #appStatusName="{ row }">
                            <el-tag
                                v-if="row.appStatusName"
                                :type="`${row.appStatusName === '已审批' ? 'success' : row.appStatusName === '待审批' ? 'warning' : row.appStatusName === '已废除' ? 'danger' : 'info'}`"
                                class="mx-1" effect="dark"
                            >
                                {{ row.appStatusName }}
                            </el-tag>
                        </template>
                    </HcTable>
                </div>
            </div>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue, getObjValue, getRandom } from 'js-fast-way'
import { useAppStore } from '~src/store'
import unitApi from '~api/project/debit/contract/unit'
import { queryWbsTreeData } from '~api/other'
const props = defineProps({
    qualityMoadal: {
        type: Boolean,
        default: false,
    },
    cid:{
        type:String,
        default:'',
    },
    periodId:{
        type:String,
        default:'',
    },
    selectId:{
        type:String,
        default:'',       
    },
    
})
const emit = defineEmits([ 'close', 'finish'])
const useAppState = useAppStore()
const contractInfo = ref(useAppState.getContractInfo)
const projectId = ref(useAppState.getProjectId || '')
const { contractType } = contractInfo.value
const classifyType = ref(contractType === 2 ? '2' : '1')
const qualityMoadal = ref(props.qualityMoadal)
const cid = ref(props.cid)
const periodId = ref(props.periodId)
const selectId = ref(props.selectId)
watch(() => [
    props.qualityMoadal,
    props.cid,
    props.qualityMoadal,
    props.selectId,
], ([qual, Cid, Pid, sle]) => {
    qualityMoadal.value = qual
    cid.value = Cid
    periodId.value = Pid
    selectId.value = sle
})
const uuid = getRandom(4)

//监听
watch(qualityMoadal, (val) => {
    if (val) {
        nextTick(() => {
                setSplitRef()
                tableData.value = []
            })
        }
    
})
//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    try {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    } catch (error) {
        console.log(error)
    }
}


//懒加载的数据
const treeLoading = ref(false)
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let contractIdRelation = '', parentId = '', primaryKeyId = ''
    if (level !== 0) {
        const nodeData = getObjValue(item)
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
    treeLoading.value = true
    //获取数据
    const { data } = await queryWbsTreeData({
        contractId: cid.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        classifyType: classifyType.value,
        tableOwner:classifyType.value,
        
    })
    treeLoading.value = false
    resolve(getArrValue(data))
   
}
const tableColumn = [
    { key: 'partName', name: '分/子分项部位' },
    { key: 'dataName', name: '资料名称' },
    { key: 'appStatusName', name: '资料审核状态' },
]

const qulModalClose = ()=>{
    qualityMoadal.value = false
    emit('close')
}

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

const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}
const qualTable = ref(null)
const tableData = ref([])
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await unitApi.getCurrentNodeAllForm({
        ...searchForm.value,
        contractId:cid.value,
        projectId:projectId.value,
        nodeId:curTree.value.pKeyId,
        contractIdRelation:curTree.value?.contractIdRelation || '',
        classifyType: classifyType.value,
        selectIds:selectId.value,
  
    })
    tableData.value = getArrValue(data['records'])
    searchForm.value.total = data.total || 0
    tableLoading.value = false

    let defaultarr = []
    tableData.value.forEach((item) => {
            if (item.isSelect === 1) {
                defaultarr.push(item)

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

    }
}
const curTree = ref(null)
const nodeElTreeClick = ({ node, data, keys })=>{
    curTree.value = data
    getTableData()

}
//多选
const tableKeys = ref([])
const tableSelection = (rows) => {
    tableKeys.value = rows
}
const saveQualModal = ()=>{
    if ( tableKeys.value.length > 0) {
        qualityMoadal.value = false
        emit('close')
        emit('finish', tableKeys.value)
    } else {
        window.$message.warning('请先选择你要关联的质检资料')
        emit('close')
        emit('finish', tableKeys.value)
    }
    
}
</script>

<style lang='scss' scoped>
</style>