import { downloadFileByBlob } from "@/common/net/download";
import { TrueOrFalseValueEnum } from "@/common/valueEnum";
import { CardStepTitle, StatusIcon, TagStatus } from "@/components";
import ExamSampleController from "@/services/apis/ExamSampleController";
import { ExamSampleStatus } from "@/services/enums";
import { ActionType, ProTable, TableDropdown } from "@ant-design/pro-components";
import { history, useModel } from "@umijs/max";
import { App, Button, Space, Tooltip, Typography, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import ExamSampleEditModal from "./ExamSampleEditModal";

/** 监测抽样管理 */
const ExamSampleList: React.FC<{
    /** 监测计划ID */
    examPlanId: number;
}> = ({ examPlanId }) => {
    const { token } = theme.useToken();

    const actionRef = useRef<ActionType>();
    const [editOpen, setEditOpen] = useState(false);

    const currentRef = useRef<Partial<API.ExamSampleOutput>>();
    const { getDictValueEnum } = useModel('useDict');

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

    // 复制
    const handleDuplicate = useCallback((id: number) => {
        modal.confirm({
            content: '确认复制当前抽样方案吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamSampleController.duplicate({ id });
                message.success('已复制');
                actionRef.current?.reload();
            },
        });
    }, [actionRef.current]);

    // 删除
    const handleDelete = useCallback((id: number) => {
        modal.confirm({
            content: '确认删除当前抽样方案吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamSampleController.del({ id });
                message.success('已删除');
                actionRef.current?.reload();
            },
        });
    }, [actionRef.current]);

    // 选定
    const handleSelect = useCallback((id: number) => {
        modal.confirm({
            content: '确认选定当前抽样方案作为最终方案吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamSampleController.selectSample({ id });
                message.success('已选定');
                actionRef.current?.reload();
            },
        });
    }, [actionRef.current]);

    // 生成
    const handleGenerate = useCallback((id: number) => {
        modal.confirm({
            content: '请仔细确认参数设置是否正确（如成绩引用、特殊学生排除、抽样比例和人数等），确定立即生成抽样吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: () => {
                ExamSampleController.executeSample({ id }, { timeout: 600000 });
                message.success('已提交');
                setTimeout(() => actionRef.current?.reload(), 1000);
            },
        });
    }, [actionRef.current]);

    // 下载存档
    const handleDownloadArchived = useCallback(async (id: number) => {
        try {
            message.loading('正在生成文件，请稍侯');
            const res = await ExamSampleController.exportToArchived({ id }, { timeout: 600000 });
            if (res) {
                downloadFileByBlob(res.data, res.fileName);
            }
        }
        catch { }
        finally {
            message.destroy();
        }
    }, []);

    // 下载发印刷厂
    const handleDownloadPrintshop = useCallback(async (id: number) => {
        try {
            message.loading('正在生成文件，请稍侯');
            const res = await ExamSampleController.exportToPrintshop({ id }, { timeout: 600000 });
            if (res) {
                downloadFileByBlob(res.data, res.fileName);
            }
        }
        catch { }
        finally {
            message.destroy();
        }
    }, []);

    // 下载统计表
    const handleDownloadCount = useCallback(async (id: number) => {
        try {
            message.loading('正在生成文件，请稍侯');
            const res = await ExamSampleController.exportSampleCount({ id });
            if (res) {
                downloadFileByBlob(res.data, res.fileName);
            }
        }
        catch { }
        finally {
            message.destroy();
        }
    }, []);

    return (
        <>
            <ProTable<API.ExamSampleOutput>
                headerTitle={<CardStepTitle>监测抽样</CardStepTitle>}
                style={{ marginTop: token.margin }}
                search={false}
                size="small"
                bordered
                sticky={{ offsetHeader: 56 }}
                actionRef={actionRef}
                options={{ density: false, fullScreen: false, setting: false }}
                scroll={{ x: 'max-content' }}
                pagination={false}
                columns={[
                    {
                        title: '序',
                        dataIndex: 'sequence',
                        width: 32,
                        align: 'center',
                        hideInSearch: true,
                    },
                    {
                        title: '方案简称',
                        dataIndex: 'name',
                        render: (v, r) => {
                            return (<a onClick={() => history.push(`/exam-c/plan/sample/detail/${r.id}`)}>{v}</a>);
                        },
                    },
                    {
                        title: '成绩引用',
                        dataIndex: 'examScoreRefExamPlanId',
                        width: 96,
                        align: 'center',
                        render: (_, r) => {
                            return (
                                <Tooltip title={r.examScoreRefExamPlan?.name ?? '未设置'}>
                                    <StatusIcon filled status={(r.examScoreRefExamPlanId ?? 0) > 0 ? 'success' : 'error'} />
                                </Tooltip>
                            );
                        },
                    },
                    {
                        title: '抽样方式',
                        dataIndex: ['config', 'isRandomSampling'],
                        width: 80,
                        align: 'center',
                        render: (_, r) => {
                            return r.config.isRandomSampling ? '随机抽样' : '等距抽样';
                        },
                    },
                    {
                        title: '抽样比例',
                        dataIndex: ['config', 'percent'],
                        valueType: () => ({
                            type: 'percent',
                            precision: 1,
                        }),
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '年级限制',
                        tooltip: '年级仅有一个班，且该班学生人数小于等于X人，该班全抽',
                        dataIndex: ['config', 'onlyOneClassStudentMin'],
                        width: 96,
                        align: 'center',
                        render: (v, r) => {
                            return (
                                <>
                                    <StatusIcon status={r.config.isEnabledOnlyOneClassStudentMin ? 'success' : 'forbid'} />
                                    <span style={{ display: 'inline-block', width: 32, textAlign: 'right' }}>{v}</span>
                                </>
                            );
                        },
                    },
                    {
                        title: '最少未抽',
                        tooltip: '年级多于一个班，且年级未抽样部分学生人数小于X人，该年级全抽',
                        dataIndex: ['config', 'gradeNoSampleStudentMin'],
                        width: 96,
                        align: 'center',
                        render: (v, r) => {
                            return (
                                <>
                                    <StatusIcon status={r.config.isEnabledGradeNoSampleStudentMin ? 'success' : 'forbid'} />
                                    <span style={{ display: 'inline-block', width: 32, textAlign: 'right' }}>{v}</span>
                                </>
                            );
                        },
                    },
                    {
                        title: '班级限制',
                        tooltip: '班级学生人数小于等于X人，该班全抽',
                        dataIndex: ['config', 'classStudentMin'],
                        width: 96,
                        align: 'center',
                        render: (v, r) => {
                            return (
                                <>
                                    <StatusIcon status={r.config.isEnabledClassStudentMin ? 'success' : 'forbid'} />
                                    <span style={{ display: 'inline-block', width: 32, textAlign: 'right' }}>{v}</span>
                                </>
                            );
                        },
                    },
                    {
                        title: '特殊排除',
                        tooltip: '抽样时排除特殊学生',
                        dataIndex: ['config', 'isExcludeSpecialStudent'],
                        width: 96,
                        align: 'center',
                        render: (_, r) => {
                            const s = TrueOrFalseValueEnum[`${r.config.isExcludeSpecialStudent ?? 'false'}`];
                            return (<TagStatus status={s.status}>{s.text}</TagStatus>);
                        },
                    },
                    {
                        title: '随机序号',
                        tooltip: '在年级内随机打乱监测号顺序',
                        dataIndex: ['config', 'isGradeSeatNumberRandom'],
                        width: 96,
                        align: 'center',
                        render: (_, r) => {
                            const s = TrueOrFalseValueEnum[`${r.config.isGradeSeatNumberRandom ?? 'false'}`];
                            return (<TagStatus status={s.status}>{s.text}</TagStatus>);
                        },
                    },
                    {
                        title: '开始位置',
                        dataIndex: ['config', 'startPosition'],
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '间距',
                        dataIndex: ['config', 'interval'],
                        width: 64,
                        align: 'center',
                    },
                    {
                        title: '全抽班级',
                        dataIndex: ['config', 'sampleAllSchoolClassIds'],
                        width: 96,
                        align: 'center',
                        render: (_, r) => `${r.config.sampleAllSchoolClassIds?.length ?? 0}个`,
                    },
                    {
                        title: '方案状态',
                        dataIndex: 'status',
                        valueEnum: getDictValueEnum('exam_sample_status', true),
                        width: 96,
                        align: 'center',
                    },
                    {
                        title: '已选定',
                        dataIndex: 'isSelected',
                        width: 96,
                        // align: 'center',
                        render: (_, r) => {
                            const s = TrueOrFalseValueEnum[`${r.isSelected}`];
                            return (
                                <Space>
                                    <TagStatus status={r.isSelected ? 'success' : 'error'}>{s.text}</TagStatus>
                                    {!r.isFixedExamSample && r.status === ExamSampleStatus.SUCCESSFUL &&
                                        <a onClick={() => handleSelect(r.id)}>选定</a>
                                    }
                                </Space>
                            )
                        },
                    },
                    {
                        title: '操作',
                        valueType: 'option',
                        width: 96,
                        fixed: 'right',
                        render: (_, r) => {
                            let menuItems: any[] = [];
                            if (!r.isFixedExamSample) {
                                menuItems = [
                                    { key: 'delete', name: '删除' },
                                    { key: 'copy', name: '复制' },
                                    { key: 'generate', name: r.status === ExamSampleStatus.INITIAL ? '生成' : '重新生成' },
                                ];
                            }
                            if (r.status === ExamSampleStatus.SUCCESSFUL) {
                                menuItems = [
                                    ...menuItems,
                                    { key: 'download-archived', name: '下载发归档文件' },
                                    { key: 'download-print-shop', name: '下载发印刷厂文件' },
                                    { key: 'download-count', name: '下载统计表' },
                                ];
                            }
                            return (
                                <Space>
                                    {!r.isFixedExamSample &&
                                        <a onClick={() => { currentRef.current = r; setEditOpen(true); }}>修改</a>
                                    }
                                    <TableDropdown
                                        onSelect={(key) => {
                                            switch (key) {
                                                case 'delete':
                                                    handleDelete(r.id);
                                                    break;
                                                case 'copy':
                                                    handleDuplicate(r.id);
                                                    break;
                                                case 'generate':
                                                    handleGenerate(r.id);
                                                    break;
                                                case 'download-archived':
                                                    handleDownloadArchived(r.id);
                                                    break;
                                                case 'download-print-shop':
                                                    handleDownloadPrintshop(r.id);
                                                    break;
                                                case 'download-count':
                                                    handleDownloadCount(r.id);
                                                    break;
                                            }
                                        }}
                                        menus={menuItems}
                                    />
                                </Space>
                            );
                        },
                    }
                ]}
                rowKey="id"
                toolbar={{
                    subTitle: (<Typography.Text type="warning">发布前重点核对<Typography.Text type="danger" strong>成绩引用</Typography.Text>、人数和特殊学生！</Typography.Text>),
                    actions: [
                        <Button
                            key="setting"
                            type="primary"
                            onClick={() => {
                                currentRef.current = {
                                    id: 0,
                                    examPlanId,
                                };
                                setEditOpen(true);
                            }}
                        >添加抽样</Button>,
                    ],
                }}
                request={async () => {
                    const res = await ExamSampleController.getListByExamPlanId({ examplanid: examPlanId });
                    return {
                        data: res ?? [],
                        success: true,
                    };
                }}
            />
            {editOpen && currentRef.current &&
                <ExamSampleEditModal
                    data={currentRef.current}
                    onFinish={() => { actionRef.current?.reload(); }}
                    onClose={() => setEditOpen(false)}
                />
            }
        </>
    );
}

export default ExamSampleList;
