<template>
    <el-dialog draggable class="cn-operate-dialog statistical-type-binding" v-model.trim="dialogVisible" title="绑定指标"
       width="1200px" @closed="close">
        <el-scrollbar style="padding-right: 0">
            <div class="box">
                <div class="box-left">
                    <el-input maxlength="32" show-word-limit    v-model.trim="searchKey" size="small" placeholder="请输入搜索内容"
                        :suffix-icon="Search" @input="filterTree" style="margin-bottom: 10px"></el-input>
                    <el-cascader-panel v-model.trim="fromDataValue" :props="{
                        multiple: true
                    }" :options="fromData"></el-cascader-panel>
                </div>
                <div class="box-center">
                    <el-button type="primary" icon="el-icon-Plus" @click="newGroup">新建分组</el-button>
                    <el-popover v-model.trim="popoverVisible" placement="right" width="400" trigger="click"
                        popper-style="width:auto">
                        <div class="statistical-type-binding-button-group">
                            <el-button type="primary" style="margin-left: 0" v-for="item in toData"
                                @click="leftCheckChange(item)">
                                {{ item.label }}
                            </el-button>
                        </div>
                        <div v-if="toData.length === 0">请先创建分组</div>
                        <template #reference>
                            <el-button style="margin-left: 0" class="mt20" type="primary" icon="el-icon-ArrowRight">
                                向右
                            </el-button>
                        </template>
                    </el-popover>
                    <el-button style="margin-left: 0" icon="el-icon-ArrowLeft" class="mt20" type="primary"
                        @click="rightCheckChange">
                        向左
                    </el-button>
                </div>
                <div class="box-right">
                    <el-input maxlength="32" show-word-limit    v-model.trim="searchKey1" size="small"
                        placeholder="请输入搜索内容" :suffix-icon="Search" @input="filterTree1"
                        style="margin-bottom: 10px"></el-input>
                    <el-cascader-panel v-model.trim="toDataValue" :props="{
                        multiple: true,
                        checkStrictly: true,
                        expandTrigger: 'click'
                    }" :options="toData">
                        <template #default="{ node, data }">
                            <div style="display: flex; align-items: center">

                                <el-tooltip placement="bottom" :hide-after="0">
                                    <template #content>
                                        <span>{{ data.label }}</span>
                                    </template>

                                    <div class="hide-txt">{{ data.label }}</div>
                                </el-tooltip>
                                <template v-if="node.level === 1">
                                    <div class="ml5">({{ data.children.length }})</div>
                                    <div style="flex: 1"></div>
                                    <Icon name="el-icon-EditPen" class="ml10" style="cursor: pointer"
                                        @click="editGroup(data)"></Icon>

                                    <el-popconfirm title="确定删除该分组吗?" @confirm="dicDeleteGroup(data)">
                                        <template #reference>
                                            <Icon name="el-icon-Delete" class="ml10" style="cursor: pointer"></Icon>
                                        </template>
                                    </el-popconfirm>


                                </template>
                            </div>
                        </template>
                    </el-cascader-panel>
                </div>
            </div>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <PopupAdd ref="addRef" @over="init(0)"></PopupAdd>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { CascaderValue, ElMessage } from 'element-plus'
