<!--  -->
<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"
                        @select="tableSelect"
                        @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 { arrUnion, getArrValue, getObjValue, getRandom, isArrIndex } from 'js-fast-way'
import { useAppStore } from '~src/store'
import unitApi from '~api/project/debit/contract/unit'
import { queryWbsTreeData } from '~api/other'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
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)

//之前节点选中的数据
const oriCheckRows = ref([])
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 = []
                oriCheckRows.value = getStoreValue('checkRows') || []
            
            })
        }
    
})
//初始化设置拖动分割线
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
    setStoreValue('checkRows', [])
    cancelcheck.value = []
    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 cancelcheck = ref([])
const tableSelect = (rows)=>{
   const { selection, row } = rows
   const isDel = isArrIndex( selection, 'selectId', row.selectId)
   if (!isDel) {
      cancelcheck.value.push( row.selectId)
   }
}
//之前选中的
const saveQualModal = ()=>{
        qualityMoadal.value = false
        emit('close')
     

        let alarr = arrUnion(tableKeys.value, oriCheckRows.value)
         // 使用reduce方法进行去重
        const uniqueArray = alarr.reduce((acc, current) => {
        // 检查当前对象的某个字段是否已存在于累积数组中
        const x = acc.find(item => item.selectId === current.selectId)
        
        // 如果不存在，则将其添加到累积数组中
        if (!x) {
            return acc.concat([current])
        } else {
            return acc
        }
        }, [])
        alarr = uniqueArray
        emit('finish', alarr, cancelcheck.value)
        setStoreValue('checkRows', alarr)
    
    
}
</script>

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