import { toSelectOptions } from '@/common/converter';
import { SuperTable, TabBadge } from '@/components';
import ExamPlanController from '@/services/apis/ExamPlanController';
import { ExamStatus } from '@/services/enums';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { App, Button } from 'antd';
import { useCallback, useRef, useState } from 'react';
import ExamPlanEditModal from './components/ExamPlanEditModal';

/** 监测计划 */
const ExamPlanList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const currentRef = useRef<Partial<API.ExamPlanOutput>>();

    const [activeKey, setActiveKey] = useState<React.Key>('0');
    const [statusCount, seStatusCount] = useState<Record<number, number>>({});

    const [editShow, setEditShow] = useState(false);

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

    const { getDictValueEnum, getDict } = useModel('useDict');
    const { baseData } = useModel('useBaseData');

    // 加载数量统计
    const loadCount = useCallback(async (params: API.ExamPlanPageInput) => {
        const m = await ExamPlanController.queryStatusCount(params);
        const tc = m?.reduce((a, b) => a + b.count, 0) ?? 0;

        const d: Record<number, number> = { 0: tc };
        m?.forEach((t) => { d[t.status] = t.count; });

        seStatusCount(d);
    }, []);

    // 呈现状态 tab
    const renderTabItems = useCallback(() => {
        let items: { key: string; label: React.ReactNode }[] = [{
            key: '0',
            label: (<span>全部<TabBadge count={statusCount[0]} active={activeKey === 0} /></span>),
        }];
        items = items.concat(
            getDict('exam_status')?.map((t) => ({
                key: `${t.value}`,
                label: (
                    <span>
                        {t.name}
                        <TabBadge color={t.antColor} count={statusCount[t.value] ?? 0} active={activeKey === `${t.value}`} />
                    </span>
                ),
            })),
        );
        return items;
    }, [activeKey, statusCount]);

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

    const columns: ProColumns<API.ExamPlanOutput>[] = [
        {
            title: '监测全称',
            dataIndex: 'fullName',
            renderText: (v, r) => <a onClick={() => history.push(`/exam-c/plan/detail/${r.id}`)}>{v}</a>,
            hideInDescriptions: true,
        },
        {
            title: '监测全称',
            dataIndex: 'fullName',
            hideInTable: true,
            hideInSearch: true,
        },
        {
            title: '监测名称',
            dataIndex: 'name',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '监测简称',
            dataIndex: 'shortName',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '监测状态',
            dataIndex: 'status',
            valueEnum: getDictValueEnum('exam_status', true),
            width: 80,
            align: 'center',
            hideInDescriptions: true,
        },
        {
            title: '监测学期',
            dataIndex: ['semester', 'nickShortName'],
            search: {
                transform: (v) => v ? ({ semesterId: JSON.parse(v) }) : v,
            },
            valueType: 'select',
            fieldProps: {
                options: toSelectOptions(baseData?.semesters ?? [], (item) => ({ key: item.id, label: item.nickShortName, value: item.id })),
            },
            width: 80,
            align: 'center',
        },
        {
            title: '监测学段',
            dataIndex: 'educationStage',
            valueEnum: getDictValueEnum('education_stage'),
            width: 80,
            align: 'center',
        },
        {
            title: '开始时间',
            dataIndex: 'beginTime',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '备注说明',
            dataIndex: 'remark',
            hideInSearch: true,
            className: 'minw-120',
        },
        {
            title: '创建人',
            dataIndex: ['createSysUser', 'name'],
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            align: 'center',
            width: 144,
            valueType: 'dateRange',
            colSize: 2,
            render: (_, r) => r.createTime,
            search: {
                transform: (v) => v ? ({
                    searchBeginTime: v[0],
                    searchEndTime: v[1],
                }) : ({}),
            },
        },
        {
            title: '操作',
            valueType: 'option',
            width: 112,
            align: 'center',
            fixed: 'right',
            render: (_, r) => {
                let ops: React.ReactNode[] = [];
                if (r.status === ExamStatus.READY) {
                    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}>
            <SuperTable<API.ExamPlanOutput>
                actionRef={actionRef}
                columns={columns}
                scroll={{ x: 'max-content' }}
                request={async (params, sort) => {
                    try {
                        return SuperTable.requestPageAgent({ params, sort }, async (p) => {
                            await loadCount(p);
                            const res = await ExamPlanController.queryPageList({
                                ...p,
                                status: activeKey !== '0' ? parseInt(activeKey as string) : undefined,
                            });
                            return res;
                        });
                    }
                    catch (ex) { return {}; }
                }}
                toolbar={{
                    menu: {
                        type: 'tab',
                        activeKey: activeKey,
                        items: renderTabItems(),
                        onChange: (key) => {
                            setActiveKey(key as React.Key);
                            actionRef.current?.reload();
                        },
                    },
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => { currentRef.current = { id: 0 }; setEditShow(true); }}
                        >创建监测计划</Button>,
                    ],
                }}
            />
            {editShow && currentRef.current &&
                <ExamPlanEditModal
                    data={currentRef.current}
                    onFinish={() => actionRef.current?.reload()}
                    onClose={() => setEditShow(false)}
                />
            }
        </PageContainer>
    );
};

export default ExamPlanList;
