<template>
    <div class='default-main'>
        <div class='custom-table-header'>
            <div>
                关键字筛选
                <el-input maxlength="32" show-word-limit class="ml10" v-model="searchValue" placeholder="请输入字典名称"
                    clearable style="width: 240px" @input="inpChaange" />
            </div>
            <div style="margin-left: auto;"> <el-button :icon='Plus' type='primary' @click='addMenu'>新增字典类型</el-button>
            </div>

        </div>
        <Table ref='tableRef' :tree-config="{ childrenField: 'children', rowField: 'id' }" />
        <PopupForm ref='popupFormRef'></PopupForm>
    </div>
</template>
<script setup lang='ts'>
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted, provide, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import { ElMessage } from 'element-plus'
import PopupForm from './popupForm.vue'
import { dicDelete } from '@/api/system-boot/dic'

defineOptions({
    name: 'setting/dictionary/tree'
})
const searchValue = ref('')
const rawList = ref<any[]>([])
const tableRef = ref()
const popupFormRef = ref()

/** 父级命中保留全部子级；仅子级命中则保留父级及匹配子级 */
function filterTreeByName(nodes: any[], keyword: string): any[] {
    if (!keyword) return nodes

    const result: any[] = []
    nodes.forEach(node => {
        const selfMatch = node.name?.includes(keyword)
        if (selfMatch) {
            result.push(node)
            return
        }
        const filteredChildren = node.children?.length ? filterTreeByName(node.children, keyword) : []
        if (filteredChildren.length > 0) {
            result.push({ ...node, children: filteredChildren })
        }
    })
    return result
}

function expandFirstTreeNode() {
    nextTick(() => {
        const treeInstance = tableRef.value?.getRef()
        if (!treeInstance) return
        treeInstance.setAllTreeExpand(false)
        const firstNode = tableStore.table.data[0]
        if (firstNode) {
            treeInstance.setTreeExpand([firstNode], true)
            treeInstance.setCurrentRow(firstNode)
        }
    })
}

function applyTreeData() {
    tableStore.table.data = filterTreeByName(rawList.value, searchValue.value)
    expandFirstTreeNode()
}

const inpChaange = () => {
    applyTreeData()
}

const tableStore = new TableStore({
    showPage: false,
    url: '/system-boot/dictTree/queryTree',
    method: 'GET',
    publicHeight: 60,
    column: [
        { title: '字典名称', field: 'name', treeNode: true, align: 'left' },
        // { title: '排序', field: 'sort',width:'80'  },
        { title: '编码', field: 'code' },
        { title: '描述', field: 'remark' },
        // {
        //     title: '状态',
        //     field: 'status',
        //     width: '80',
        //     render: 'tag',
        //     custom: {
        //         0: 'success',
        //         1: 'warning',
        //         2: 'danger'
        //     },
        //     replaceValue: {
        //         0: '正常',
        //         1: '禁用',
        //         2: '删除'
        //     }
        // },
        {
            title: '操作', fixed: 'right',
            width: '180',
            render: 'buttons',

            buttons: [
                {
                    title: '新增',
                    type: 'primary',
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: row => {
                        popupFormRef.value.open('新增字典类型', {
                            name: '',
                            code: '',
                            remark: '',
                            sort: 100,
                            type: 0,
                            pid: row.id,
                            id: ''
                        })
                    }
                },
                {
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        popupFormRef.value.open('编辑字典类型', row)
                    }
                },
                {
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除该字典类型吗？'
                    },
                    click: row => {
                        dicDelete(row.id).then(() => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                }
            ]
        }
    ],
    loadCallback: () => {
        rawList.value = JSON.parse(JSON.stringify(tableStore.table.data))
        applyTreeData()
    }
})

provide('tableStore', tableStore)
tableStore.table.params.searchState = 0
onMounted(() => {
    tableStore.index()
})
const addMenu = () => {
    popupFormRef.value.open('新增字典类型')
}
</script>
