import { toValueEnum } from "@/common/converter";
import { downloadFileByBlob } from "@/common/net/download";
import { CardStepTitle, SuperTable } from "@/components";
import ExamGradeController from "@/services/apis/ExamGradeController";
import ExamSampleController from "@/services/apis/ExamSampleController";
import ExamSampleStudentController from "@/services/apis/ExamSampleStudentController";
import SysOrgController from "@/services/apis/SysOrgController";
import { DataPublishType, ExamSampleType } from "@/services/enums";
import { DownloadOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import { history, useModel, useParams } from "@umijs/max";
import { useRequest } from "ahooks";
import { App, Button, Spin, theme } from "antd";
import { useRef } from "react";

/** 监测抽样学生名单 */
const OrgExamSampleList: React.FC = () => {
    const reqParams = useParams() as unknown as { examDataPublishId: number };

    const { token } = theme.useToken();
    const { getDictValueEnum } = useModel('useDict');

    const actionRef = useRef<ActionType>();
    const { message } = App.useApp();

    const { initialState } = useModel('@@initialState');
    const { currentUser } = initialState ?? {};

    const { data, loading } = useRequest(async () => {
        const orgRes = await SysOrgController.getOrgBranchByOrgId({ orgid: currentUser?.sysOrgId ?? 0 });
        const sampleRes = await ExamSampleController.getByExamDataPublishId({ examdatapublishid: reqParams.examDataPublishId, type: DataPublishType.STUDENT_SAMPLE_LIST });
        const egRes = await ExamGradeController.getListByExamPlanId({ examplanid: sampleRes?.examPlanId ?? 0 });
        return {
            examGrades: egRes ?? [],
            branches: orgRes ?? [],
            hasDistrict: (orgRes?.length ?? 0) > 0,
            examSample: sampleRes,
        };
    });

    // 明细表列定义
    const columns: ProColumns<API.ExamSampleStudentOutput>[] = [
        {
            title: '名单类型',
            dataIndex: 'examSampleType',
            valueEnum: getDictValueEnum('exam_sample_type', false, [ExamSampleType.SCHOOL]),
            width: 72,
            align: 'center',
            search: {
                transform: (v) => ({ examSampleType: JSON.parse(v) }),
            },
        },
        ...(data?.hasDistrict ? [{
            title: '校区',
            dataIndex: ['examStudent', 'sysOrgBranchId'],
            width: 96,
            align: 'center',
            hideInSearch: !data?.hasDistrict,
            valueEnum: toValueEnum(data?.branches ?? []),
            search: {
                transform: (v) => ({ sysOrgBranchId: v }),
            },
        } as ProColumns] : []),
        {
            title: '年级',
            dataIndex: ['examStudent', 'examGrade', 'gradeId'],
            width: 144,
            align: 'center',
            valueEnum: toValueEnum(data?.examGrades?.map(t => ({ id: t.gradeId, name: `${t.grade.name}（${t.gradeBeginName}）` })) ?? []),
            search: {
                transform: (v) => ({ gradeId: v }),
            },
        },
        {
            title: '班级',
            dataIndex: ['examStudent', 'classNumber'],
            width: 64,
            align: 'center',
            renderText: (v) => `${v}班`,
            search: {
                transform: (v) => ({ classNumber: v }),
            },
        },
        {
            title: '监测号',
            dataIndex: 'examNumber',
            width: 128,
            align: 'center',
        },
        {
            title: '姓名',
            dataIndex: ['examStudent', 'name'],
            width: 160,
            align: 'center',
            search: {
                transform: (v) => ({ name: v }),
            },
        },
        {
            title: '证件类型',
            dataIndex: ['examStudent', 'certificateType'],
            valueEnum: getDictValueEnum('certificate_type'),
            width: 112,
            align: 'center',
            search: {
                transform: (v) => ({ certificateType: JSON.parse(v) }),
            },
        },
        {
            title: '证件号码',
            dataIndex: ['examStudent', 'idNumber'],
            width: 160,
            align: 'center',
            search: {
                transform: (v) => ({ idNumber: v }),
            },
        },
    ];

    return (
        <PageContainer
            title={`${data?.examSample?.examPlan?.fullName ?? '监测计划'} - 监测抽样学生名单`}
            onBack={() => history.back()}
        >
            <Spin spinning={loading}>
                {data?.examSample?.id &&
                    <>
                        <SuperTable<API.ExamSampleStudentOutput>
                            headerTitle={<CardStepTitle>监测抽样学生名单</CardStepTitle>}
                            style={{ marginTop: token.margin }}
                            actionRef={actionRef}
                            scroll={{ x: 'max-content' }}
                            // loading={loading}
                            rowKey="id"
                            columnEmptyText=""
                            columns={columns}
                            toolbar={{
                                actions: [
                                    <Button
                                        key="export"
                                        type="primary"
                                        icon={<DownloadOutlined />}
                                        disabled={!data?.examSample?.id}
                                        onClick={async () => {
                                            try {
                                                message.loading('正在生成文件，请稍侯');
                                                if (!data?.examSample?.id) {
                                                    return;
                                                }
                                                const res = await ExamSampleController.exportToOrg({ id: data?.examSample?.id });
                                                if (res) {
                                                    downloadFileByBlob(res.data, res.fileName);
                                                }
                                            }
                                            catch { }
                                            finally {
                                                message.destroy();
                                            }
                                        }}
                                    >下载检录表</Button>,
                                    <Button
                                        key="export"
                                        icon={<DownloadOutlined />}
                                        disabled={!data?.examSample?.id}
                                        onClick={async () => {
                                            try {
                                                message.loading('正在生成文件，请稍侯');
                                                if (!data?.examSample?.id) {
                                                    return;
                                                }
                                                const res = await ExamSampleController.exportSampleCountToOrg({ id: data?.examSample?.id });
                                                if (res) {
                                                    downloadFileByBlob(res.data, res.fileName);
                                                }
                                            }
                                            catch { }
                                            finally {
                                                message.destroy();
                                            }
                                        }}
                                    >下载统计表</Button>,
                                ],
                            }}
                            request={async (params, sort) => {
                                return SuperTable.requestPageAgent({ params, sort }, async (p) => {
                                    const res = await ExamSampleStudentController.queryPageList({ ...p, examSampleId: data?.examSample?.id ?? 0 });
                                    return res;
                                });
                            }}
                        />
                    </>
                }
            </Spin>
        </PageContainer>
    );
}

export default OrgExamSampleList;
