import { ref, reactive, computed } from 'vue'
import { getTableColumns } from '@/business/table'
import { queryNewFuncmenu, insertNewFuncmenu } from '@/services/api/common'

export function useMenu() {
    const loading = ref(false)
    const dataList = ref<Ermcp.NewFuncmenuRsp[]>([])
    const columns = ref(getTableColumns('system_menu'))

    // 扁平列表树形化
    const arrayToTree = (list: Ermcp.NewFuncmenuRsp[]) => {
        return list.filter(<T extends Ermcp.NewFuncmenuRsp>(item: T) => {
            for (const key in item) {
                if (item[key] == null) {
                    delete item[key] // 删除无效值
                }
            }
            const children = list.filter((e) => e.parentcode === item.resourcecode) // 找出所有子元素
            if (children.length) {
                item.children = children // 递归向父级添加子元素
            }
            return !item.parentcode // 非父级的不返回
        })
    }

    const getMenuList = () => {
        loading.value = true
        return queryNewFuncmenu({
            data: {
                menutype: '5'
            },
            success: (res) => {
                dataList.value = arrayToTree(res.data)
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        columns,
        dataList,
        getMenuList,
    }
}

export function useMenuForm(selectedRow?: Ermcp.NewFuncmenuRsp) {
    const { dataList, getMenuList } = useMenu()
    const loading = ref(false)
    const formData = reactive<Partial<Ermcp.NewFuncmenuRsp>>({
        menutype: 5,
        parentcode: '',
        ...selectedRow
    })

    const menus = computed<Partial<Ermcp.NewFuncmenuRsp>[]>(() => {
        return [
            {
                resourcename: '一级菜单',
                resourcecode: '',
                children: dataList.value
            }
        ]
    })

    const addOrUpdate = () => {
        loading.value = true
        return insertNewFuncmenu({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    getMenuList()

    return {
        loading,
        menus,
        formData,
        addOrUpdate,
    }
}