import { CardStepTitle, SuperTable, TagStatus } from "@/components";
import ExamSampleController from "@/services/apis/ExamSampleController";
import ExamStudentController from "@/services/apis/ExamStudentController";
import { CheckCircleFilled } from "@ant-design/icons";
import { ActionType, PageContainer, ProCard, ProColumns, ProDescriptions } from "@ant-design/pro-components";
import { useEmotionCss } from "@ant-design/use-emotion-css";
import { history, useModel, useParams } from "@umijs/max";
import { useRequest } from "ahooks";
import { App, FloatButton, Tag, theme, Typography } from "antd";
import lodash from 'lodash';
import { useCallback, useRef } from "react";

type ClassItem = API.ExamStudentCountItem & {
    isFirstGrade: boolean;

    classes: {
        [key: number]: {
            schoolClassId: string;
            studentCount: number;
            isSampleAll: boolean;
        }
    }
};

const EnabledStatus: React.FC<{ enabled: boolean; enabledText?: string; disabledText?: string; }> = ({ enabled, enabledText, disabledText }) => {
    return (<Tag color={enabled ? 'success' : 'error'}>{enabled ? enabledText ?? '启用' : disabledText ?? '禁用'}</Tag>);
}

const ExamSampleDetail: React.FC = () => {
    const reqParams = useParams() as unknown as { id: number };

    const classStuCountClassName = useEmotionCss(({ token }) => {
        return {
            position: 'relative',
            borderRadius: token.borderRadiusXS,
            '&.selected': {
                color: token.colorWhite,
                backgroundColor: token.colorSuccess,
                paddingRight: token.paddingSM,
                '.check-icon': {
                    position: 'absolute',
                    bottom: 2,
                    right: 2,
                    fontSize: token.fontSizeSM,
                }
            },
            ':hover': {
                cursor: 'pointer',
                backgroundColor: token.colorLinkHover,
            }
        };
    });

    const { token } = theme.useToken();
    const { getDictValueEnum, getKeyDict } = useModel('useDict');
    const examSampleStatusDict = getKeyDict('exam_sample_status');

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

    const actionRef = useRef<ActionType>();
    // const currentRef = useRef<Partial<API.ExamStudentCountItem>>();

    const { data, run, loading } = useRequest(async () => {
        const examSample = await ExamSampleController.getById({ id: reqParams.id });
        const res = await ExamStudentController.queryStudentCountPageList({ pageIndex: 1, pageSize: 9999, examPlanId: examSample?.examPlanId ?? 0 });

        const maxClassNumber = (lodash.maxBy(res?.items, 'classNumber') as any)?.classNumber ?? 0;

        const hasInAll = (schoolClassId: string) => examSample?.config.sampleAllSchoolClassIds?.some(t => t === schoolClassId) ?? false;

        let list: ClassItem[] = [];
        res?.items?.forEach(t => {
            let item = list.find(o => o.sysOrgId === t.sysOrgId && o.gradeId === t.gradeId) as ClassItem;
            if (!item) {
                item = {
                    ...t,
                    isFirstGrade: !list.some(o => o.sysOrgId === t.sysOrgId),
                    classes: {
                        [t.classNumber]: {
                            schoolClassId: t.schoolClassId,
                            studentCount: t.studentCount,
                            isSampleAll: hasInAll(t.schoolClassId),
                        },
                    }
                } as ClassItem;
                list.push(item);
            }
            else {
                item.classes[t.classNumber] = {
                    schoolClassId: t.schoolClassId,
                    studentCount: t.studentCount,
                    isSampleAll: hasInAll(t.schoolClassId),
                };
            }
        });

        return {
            examSample,
            list,
            maxClassNumber,
        };
    });

    // 切换班级全抽
    const handleSwitchAll = useCallback(async (schoolClassId: string, isAdd: boolean) => {
        modal.confirm({
            // title: `提示`,
            content: `确认${isAdd ? '加入' : '取消'}全抽吗？`,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamSampleController.switchExamSampleAllClass({
                    id: reqParams.id,
                    schoolClassId,
                    isAdd,
                });
                message.success(`${isAdd ? '加入' : '取消'}`);
                run();
                actionRef.current?.reload();
            },
        });
    }, []);

    // 班级列
    const classColumns = lodash.range(1, (data?.maxClassNumber ?? 0) + 1).map(cn => {
        return {
            title: cn,
            dataIndex: ['classes', `${cn}`, 'studentCount'],
            width: 56,
            align: 'center',
            hideInSearch: true,
            render: (v, r: ClassItem) => {
                const c = r.classes[cn];
                if (!c) {
                    return null;
                }
                if (data?.examSample?.isFixedExamSample) {
                    return (
                        <div className={`${classStuCountClassName}${c?.isSampleAll ? ' selected' : ''}`}>
                            {v}
                            {c?.isSampleAll && <CheckCircleFilled className="check-icon" />}
                        </div>
                    );
                }
                return (
                    <div
                        className={`${classStuCountClassName}${c?.isSampleAll ? ' selected' : ''}`}
                        onClick={() => handleSwitchAll(c.schoolClassId, !c.isSampleAll)}
                    >
                        {v}
                        {c?.isSampleAll && <CheckCircleFilled className="check-icon" />}
                    </div>
                );
            },
        } as ProColumns;
    }) ?? [];

    const columns: ProColumns<ClassItem>[] = [
        {
            title: '学校代码',
            dataIndex: 'sysOrgCode',
            width: 80,
            align: 'center',
            onCell: (r) => {
                if (r.isFirstGrade === true) {
                    return { rowSpan: r.gradeCount };
                }
                return { rowSpan: 0 };
            },
        },
        {
            title: '学校名称',
            dataIndex: 'sysOrgName',
            width: 180,
            onCell: (r) => {
                if (r.isFirstGrade === true) {
                    return { rowSpan: r.gradeCount };
                }
                return { rowSpan: 0 };
            },
        },
        {
            title: '城乡类别',
            dataIndex: 'urbanRuralType',
            valueEnum: getDictValueEnum('urban_rural_type'),
            width: 80,
            align: 'center',
            onCell: (r) => {
                if (r.isFirstGrade === true) {
                    return { rowSpan: r.gradeCount };
                }
                return { rowSpan: 0 };
            },
        },
        {
            title: '年级',
            dataIndex: 'gradeName',
            // render: (v, r) => {
            //     return `${v}（${r.gradeBeginYear}级）`;
            // },
            width: 80,
            align: 'center',
        },
        {
            title: '学生人数',
            dataIndex: 'studentCount',
            valueType: 'digitRange',
            hideInTable: true,
            search: {
                transform: (v) => ({
                    studentCountMin: v[0],
                    studentCountMax: v[1],
                }),
            },
            fieldProps: {
                placeholder: ['最少数量', '最多数量'],
            },
        },
        ...classColumns,
    ];

    const status = data?.examSample?.status ? examSampleStatusDict[data?.examSample?.status] : undefined;

    return (
        <PageContainer
            title={data?.examSample?.fullName}
            onBack={() => history.back()}
        >
            <ProCard
                title={<CardStepTitle>基本信息</CardStepTitle>}
            >
                <ProDescriptions size="small">
                    <ProDescriptions.Item label="监测名称">
                        {data?.examSample?.name}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="监测简称">
                        {data?.examSample?.shortName}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="抽样比例">
                        {data?.examSample?.config?.percent}%
                    </ProDescriptions.Item>
                    <ProDescriptions.Item
                        label="年级限制"
                        tooltip="年级仅有一个班，且该班学生人数小于等于X人，该班全抽"
                    >
                        <EnabledStatus enabled={data?.examSample?.config?.isEnabledOnlyOneClassStudentMin ?? false} />
                        {data?.examSample?.config?.isEnabledOnlyOneClassStudentMin ? data?.examSample?.config?.onlyOneClassStudentMin : ''}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item
                        label="最少未抽"
                        tooltip="年级多于一个班，且年级未抽样部分学生人数小于X人，该年级全抽"
                    >
                        <EnabledStatus enabled={data?.examSample?.config?.isEnabledGradeNoSampleStudentMin ?? false} />
                        {data?.examSample?.config?.isEnabledGradeNoSampleStudentMin ? data?.examSample?.config?.gradeNoSampleStudentMin : ''}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item
                        label="班级限制"
                        tooltip="班级学生人数小于等于X人，该班全抽"
                    >
                        <EnabledStatus enabled={data?.examSample?.config?.isEnabledClassStudentMin ?? false} />
                        {data?.examSample?.config?.isEnabledClassStudentMin ? data?.examSample?.config?.classStudentMin : ''}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item
                        label="特殊排除"
                        tooltip="抽样时排除特殊学生"
                    >
                        <EnabledStatus enabled={data?.examSample?.config?.isExcludeSpecialStudent ?? false} />
                        {data?.examSample?.config?.specialStudentMustApproved ? '（仅审核已通过不参与抽样）' : '（待审核和审核已通过均不参与抽样）'}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item
                        label="随机序号"
                        tooltip="在年级内随机打乱监测号顺序"
                    >
                        <EnabledStatus enabled={data?.examSample?.config?.isGradeSeatNumberRandom ?? false} />
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="抽样方式">
                        {data?.examSample?.config.isRandomSampling ? '随机抽样' : '等距抽样'}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="开始位置">
                        {data?.examSample?.config.startPosition}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="抽样间距">
                        {data?.examSample?.config.interval}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="方案状态">
                        <TagStatus status={status?.antStatus} fill>{status?.name}</TagStatus>
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="方案选定">
                        <EnabledStatus enabled={data?.examSample?.isSelected ?? false} enabledText="已选定" disabledText="未选定" />
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="成绩引用">
                        {data?.examSample?.examScoreRefExamPlan?.name ?? <Typography.Text type="danger">未设置</Typography.Text>}
                    </ProDescriptions.Item>
                </ProDescriptions>
            </ProCard>
            <SuperTable<ClassItem>
                style={{ marginTop: token.margin }}
                actionRef={actionRef}
                loading={loading}
                search={false}
                // search={{ filterType: 'light' }}
                scroll={{ x: 'max-content' }}
                toolbar={{
                    title: <CardStepTitle>全抽班级</CardStepTitle>,
                    subTitle: !data?.examSample?.isFixedExamSample ? '点击下面班级单元格切换全抽班级' : '',
                }}
                options={{ setting: false, fullScreen: false }}
                rowKey="schoolClassId"
                columns={columns}
                dataSource={data?.list ?? []}
                pagination={false}
            />

            <FloatButton.BackTop visibilityHeight={100} />
        </PageContainer>
    );
}

export default ExamSampleDetail;