import { addStatistical, queryStatistical } from '@/api/system-boot/csstatisticalset'
import { getDictTreeById, queryCsDictTree } from '@/api/system-boot/dictTree'
import PopupAdd from './add.vue'
import { dicDelete } from '@/api/system-boot/dic'
import List from '@/views/pms/comptroller/list.vue'
import { Search } from '@element-plus/icons-vue'
defineOptions({
    name: 'govern/setting/statisticalType/binding'
})
const addRef = ref()
// 统计类型pid
const pid = ref('')
const dialogVisible = ref(false)
const popoverVisible = ref(false)
const fromData = ref<treeData[]>([])
const fromDataValue = ref<string[]>([])
const toData = ref<treeData[]>([])
const toDataValue = ref<string[]>([])
const loading = ref(false)
const init = (val: any) => {
    queryStatistical(pid.value).then(res => {
        if (val == 0) {
            fromData.value = []
            fromDataValue.value = []
            toData.value = []
            toDataValue.value = []
            res.data.unSelectedList.forEach((item: any) => {
                const obj = {
                    id: item.dataType,
                    value: item.dataType,
                    pid: 0,
                    label: item.dataTypeName,
                    children: [] as any[]
                }
                item.eleEpdPqdVOS.forEach((item2: any) => {
                    const obj2 = {
                        id: item2.id,
                        pid: item.dataType,
                        value: item2.id,
                        label: item2.phase === 'T' ? item2.showName : item2.phase + '相' + item2.showName
                    }
                    if (item2.showName) {
                        obj.children.push(obj2)
                    }
                })
                fromData.value.push(obj)
            })
            res.data.selectedList.forEach((item: any) => {
                const obj = {
                    id: item.dataType,
                    value: item.dataType,
                    pid: 0,
                    label: item.dataTypeName,
                    children: [] as any[]
                }
                item.eleEpdPqdVOS.forEach((item2: any) => {
                    const obj2 = {
                        id: item2.id,
                        pid: item2.dataType,
                        value: item2.id,
                        label: item2.phase === 'T' ? item2.showName : item2.phase + '相' + item2.showName
                    }
                    if (item2.showName) {
                        obj.children.push(obj2)
                    }
                })
                toData.value.push(obj)
            })
        } else if (val == 1) {
            fromData.value = []
            fromDataValue.value = []
            res.data.unSelectedList.forEach((item: any) => {
                const obj = {
                    id: item.dataType,
                    value: item.dataType,
                    pid: 0,
                    label: item.dataTypeName,
                    children: [] as any[]
                }
                item.eleEpdPqdVOS.forEach((item2: any) => {
                    const obj2 = {
                        id: item2.id,
                        pid: item.dataType,
                        value: item2.id,
                        label: item2.phase === 'T' ? item2.showName : item2.phase + '相' + item2.showName
                    }
                    if (item2.showName) {
                        obj.children.push(obj2)
                    }
                })
                fromData.value.push(obj)
            })
        } else if (val == 2) {
            toData.value = []
            toDataValue.value = []
            res.data.selectedList.forEach((item: any) => {
                const obj = {
                    id: item.dataType,
                    value: item.dataType,
                    pid: 0,
                    label: item.dataTypeName,
                    children: [] as any[]
                }
                item.eleEpdPqdVOS.forEach((item2: any) => {
                    const obj2 = {
                        id: item2.id,
                        pid: item2.dataType,
                        value: item2.id,
                        label: item2.phase === 'T' ? item2.showName : item2.phase + '相' + item2.showName
                    }
                    if (item2.showName) {
                        obj.children.push(obj2)
                    }
                })
                toData.value.push(obj)
            })
        }
    })
}

const searchVisible = ref(false)
const searchKey = ref('')
//查左边
const filteredTree = ref([])
const filterTree = () => {
    filteredTree.value = filterNodes(fromData.value, searchKey.value)
}
//查右边
const searchKey1 = ref('')
const filteredTree1 = ref([])
const filterTree1 = () => {
    filteredTree1.value = filterNodes1(toData.value, searchKey1.value)
}

const filterNodes = (node: any, query: any) => {
    if (searchKey.value) {
        const keyword = query.trim().toLowerCase() // 获取搜索关键字并转换为小写
        const nodes = node
        // 使用递归函数过滤树形数据
        const filteredNodes = []
        for (const node of nodes) {
            if (node.label.toLowerCase().includes(keyword)) {
                // 如果节点的标签包含关键字，将其添加到结果中
                filteredNodes.push(node)
            } else if (node.children && node.children.length > 0) {
                // 如果节点有子节点，则递归过滤子节点
                const filteredChildren: any = filterNodes(node.children, keyword)
                if (filteredChildren.length > 0) {
                    // 如果子节点中有匹配的结果，则添加父节点
                    const clonedNode = { ...node, children: filteredChildren }
                    filteredNodes.push(clonedNode)
                }
            }
        }
        return (fromData.value = filteredNodes)
    } else {
        init(1)
    }
}

const filterNodes1 = (node: any, query: any) => {
    if (searchKey1.value) {
        const result: any = []
        node.forEach((node: any) => {
            let newNode = { ...node }
            if (node.children) {
                newNode.children = filterNodes1(node.children, query)
            }
            if (newNode.label.includes(query) || (newNode.children && newNode.children.length)) {
                result.push(newNode)
            }
        })
        return (toData.value = result)
    } else {
        init(2)
    }
}

