<template>
    <el-dialog
        draggable
        class="cn-operate-dialog statistical-type-binding"
        v-model="dialogVisible"
        title="绑定监测点"
        style="width: 1040px"
    >
        <el-scrollbar style="padding-right: 0" v-loading="loading">
            <div class="box">
                <div class="box-left">
                    <el-tree
                        ref="leftTree"
                        style="width: 100%; height: 100%"
                        :props="props"
                        :data="fromDataValue"
                        :default-expanded-keys="leftDefaultExpandedKeys"
                        show-checkbox
                        node-key="id"
                        @check="leftCheckChange"
                    />
                </div>
                <div class="box-center">
                    <el-button
                        style="margin-left: 0"
                        class="mt20"
                        type="primary"
                        icon="el-icon-ArrowRight"
                        @click="bind"
                        :disabled="fromData.length === 0"
                    >
                        绑定
                    </el-button>
                    <el-button
                        style="margin-left: 0"
                        icon="el-icon-ArrowLeft"
                        class="mt20"
                        type="primary"
                        @click="unbind"
                        :disabled="toData.length === 0"
                    >
                        解绑
                    </el-button>
                </div>
                <div class="box-right">
                    <el-tree
                        ref="rightTree"
                        style="width: 100%; height: 100%"
                        :props="props"
                        :data="toDataValue"
                        :default-expanded-keys="rightDefaultExpandedKeys"
                        show-checkbox
                        node-key="id"
                        @check="rightCheckChange"
                    />
                </div>
            </div>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { CascaderValue, ElMessage } from 'element-plus'
import { getDeptBindDeptLineTree } from '@/api/user-boot/terminalTree'
import { deptBindLine } from '@/api/user-boot/deptLine'

defineOptions({
    name: 'govern/setting/statisticalType/binding'
})
const pid = ref('')
const binData = reactive({
    deptId: '',
    deptType: '',
    id: '',
    type: 0
})
const dialogVisible = ref(false)
const loading = ref(false)
const leftTree = ref()
const rightTree = ref()
const fromData = ref<treeData[]>([])
const fromDataValue = ref<treeData[]>([])
const leftDefaultExpandedKeys = ref<string[]>([])
const toData = ref<treeData[]>([])
const toDataValue = ref<treeData[]>([])
const rightDefaultExpandedKeys = ref<string[]>([])
const props = {
    label: 'name',
    value: 'id',
    children: 'children'
}
const getExpandedKeys = (originArr: treeData[]) => {
    let arr: string[] = []
    const call = (originArr: treeData[]) => {
        originArr.forEach((item: treeData) => {
            if (item.level === 6) {
                arr.push(item.id as string)
            } else {
                call(item.children)
            }
        })
    }
    call(originArr)
    return arr
}
const init = () => {
    loading.value = true
    getDeptBindDeptLineTree(binData).then(res => {
        fromData.value = []
        fromDataValue.value = res.data[0]?.nothingBindTree || []
        toData.value = []
        toDataValue.value = res.data[0]?.myselfBindTree || []
        leftDefaultExpandedKeys.value = getExpandedKeys(fromDataValue.value)
        rightDefaultExpandedKeys.value = getExpandedKeys(toDataValue.value)
        loading.value = false
    })
}
// 左侧源数据选中事件
const leftCheckChange = (e: any) => {
    fromData.value = leftTree.value.getCheckedNodes().filter((item: any) => {
        return item.level === 6
    })
}
// 右侧目标数据选中事件
const rightCheckChange = (e: any) => {
    toData.value = rightTree.value.getCheckedNodes().filter((item: any) => {
        return item.level === 6
    })
}

// 定义一个函数来创建映射
const createMapping = (data: treeData[], key: 'pid' | 'id') => {
    const map = new Map<string, treeData[]>()
    data.forEach((item: treeData) => {
        const list = map.get(item[key]) || []
        list.push(item)
        map.set(item[key], list)
    })
    return map
}

// 定义一个函数来添加子节点
const addChildren = (data: treeData[], map: Map<string, treeData[]>) => {
    data.forEach((item: treeData) => {
        if (item.level === 3) {
            let children =
                map.get(item.id as string)?.filter((child: treeData) => {
                    return !item.children.find(child2 => (child.id as string) === child2.id)
                }) || []
            item.children.push(...children)
        } else {
            addChildren(item.children, map)
        }
    })
}

// 定义一个函数来过滤子节点
const filterChildren = (data: treeData[], map: Map<string, treeData[]>) => {
    data.forEach((item: treeData) => {
        if (item.level === 3) {
            const childrenIds = map.get(item.id as string)?.map(child => child.id as string) || []
            item.children = item.children.filter(child => !childrenIds.includes(child.id as string))
        } else {
            filterChildren(item.children, map)
        }
    })
}

const bind = () => {
    const map = createMapping(fromData.value, 'pid')
    filterChildren(fromDataValue.value, map)
    addChildren(toDataValue.value, map)
    rightDefaultExpandedKeys.value = getExpandedKeys(toDataValue.value)
    fromData.value = []
    leftTree.value.setCheckedKeys([])
}

const unbind = () => {
    const map = createMapping(toData.value, 'pid')
    filterChildren(toDataValue.value, map)
    addChildren(fromDataValue.value, map)
    toData.value = []
    rightTree.value.setCheckedKeys([])
    leftDefaultExpandedKeys.value = getExpandedKeys(fromDataValue.value)
}

const open = (row: any) => {
    console.log(row)
    dialogVisible.value = true
    binData.deptId = row.id
    binData.deptType = row.type
    binData.id = row.area
    init()
}
const submit = async () => {
    deptBindLine({
        id: binData.deptId,
        ids: getExpandedKeys(toDataValue.value)
    }).then(() => {
        ElMessage.success('绑定成功')
        dialogVisible.value = false
    })
}

defineExpose({ open })
</script>
<style lang="scss">
.statistical-type-binding-button-group {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 10px;
}

.statistical-type-binding {
    .box {
        display: flex;
        width: 1000px;
        height: calc(60vh - 95px);
        margin: 0 auto;
        text-align: left;

        .box-center {
            display: flex;
            align-items: center;
            width: 100px;
            padding-top: 20px;
            margin: 0 20px;
            flex-direction: column;
        }

        .box-right,
        .box-left {
            height: 100%;
            overflow-x: hidden;
            overflow-y: scroll;
            flex: 1;

            .el-cascader-menu {
                padding-right: 0;

                .el-scrollbar__wrap {
                    height: 100%;
                }
            }

            .el-cascader-panel {
                height: 100%;

                .el-cascader-menu__list {
                    height: 100% !important;
                }
            }
        }
    }
}
</style>
