import { buildTreeNodes } from '@/common/converter';
import { calcElementTop } from '@/common/helper';
import { SuperTable } from '@/components';
import SysOrgController from '@/services/apis/SysOrgController';
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 { useRequest } from '@umijs/max';
import { Tree } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

const ROOT_KEY = 0;

/** 用户管理 */
const OrgMember: React.FC = () => {
    const [expandedKeys, setExpandedKeys] = useState<Key[]>([ROOT_KEY]);
    const [selectedKeys, setSelectedKeys] = useState<Key[]>([ROOT_KEY]);

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

    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 { data: orgData } = useRequest(() => {
        return SysOrgController.getAllList();
    }, {
        formatResult: (res) => {
            setExpandedKeys([ROOT_KEY]);
            const items = buildTreeNodes<API.SysOrgLiteOutput>((res ?? []) as unknown as DICTS.ParentTreeNode[], ROOT_KEY);
            return items;
        }
    });

    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.SysUserOutput>[] = [
        {
            title: '姓名',
            dataIndex: ['user', 'name'],
            search: {
                transform: (v) => v ? ({ name: v }) : v,
            },
            width: 80,
        },
        {
            title: '手机号码',
            dataIndex: ['user', 'mobile'],
            search: {
                transform: (v) => v ? ({ mobile: v }) : v,
            },
            width: 120,
            align: 'center',
            hideInSearch: true,
            // renderText: (v) => {
            //     const p = /(\d{3})\d*(\d{4})/;
            //     return v.replace(p, '$1****$2');
            // },
        },
        {
            title: '所属机构',
            dataIndex: ['sysOrg', 'name'],
            hideInSearch: true,
        },
        {
            title: '所属角色',
            dataIndex: ['user', 'roles'],
            hideInSearch: true,
            render: (_, r) => {
                return r.sysRoles?.map((t: any) => t.name).join('、');
            },
        },

        {
            title: '操作',
            width: 100,
            align: 'center',
            valueType: 'option',
            // render: (_, record) => <ResetPassword userId={record.id} trigger={<a>重置密码</a>} />,
        },

    ];

    useEffect(() => {
        const orgTree = document.getElementById('org-tree');
        const orgTreeHeader = orgTree?.getElementsByClassName('ant-pro-card-header');
        let h = ((orgTreeHeader?.[0] as HTMLElement)?.offsetHeight ?? 0) + 24;
        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='org-tree'
                >
                    <Tree.DirectoryTree
                        ref={treeRef}
                        className={treeClassName}
                        showIcon={false}
                        autoExpandParent
                        blockNode={true}
                        expandedKeys={expandedKeys}
                        selectedKeys={selectedKeys}
                        onExpand={(expandedKeys) => setExpandedKeys(expandedKeys as number[])}
                        treeData={orgData}
                        onSelect={handleSelect}
                    />
                </ProCard>
                <ProCard
                    title="人员信息"
                    bodyStyle={{ padding: 0 }}
                    headerBordered
                >
                    <SuperTable
                        columns={columns}
                        actionRef={actionRef}
                        sticky
                        // request={async (params = {}, sort) => {
                        //     return SuperTable.requestPageAgent({ params, sort }, async (p) => {
                        //         const res = await SysOrgUserController.queryPageList({ ...p, sysOrgId: (selectedKeys?.[0] as number) ?? undefined });
                        //         return res;
                        //     });
                        // }}
                        options={{ reload: false, fullScreen: false, setting: false }}
                    />
                </ProCard>
            </ProCard>
        </PageContainer>
    );
};

export default OrgMember;
