import { buildTableTreeData2 } from '@/common/converter';
import { SuperTable } from '@/components';
import SysOrgController from '@/services/apis/SysOrgController';
import { CommonStatus } from '@/services/enums';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer, ProDescriptions, ProDescriptionsItemProps } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { useModel } from '@umijs/max';
import { App, Badge, Button, Drawer, FloatButton, Space } from 'antd';
import { useCallback, useRef, useState } from 'react';
import OrgEditModal from './components/OrgEditModal';

/** 机构管理 */
const OrgList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const { getDictValueEnum, getKeyDict } = useModel('useDict');
    const commonStatus = getKeyDict('common_status');

    const currentRef = useRef<Partial<API.SysOrgOutput>>();
    const [editShow, setEditShow] = useState(false);
    const [detailShow, setDetailShow] = useState(false);

    const { message, modal } = App.useApp();

    /** 删除 */
    const handleDelete = useCallback(async (id: number) => {
        modal.confirm({
            title: '消息',
            content: `确定立即删除吗`,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await SysOrgController.del({ id });
                message.success('已删除');
                actionRef.current?.reload();
            },
        });
    }, []);

    /** 变更状态 */
    const handleChangeStatus = useCallback(async (id: number, status: CommonStatus) => {
        modal.confirm({
            title: '消息',
            content: `确定立即${status === CommonStatus.ENABLE ? '停用' : '启用'}吗`,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await SysOrgController.changeStatus({ id });
                message.success('已变更');
                actionRef.current?.reload();
            },
        });
    }, []);

    const columns: ProColumns<API.SysOrgOutput>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            renderText: (v, r) => <a onClick={() => { currentRef.current = r; setDetailShow(true); }}>{v}</a>,
            width: 280,
            fixed: 'left',
        },
        {
            title: '简称',
            dataIndex: 'shortName',
            width: 160,
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '简称2',
            dataIndex: 'shortName2',
            width: 96,
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '全称',
            dataIndex: 'fullName',
            width: 320,
            hideInSearch: true,
        },
        {
            title: '代码',
            dataIndex: 'code',
            width: 64,
            align: 'center',
        },
        {
            title: '机构类型',
            dataIndex: 'orgType',
            valueEnum: getDictValueEnum('org_type'),
            width: 80,
            align: 'center',
            search: { transform: (v) => ({ orgType: JSON.parse(v) }) },
        },
        {
            title: '学段',
            dataIndex: 'educationStage',
            valueEnum: getDictValueEnum('education_stage'),
            width: 80,
            align: 'center',
            search: { transform: (v) => ({ educationStage: JSON.parse(v) }) },
        },
        {
            title: '城乡类别',
            dataIndex: 'urbanRuralType',
            valueEnum: getDictValueEnum('urban_rural_type'),
            width: 80,
            align: 'center',
            search: { transform: (v) => ({ urbanRuralType: JSON.parse(v) }) },
        },
        {
            title: '办学性质',
            dataIndex: 'orgFundSource',
            valueEnum: getDictValueEnum('org_fund_source'),
            width: 80,
            align: 'center',
            search: { transform: (v) => ({ orgFundSource: JSON.parse(v) }) },
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 64,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: getDictValueEnum('common_status', true),
            width: 128,
            align: 'center',
            hideInDescriptions: true,
            render: (v, r) => {
                return (
                    <Space size="middle">
                        {v}
                        <a onClick={() => handleChangeStatus(r.id, r.status)}
                        >{r.status === CommonStatus.ENABLE ? '停用' : '启用'}</a>
                    </Space>
                );
            },
            search: { transform: (v) => ({ status: JSON.parse(v) }) },
        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInSearch: true,
            hideInTable: true,
            render: (_, r) => {
                const s = commonStatus[r.status];
                if (!s) {
                    return '';
                }
                return (<Badge status={s.antStatus as any ?? 'default'} text={s.name} />);
            },
        },
        {
            title: 'TQES ID',
            dataIndex: 'tqesId',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: 'TQES 编码',
            dataIndex: 'tqesCode',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '备注',
            dataIndex: 'remark',
            hideInSearch: true,
            className: 'minw-80',
            width: 160,
        },
        {
            title: '操作',
            valueType: 'option',
            width: 112,
            align: 'center',
            fixed: 'right',
            render: (_, r) => {
                let ops: React.ReactNode[] = [];
                ops.push(<Button key="edit" type="link" size="small" onClick={() => { currentRef.current = r; setEditShow(true); }}>修改</Button>);
                ops.push(<Button key="del" type="link" size="small" onClick={() => handleDelete(r.id)}>删除</Button>);
                return (<>{ops}</>);
            },
        },
    ];

    return (
        <PageContainer title={false} childrenContentStyle={{ paddingTop: 0 }}>
            <SuperTable<API.SysOrgOutput>
                actionRef={actionRef}
                bordered
                headerTitle="机构列表"
                columns={columns}
                scroll={{ x: 'max-content', y: document.body.clientHeight - 336 }}
                virtual
                request={async (params) => {
                    const res = await SysOrgController.queryPageList({ ...params, pageIndex: 1, pageSize: 9999 });
                    return {
                        data: res?.items,
                        success: true,
                    };
                }}
                postData={(rows: API.SysOrgOutput[]) => {
                    const list = buildTableTreeData2(rows);
                    return list;
                }}
                toolbar={{
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => { currentRef.current = { id: 0 }; setEditShow(true); }}
                        >添加机构</Button>,
                    ],
                }}
                pagination={false}
            />
            <Drawer
                title="监测计划详情"
                open={detailShow}
                onClose={() => setDetailShow(false)}
                width="60%"
                className="yb-pro-desc hide-header"
            >
                <ProDescriptions<API.SysOrgOutput>
                    dataSource={currentRef.current as API.SysOrgOutput}
                    columns={columns as ProDescriptionsItemProps<API.SysOrgOutput>[]}
                    column={1}
                    size="small"
                    labelStyle={{ width: 128 }}
                />
            </Drawer>
            {editShow && currentRef.current &&
                <OrgEditModal
                    data={currentRef.current}
                    onFinish={() => actionRef.current?.reload()}
                    onClose={() => setEditShow(false)}
                />
            }
            <FloatButton.BackTop visibilityHeight={100} />
        </PageContainer>
    );
};

export default OrgList;