// 左侧源数据选中事件
const leftCheckChange = (e: any) => {
    if (fromDataValue.value.length === 0) {
        return ElMessage.warning('请先选择数据')
    }
    let arr: any[] = []
    fromDataValue.value.forEach(item1 => {
        fromData.value.forEach(item2 => {
            if (item2.value === item1[0]) {
                item2.children = item2.children.filter((item3, index) => {
                    if (item3.value === item1[1]) {
                        arr.push(item3)
                        return false
                    } else {
                        return true
                    }
                })
            }
        })
    })
    if (e.value) {
        toData.value.forEach(item => {
            if (item.value === e.value) {
                item.children.push(...arr)
            }
        })
    } else {
        toData.value.push(...arr)
    }
    // fromDataValue.value = []
    popoverVisible.value = false
}
// 右侧目标数据选中事件
const rightCheckChange = () => {
    if (toDataValue.value.length === 0) {
        return ElMessage.warning('请先选择数据')
    }
    let arr: any[] = []
    toDataValue.value.forEach(item1 => {
        if (item1.length === 1) {
            toData.value = toData.value.filter(item2 => {
                if (item2.value === item1[0]) {
                    arr.push(item2)
                    return false
                } else {
                    return true
                }
            })
        } else {
            toData.value.forEach(item2 => {
                if (item2.value === item1[0]) {
                    item2.children = item2.children.filter((item3, index) => {
                        if (item3.value === item1[1]) {
                            arr.push(item3)
                            return false
                        } else {
                            return true
                        }
                    })
                }
            })
        }
    })
    fromData.value.forEach(item1 => {
        arr.forEach(item2 => {
            if (item2.pid === item1.value) {
                item1.children.push(item2)
            }
        })
    })
}

const dicDeleteGroup = (data: any) => {
    if (data.children.length) {
        return ElMessage.warning('该分组下有指标，不能删除')
    }
    dicDelete(data.value).then(res => {
        ElMessage.success('删除成功')
        toData.value = toData.value.filter(item => item.value !== data.value)
    })
}

const newGroup = () => {
    queryCsDictTree(pid.value).then(res => {
        const list = res.data || []
        const sort = list.length
            ? Math.max(...list.map((item: any) => Number(item.sort) || 0)) + 1
            : 1
        addRef.value.open('新建分组', {
            sort,
            code: '',
            pid: pid.value,
            id: '',
            remark: '',
            name: ''
        })
    })
}
const editGroup = (data: any) => {
    getDictTreeById(data.id).then(res => {
        addRef.value.open('修改分组', {
            sort: res.data.sort ?? 100,
            code: res.data.code || '',
            pid: res.data.pid || '',
            id: res.data.id || '',
            remark: res.data.remark || '',
            name: res.data.name || ''
        })
    })

}

const open = (id: string) => {
    dialogVisible.value = true
    pid.value = id
    init(0)
}
const submit = async () => {
    let ids = []
    let one = {
        id: pid.value,
        ids: [] as any[]
    }
    toData.value.forEach(item => {
        let obj = {
            id: item.id,
            ids: [] as any[]
        }
        if (item.children) {
            item.children.forEach(item2 => {
                obj.ids.push(item2.value)
            })
            ids.push(obj)
        } else {
            one.ids.push(item.value)
        }
    })
    if (one.ids.length) {
        ids.push(one)
    }
    loading.value = true
    addStatistical(ids).then(res => {
        ElMessage.success('绑定指标成功')
        dialogVisible.value = false
    }).finally(() => {
        loading.value = false
    })
}
const close = () => {
    searchKey.value = ''
    searchKey1.value = ''
    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: 1160px;
        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: hidden;
            // flex: 1;
            width: 450px;

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

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

            .el-cascader-panel {
                height: calc(60vh - 140px);

                .el-cascader-menu__list {
                    height: 100% !important;
                    overflow-y: auto !important;
                    // padding-bottom: 50px !important;
                    box-sizing: border-box;
                }
            }
        }

        .box-right {
            flex: 1;
        }

        .hide-txt {
            width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
</style>
