<template>
    <super-dialog
        v-model="dialogVisible"
        :title="title"
        custom-class="notification-dialog"
        top="8%"
        width="60%"
        :close-on-click-modal="false"
        @closed="closePage"
    >
        <div
            v-loading="detailLoading"
            class="table-container"
            element-loading-background="rgba(10 ,38 ,61, 0.9)"
        >
            <el-table
                ref="multipleSelection"
                :data="tableData"
                border
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                class="table-list"
                element-loading-background="rgba(10 ,38 ,61, 0.9)"
                height="100%"
                row-key="id"
                stripe
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column prop="catNo" label="分类编码" align="center" width="300" />
                <el-table-column prop="catName" label="分类名称" align="center" />
            </el-table>
        </div>
        <div slot="footer" style="display: flex; justify-content: center; width: 100%">
            <el-button type="primary" @click="submitObject" :loading="btnLoading">确定</el-button>
            <el-button @click="closePage">取消</el-button>
        </div>
    </super-dialog>
</template>

<script lang="ts" setup>
import { materialCategoryList } from '@/api/supplierMonitor/ConfigManagement/AccessQualificationConfig'
import SuperDialog from '@/components/Dialog/index.vue'
import { onMounted, reactive, ref, computed, watch, nextTick } from 'vue'
// 1. 定义 props
const props = defineProps({
    isShowAdd: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: ''
    },
    selectedContent: {
        type: Array,
        default: () => []
    }
})

const btnLoading = ref(false)
const detailLoading = ref<Boolean>(false)
const tableData = ref<any[]>([])
const multipleSelection = ref()

const getClassList = async () => {
    detailLoading.value = true
    let params = {
        pageBean: {
            pageSize: 20,
            page: 1,
            total: 0
        },
        querys: [],
        sorter: []
    }
    const result = (await materialCategoryList(params)) as any
    tableData.value = result?.value || result || []
    detailLoading.value = false
    // 数据加载完成后，设置选中状态
    await nextTick()
    setSelectedRows()
}

// 递归查找所有行（包括子节点）
const findAllRows = (data: any[], rows: any[] = []): any[] => {
    data.forEach((row) => {
        rows.push(row)
        if (row.children && row.children.length > 0) {
            findAllRows(row.children, rows)
        }
    })
    return rows
}

// 根据 selectedContent 的 id 设置表格选中状态
const setSelectedRows = () => {
    if (!multipleSelection.value || !props.selectedContent || props.selectedContent.length === 0) {
        return
    }

    // 先清空所有选中
    multipleSelection.value.clearSelection()

    // 获取所有行（包括子节点）
    const allRows = findAllRows(tableData.value)

    // 获取需要选中的 id 列表
    const selectedIds = props.selectedContent.map((item: any) => item.id || item)

    // 根据 id 勾选对应的行
    allRows.forEach((row) => {
        if (selectedIds.includes(row.id)) {
            multipleSelection.value.toggleRowSelection(row, true)
        }
    })
}

// 监听 selectedContent 变化，重新设置选中状态
watch(
    () => props.selectedContent,
    () => {
        if (props.isShowAdd && tableData.value.length > 0) {
            nextTick(() => {
                setSelectedRows()
            })
        }
    },
    { deep: true, immediate: false }
)

// 监听对话框打开，设置选中状态
watch(
    () => props.isShowAdd,
    (newVal) => {
        if (newVal) {
            // 如果数据已加载，直接设置选中状态
            if (tableData.value.length > 0) {
                nextTick(() => {
                    setSelectedRows()
                })
            } else {
                // 如果数据未加载，先加载数据
                getClassList()
            }
        }
    }
)

onMounted(() => {
    if (props.isShowAdd) {
        getClassList()
    }
})

// 2. 定义 emit
const emit = defineEmits(['update:isShowAdd', 'refresh', 'cancel', 'submit'])

const openPage = () => {}

const closePage = () => {
    // 触发取消事件，通知父组件这是取消操作
    emit('cancel')
    emit('update:isShowAdd', false)
}

defineExpose({
    openPage
})
// 保存绑定
const submitObject = async () => {
    if (selectedContent.value.length === 0) {
        ElMessage.warning('请选择物资分类')
        return
    }
    emit('submit', selectedContent.value)
    closePage()
}

const selectedContent = ref<any[]>([])
const handleSelectionChange = (selection: any) => {
    selectedContent.value = selection
}
// 3. 使用 computed 定义双向绑定
const dialogVisible = computed({
    get() {
        return props.isShowAdd
    },
    set(val) {
        emit('update:isShowAdd', false)
    }
})
</script>

<style lang="scss" scoped>
.table-container {
    height: 50vh;
    margin-bottom: 20px;
}
</style>
