<template>
    <div>
        <div
            :style="{ width: menuCollapse ? '40px' : '280px' }"
            style="transition: all 0.3s; overflow: hidden; height: 100%"
        >
            <Icon
                v-show="menuCollapse"
                @click="onMenuCollapse"
                :name="menuCollapse ? 'el-icon-Expand' : 'el-icon-Fold'"
                :class="menuCollapse ? 'unfold' : ''"
                size="18"
                class="fold ml10 mt20 menu-collapse"
                style="cursor: pointer"
            />
            <div class="cn-tree" :style="{ opacity: menuCollapse ? 0 : 1 }">
                <div style="display: flex; align-items: center" class="mb10">
                    <el-input v-model="filterText" placeholder="请输入内容" clearable>
                        <template #prefix>
                            <Icon name="el-icon-Search" style="font-size: 16px" />
                        </template>
                    </el-input>
                    <Icon
                        @click="onMenuCollapse"
                        :name="menuCollapse ? 'el-icon-Expand' : 'el-icon-Fold'"
                        :class="menuCollapse ? 'unfold' : ''"
                        size="18"
                        class="fold ml10 menu-collapse"
                        style="cursor: pointer"
                        v-if="true"
                    />
                </div>
                <el-tree
                    style="flex: 1; overflow: auto"
                    :props="defaultProps"
                    highlight-current
                    :filter-node-method="filterNode"
                    node-key="id"
                    v-bind="$attrs"
                    default-expand-all
                    :data="tree"
                    ref="treRef"
                    @node-click="clickNode"
                    :expand-on-click-node="false"
               
                >
                    <template #default="{ node, data }">
                        <span class="custom-tree-node">
                            <div class="left">
                                <Icon
                                    :name="data.icon"
                                    style="font-size: 16px"
                                    :style="{ color: data.color }"
                                    v-if="data.icon"
                                />
                                <span>{{ node.label }}</span>
                            </div>
                            <div class="right">
                                <a :style="{ marginRight: '0.5rem' }" v-if="data.children">
                                    <el-icon :style="{ color: '#0000FF' }">
                                        <Plus @click="add(node, data)" />
                                    </el-icon>
                                </a>
                                <a :style="{ marginRight: '0.5rem' }">
                                    <el-icon :style="{ color: '#DA3434' }">
                                        <Delete @click="del(node, data)" />
                                    </el-icon>
                                </a>
                                <a :style="{ marginRight: '0.5rem' }">
                                    <el-icon :style="{ color: '#0000FF' }">
                                        <Edit @click="edit(node, data)" />
                                    </el-icon>
                                </a>
                            </div>
                        </span>
                    </template>
                </el-tree>
            </div>
        </div>
        <popup ref="dialogRef" @onSubmit="getTreeList"></popup>
    </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, watch, defineProps, defineEmits, inject, onMounted } from 'vue'
import { getSchemeTree } from '@/api/cs-device-boot/planData'
import { useConfig } from '@/stores/config'
import useCurrentInstance from '@/utils/useCurrentInstance'
import { ElTree } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { delRecord } from '@/api/cs-device-boot/planData'
import popup from './popup.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
defineOptions({
    name: 'govern/schemeTree'
})
interface Props {
    width?: string
    canExpand?: boolean
}

const { proxy } = useCurrentInstance()
const menuCollapse = ref(false)
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
watch(filterText, val => {
    treRef.value!.filter(val)
})
const onMenuCollapse = () => {
    menuCollapse.value = !menuCollapse.value
    proxy.eventBus.emit('cnTreeCollapse', menuCollapse)
}
const filterNode = (value: string, data: any) => {
    if (!value) return true
    return data.name.includes(value)
}

/** 树形结构数据 */
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
}
const props = withDefaults(
    defineProps<{
        showCheckbox?: boolean
        defaultCheckedKeys?: any
    }>(),
    {
        showCheckbox: false,
        defaultCheckedKeys: []
    }
)

const emit = defineEmits(['init', 'checkChange', 'nodeChange', 'editNode', 'getChart'])
const config = useConfig()
const tree = ref()
const treRef = ref()
//获取方案树形数据
const getTreeList = () => {
    getSchemeTree().then(res => {
        let arr: any[] = []
        res.data.forEach((item: any) => {
            item.icon = 'el-icon-Menu'
            item.color = config.getColorVal('elementUiPrimary')
            item.children.forEach((item2: any) => {
                item2.icon = 'el-icon-Document'
                item2.color = config.getColorVal('elementUiPrimary')
                arr.push(item2)
            })
        })
        tree.value = res.data
        nextTick(() => {
            if (arr.length) {
                treRef.value.setCurrentKey(arr[0].id)
                // 注册父组件事件
                emit('init', {
                    level: 2,
                    ...arr[0]
                })
            } else {
                emit('init')
            }
        })
    })
}
getTreeList()
const dialogRef = ref()

const handleOpen = (val: any, id: any) => {
    dialogRef.value.open(val, id)
}
//方案id
const planId: any = ref('')
//测试项id
const monitorId: any = ref('')
const planData: any = ref({})
const getPlanData = (row: any) => {
    planData.value = {}
    planData.value = JSON.parse(JSON.stringify(row))
}
/** 添加树节点 */
// 0 新增方案 1 修改方案 2 新增测试项 3 修改测试项 4 设备信息
const add = (node: any, data: any) => {
    planId.value = data.id
    //添加测试项
    if (data.children) {
        handleOpen(2, planId.value)
    }
}
/** 编辑树节点 */
const edit = async (node: Node, data: any) => {
    planId.value = data.id
    //修改方案
    if (data.children) {
        await handleOpen(1, planId.value)
    }
    //修改测试项
    else {
        monitorId.value = data.id
        await handleOpen(3, planId.value)
    }
}
/** 删除树节点 */
const del = (node: Node, data: any) => {
    planId.value = data.id
    //删除方案/测试项
    ElMessageBox.confirm('是否确认删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            delRecord({ id: data.id }).then(res => {
                if (res.code == 'A0000') {
                    ElMessage.success('删除成功')
                    getTreeList()
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消'
            })
        })
}
//取消删除
const cancelDel = () => {}
const clickNode = (e: anyObj) => {
    e.children ? (planId.value = e.id) : (planId.value = e.pid)
    emit('nodeChange', e)
}
watch(
    () => planData.value,
    (val, oldVal) => {
        if (val && dialogRef.value) {
            const obj = JSON.parse(JSON.stringify(val))
            obj.records = [
                val.records.find(item => {
                    return item.id == monitorId.value
                })
            ]
            dialogRef.value.details(obj)
        }
    },
    {
        immediate: true,
        deep: true
    }
)
defineExpose({ treeRef, getPlanData, getTreeList })
</script>
<style lang="scss" scoped>
.cn-tree {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    width: 100%;

    :deep(.el-tree) {
        border: 1px solid var(--el-border-color);
    }

    :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
        background-color: var(--el-color-primary-light-7);
    }

    .menu-collapse {
        color: var(--el-color-primary);
    }
}

.ml10 {
    margin-bottom: 0 !important;
}
.add_plan {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
.custom-tree-node {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left,
    .right {
        display: flex;
        align-items: center;
    }
    .left{
        span{
            margin-left: 2px;
        }
    }
    .right{
        a{
            margin-left: 2px;
        }
    }
}
</style>
