<template>
    <div>
        <div :style="{ width: menuCollapse ? '40px' : '280px' }" style="transition: all 0.3s; overflow: hidden">
            <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>
                <div class="add_plan">
                    <el-button size="small" type="primary" @click="handleOpen(0, '')">新增方案</el-button>
                </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"
                                />
                                {{ node.label }}
                            </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 } 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 => {
    treeRef.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'])
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-HomeFilled'
            item.color = config.getColorVal('elementUiPrimary')
            item.children.forEach((item2: any) => {
                item2.icon = 'el-icon-List'
                item2.color = config.getColorVal('elementUiPrimary')
                arr.push(item2)
            })
        })
        tree.value = res.data
        planId.value = res.data[0]?.id
        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)
}
const planId: any = ref('')
const planData: any = ref({})
const getPlanData = (row: any) => {
    planData.value = {}
    planData.value = JSON.parse(JSON.stringify(row))
}
// const getPlanId = (id: any) => {
//     planId.value = id;
// }
/** 添加树节点 */
// 0 新增方案 1 修改方案 2 新增测试项 3 修改测试项 4 删除方案 5 删除测试项 6 设备信息
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 {
        await handleOpen(3, planId.value)
    }
}
/** 删除树节点 */
const del = (node: Node, data: any) => {
    planId.value = data.id
    //删除方案/测试项
    delRecord({ id: planId.value }).then(res => {
        if (res.code == 'A0000') {
            ElMessage.success('删除成功')
            getTreeList()
        }
    })
}
const clickNode = (e: anyObj) => {
    planId.value = e.id
    emit('nodeChange', e)
}
watch(
    () => planData.value,
    (val, oldVal) => {
        if (val && dialogRef.value) {
            dialogRef.value.details(val)
        }
    },
    {
        immediate: true,
        deep: true
    }
)
defineExpose({ treeRef, getPlanData })
</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;
}
</style>
