import { calcElementTop } from '@/common/helper';
import { SuperTable } from '@/components';
import SysDictDataController from '@/services/apis/SysDictDataController';
import SysDictTypeController from '@/services/apis/SysDictTypeController';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { useModel, useRequest } from '@umijs/max';
import { Tree, theme } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

/** 数据字典管理 */
const DictList: React.FC = () => {
    const [expandedKeys, setExpandedKeys] = useState<Key[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<Key[]>([]);

    const actionRef = useRef<ActionType>();
    const dictRef = useRef(null);
    const [treeTop, setTreeTop] = useState(148);

    const { token } = theme.useToken();

    const treeClassName = useEmotionCss(({ token }) => {
        return {
            '.ant-tree-list-holder-inner': {
                padding: 0,
            },

            '.ant-tree-treenode': {
                padding: `${token.paddingXXS}px 0 ${token.paddingXS}px 0`,
                width: '100%',
                '.ant-tree-node-content-wrapper': {
                    width: '100%',
                },
                '&.ant-tree-treenode-selected': {
                    '::before': {
                        borderRadius: token.borderRadius,
                    }
                },
                '.ant-tree-node-selected': {
                    color: token.colorWhite,
                    backgroundColor: token.colorPrimary,
                }
            },
        };
    });

    const { getDictValueEnum } = useModel('useDict');

    const { data: dictTypes } = useRequest(() => {
        return SysDictTypeController.getAllList();
    }, {
        formatResult: (res) => {
            const list = res?.map(t => ({
                key: t.id,
                title: (
                    <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                        <div style={{ flex: 1 }}>{t.name}</div>
                        <div style={{ flex: 1 }}>{t.code}</div>
                    </div>
                )
            }));
            return list;
        }
    });

    const handleSelect = (sks: Key[]) => {
        const did = sks?.[0];
        const departmentId = selectedKeys?.[0] ?? null;
        if (departmentId === did) {
            return;
        }
        setSelectedKeys(sks);
        actionRef?.current?.reload();
    }

    const columns: ProColumns<API.SysDictDataOutput>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            // width: 80,
        },
        {
            title: '别称',
            dataIndex: 'nickName',
            // width: 80,
        },
        {
            title: '代码',
            dataIndex: 'code',
            // width: 80,
        },
        {
            title: '内码',
            dataIndex: 'value',
            // width: 80,
            align: 'center',
        },
        {
            title: '排序',
            dataIndex: 'sort',
            // width: 80,
            align: 'center',
        },
        {
            title: '状态码',
            dataIndex: 'antStatus',
            // width: 80,
        },
        {
            title: '颜色',
            dataIndex: 'antColor',
            // width: 80,
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 80,
            align: 'center',
            valueEnum: getDictValueEnum('common_status'),
        },
        {}
    ];

    useEffect(() => {
        const orgTree = document.getElementById('dict-tree');
        const orgTreeHeader = orgTree?.getElementsByClassName('ant-pro-card-header');
        let h = ((orgTreeHeader?.[0] as HTMLElement)?.offsetHeight ?? 0) + 16;
        h += calcElementTop(orgTree);
        setTreeTop(h);
    }, []);

    return (
        <PageContainer title={false}>
            <ProCard split="vertical">
                <ProCard
                    colSpan="320px"
                    bodyStyle={{
                        padding: 8,
                        overflow: 'auto',
                        maxHeight: `calc(100vh - ${treeTop}px)`,
                    }}
                    title="字典类型"
                    headerBordered
                    id='dict-tree'
                >
                    <Tree.DirectoryTree
                        ref={dictRef}
                        className={treeClassName}
                        showIcon={false}
                        autoExpandParent
                        blockNode={true}
                        expandedKeys={expandedKeys}
                        selectedKeys={selectedKeys}
                        onExpand={(expandedKeys) => setExpandedKeys(expandedKeys as number[])}
                        treeData={dictTypes}
                        onSelect={handleSelect}
                    />
                </ProCard>
                <ProCard
                    title="字典数据"
                    bodyStyle={{ padding: 0, paddingTop: token.paddingMD }}
                    headerBordered
                >
                    <SuperTable<API.SysDictDataOutput>
                        headerTitle={``}
                        columns={columns}
                        actionRef={actionRef}
                        sticky
                        search={false}
                        pagination={false}
                        request={async () => {
                            const data = await SysDictDataController.getListByDictTypeId({ dicttypeid: (selectedKeys?.[0] as number) ?? undefined });
                            return {
                                data,
                                success: true,
                            };
                        }}
                        options={{ reload: false, fullScreen: false, setting: false }}
                    />
                </ProCard>
            </ProCard>
        </PageContainer>
    );
};

export default DictList;
