<script lang="tsx">
import { defineComponent, onMounted, ref, Fragment } from 'vue'
import { Omix, useSkyConfiger, APP_HOST, getSkyToken, delSkyToken, delSkyStore, fetchSkySignin } from '../packages'

export default defineComponent({
    name: 'App',
    setup() {
        const { state, setCollapsed, setState } = useSkyConfiger()
        const dataSource = ref<Array<Omix>>([])
        const dataNodes = ref<Array<Omix>>([])
        const defaultActive = ref<string>('/system/user')

        onMounted(fetchPlatformResource)

        /**路由格式化**/ //prettier-ignore
        function fetchRouteFormat(list: Array<Omix>, parent?: Omix) {
            return list.sort((a, b) => a.sort - b.sort).reduce<Omix[]>((pre, cur) => {
                const { meta, name, path } = cur ?? {}
                const { title, node, tab, icon } = meta ?? {}
                const _path = `${parent?.path ?? ''}/${path.replace('/', '')}`
                const item: Omix = { path: _path, name: name ?? _path, meta: { title, icon }, children: [] }
                let children: Array<Omix> = []
                if (node && node.length) {
                    children = node
                } else if (tab && tab.length) {
                    children = tab
                }
                if (children.length > 0 && children[0].meta?.button) {
                    item.meta.button = children.sort((a1, b1) => a1.meta.sort - b1.meta.sort)
                } else {
                    item.children =  fetchRouteFormat(children, item)
                }
                pre.push(item)
                return pre
            }, [])
        }

        /**菜单扁平化**/
        function findLeafNodes(list: Array<any>): Array<Omix> {
            return list.reduce((pre, cur) => {
                if (cur.children && cur.children.length > 0) {
                    pre = pre.concat(findLeafNodes(cur.children))
                } else {
                    pre.push(cur)
                }
                return pre
            }, [])
        }

        /**移除页面路由children字段**/
        function fetchRouteChildren(list: Array<Omix>) {
            function removeChildrenField(data: Omix) {
                if (data.children && data.children.length > 0) {
                    data.children = data.children.map((child: any) => removeChildrenField(child))
                } else if (data.children && data.children.length === 0) {
                    delete data.children
                }
                return data
            }
            return list.map(removeChildrenField)
        }

        async function fetchPlatformResource() {
            try {
                const response = await fetch(`https://gw-test.praise.com/staff/common/system/platform/resource`, {
                    method: 'POST',
                    headers: {
                        Authorization: getSkyToken(),
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ platform: 'skyline-staff-buka' })
                })
                const { data } = await response.json()
                dataSource.value = fetchRouteChildren(fetchRouteFormat(data ?? []))
                dataNodes.value = findLeafNodes(dataSource.value)
                dataNodes.value[0].close = false
                return await setState({ loading: false })
            } catch (err) {
                return await setState({ loading: false, failure: true })
            }
        }

        async function delCookie() {
            await delSkyToken()
            await delSkyStore(APP_HOST.APP_REFRESH_TOKEN)
            await delSkyStore(APP_HOST.APP_TOKEN_EXPIRES)
        }

        return () => (
            <sky-container header-hidden={false} aside-hidden={false}>
                {{
                    header: () => (
                        <sky-header trigger onTrigger={(evt: Omix) => console.log(evt)}>
                            <div style={{ flex: 1, overflow: 'hidden' }}>
                                <el-button>按钮测试</el-button>
                            </div>
                            <sky-user
                                loading={state.loading}
                                nickname="李飞的(1233)"
                                avatar="https://chat-oss.lisfes.cn/chat/image/2164042228379484160.jpg"
                            ></sky-user>
                        </sky-header>
                    ),
                    aside: (data: Record<string, any>) => (
                        <sky-navbar
                            navbar-height="42px"
                            default-active={defaultActive.value}
                            collapsed={data.collapsed}
                            data-source={dataSource.value}
                            onSelecter={(key: string) => (defaultActive.value = key)}
                            v-slots={{
                                iconRender: () => (
                                    <el-icon size={16}>
                                        <local-skyline-home />
                                    </el-icon>
                                )
                            }}
                        ></sky-navbar>
                    ),
                    bookmark: () => (
                        <Fragment>
                            {!state.loading && (
                                <sky-bookmark
                                    default-active={defaultActive.value}
                                    data-source={dataNodes.value}
                                    onSelecter={(evt: Omix) => (defaultActive.value = evt.path)}
                                    onClose-current={() => console.log('11')}
                                ></sky-bookmark>
                            )}
                        </Fragment>
                    ),
                    default: () => (
                        <el-scrollbar class="skyline-scrollbar">
                            {!state.loading && (
                                <div>
                                    <div>内容区域</div>
                                    <el-button onClick={fetchSkySignin}>授权</el-button>
                                    <el-button onClick={delCookie}>删除</el-button>
                                    <el-button onClick={() => setCollapsed(!state.collapsed)}>
                                        {state.collapsed ? '展开' : '收缩'}
                                    </el-button>
                                </div>
                            )}
                        </el-scrollbar>
                    )
                }}
            </sky-container>
        )
    }
})
</script>
