<template>
    <div>
        <el-dialog v-model="dialogVisible" draggable title="选择ied" width="30%" @close="sureclose" :close-on-click-modal="false">
            <el-tree :data="treeList" :props="treeProps" @check-change="handleNodeClick" show-checkbox
                style="height: 300px;overflow-y: auto;" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cleanBox">取消</el-button>
                    <el-button type="primary" @click="sureArr">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, onMounted, watch, onBeforeUnmount, toRefs } from 'vue';
import scd from '@/api/scd';
export default {
    props: {
        iedModal: {
            type: Boolean,
            required: true
        },
        loadScdId: {
            type: Number || String,
            required: true
        }
    },
    setup(props, { emit }) {
        let dialogVisible = ref(false)
        let resultId = ref(0)
        let treeList = ref([])
        let checkArr = ref([])
        let treeProps = ref({
            label: "ied_name",
            id: "area_id",
        })
        watch(() => props.loadScdId, (newVal) => {
            resultId.value = newVal
        })
        function reload() {
            dialogVisible.value = props.iedModal
            resultId.value = props.loadScdId
            scd.scdAllIed({ scd_id: resultId.value - 0 }).then(res => {
                treeList.value = res.data
            })
        }
        function modalClose() {
            dialogVisible.value = false
            emit("iedBack", dialogVisible.value)
        }
        function modalSure() {
            emit("iedArrBack", checkArr.value);
            dialogVisible.value = false
            emit("iedBack", dialogVisible.value)
        }
        function handleNodeClick(e) {
            const existingIndex = checkArr.value.findIndex(item => item.id === e.id);
            if (existingIndex === -1) {
                // 如果 e.id 不在 checkArr 中，则将 e 添加到 checkArr
                checkArr.value.push(e);
            } else {
                // 如果 e.id 已经在 checkArr 中，则从 checkArr 中删除
                checkArr.value.splice(existingIndex, 1);
            }

        }

        onMounted(() => {
            reload()
        })
        return {
            reload,
            dialogVisible,
            sureclose: modalClose,
            cleanBox: modalClose,
            sureArr: modalSure,
            treeList,
            treeProps,
            handleNodeClick,
            checkArr,
        }
    }
}
</script>

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