import { CardStepTitle, StatusIcon, UploadWrongLocalHeaderError } from "@/components";
import ExamTeacherController from "@/services/apis/ExamTeacherController";
import { CertificateType, DataImportMode, Gender, SchoolJobTitle } from "@/services/enums";
import { BulbOutlined, InboxOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProCard, ProColumns, ProTable } from "@ant-design/pro-components";
import { useModel, useParams } from "@umijs/max";
import { Alert, App, Button, Space, Tooltip, Tour, Typography, Upload, theme } from "antd";
import type { RcFile, UploadFile, UploadProps } from "antd/lib/upload/interface";
import { useRef, useState } from "react";
import ExamTeacherImportEditModal from "./components/ExamTeacherImportEditModal";

/** 监测教师批量导入 */
const OrgExamTeacherImport: React.FC = () => {
    const reqParams = useParams() as unknown as { examPlanId: number };

    const actionRef = useRef<ActionType>();

    const [tourOpen, setTourOpen] = useState(false);
    const currentRef = useRef<API.UploadExamTeacherOutput>();
    const [editOpen, setEditOpen] = useState(false);

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

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

    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const [data, setData] = useState<API.UploadExamDataOutput_UploadExamTeacherOutput>();

    const tourDownloadRef = useRef(null);
    const tourChooseFileRef = useRef(null);
    const tourUploadRef = useRef(null);
    const tourTeacherCountRef = useRef(null);
    const tourStuDetailRef = useRef(null);
    const tourSubmitRef = useRef(null);


    const uploadProps: UploadProps = {
        onRemove: () => {
            setFileList([]);
        },
        beforeUpload: (file) => {
            setFileList([file]);

            return false;
        },
        fileList,
        multiple: false,
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
    };

    const handleBack = () => history.back();

    // 计算统计数据
    const handleClassTotal = (rows: API.UploadExamTeacherOutput[]) => {
        const total = rows.length;
        const s = rows.filter(t => t.isSuccess === true)?.length ?? 0;
        setData(v => ({ ...v, totalRowCount: total, successRowCount: s, errorRowCount: total - s }));
    }

    // 上传
    const handleUpload = async () => {
        const formData = new FormData();
        formData.append('examPlanId', `${reqParams.examPlanId}`);
        fileList.forEach((file) => {
            formData.append('file', file as RcFile);
        });
        setUploading(true);
        try {
            const res = await ExamTeacherController.upload(formData);
            setData(res);
        }
        catch { }
        finally {
            setUploading(false);
        }
    }

    // 保存编辑
    const handleEdit = (v: API.UploadExamTeacherOutput) => {
        const i = data?.rows?.findIndex(t => t.rowNumber === v.rowNumber) ?? -1;
        if (i !== -1) {
            const d = { ...data };
            if (d.rows) {
                d.rows[i] = v;
                setData(d);
                handleClassTotal(d.rows ?? []);
            }
        }
    }

    // 删除行
    const handleDelete = (rowNumber: number) => {
        modal.confirm({
            title: '警告',
            content: '确定立即删除吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                const i = data?.rows?.findIndex(t => t.rowNumber === rowNumber) ?? -1;
                if (i !== -1) {
                    const d = { ...data };
                    if (d.rows) {
                        d.rows.splice(i, 1);
                        setData(d);
                        handleClassTotal(d.rows ?? []);
                        message.success('已删除');
                        return;
                    }
                }
                message.error('删除失败');
            },
        });
    }

    // 确认导入
    const handleImport = async () => {
        const sysOrgId = currentUser?.sysOrgId;
        if (!sysOrgId) {
            message.error('获取机构ID错误');
            return;
        }

        const items = [...(data?.rows ?? [])];
        if (items.some(t => t.isSuccess === false)) {
            message.error('还有校验未通过的数据不能导入');
            return;
        }
        await ExamTeacherController.importAction({
            examPlanId: reqParams.examPlanId,
            items: items.map(t => ({
                examPlanId: reqParams.examPlanId,
                certificateType: t.certificateType ? JSON.parse(`${t.certificateType}`) : CertificateType.NONE,
                idNumber: t.idNumber?.toUpperCase(),
                name: t.name,
                gender: t.gender ? JSON.parse(`${t.gender}`) : Gender.UNKNOWN,
                schoolJobTitle: t.schoolJobTitle ? JSON.parse(`${t.schoolJobTitle}`) : SchoolJobTitle.TEACHER,
                mobile: t.mobile,
                email: t.email,
                remark: t.remark,
            })),
            dataImportMode: DataImportMode.CLEAR_APPEND,
        });
        message.success('导入成功');
        handleBack();
    }

    const columns: ProColumns<API.UploadExamTeacherOutput>[] = [
        {
            title: '验证',
            valueType: 'option',
            width: 48,
            align: 'center',
            render: (_, r) => {
                if (r.isSuccess) {
                    return (<StatusIcon status="success" filled />);
                }
                return (
                    <Tooltip title={r.errorMessage}>
                        <StatusIcon status="error" filled />
                    </Tooltip>
                );
            },
        },
        {
            title: '行号',
            valueType: 'option',
            render: (v, _, index) => {
                return <Typography.Text type="secondary">{index + 1}</Typography.Text>;
            },
            width: 48,
            align: 'center',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            align: 'center',
            width: 120,
            // className: 'minw-80',
        },
        {
            title: '证件类型',
            dataIndex: 'certificateType',
            valueEnum: getDictValueEnum('certificate_type'),
            width: 120,
            align: 'center',
        },
        {
            title: '证件号码',
            dataIndex: 'idNumber',
            width: 160,
            align: 'center',
        },
        {
            title: '性别',
            dataIndex: 'gender',
            valueEnum: getDictValueEnum('gender'),
            width: 48,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '校内职务',
            dataIndex: 'schoolJobTitle',
            valueEnum: getDictValueEnum('school_job_title'),
            width: 112,
            align: 'center',
        },
        {
            title: '手机号码',
            dataIndex: 'mobile',
            width: 112,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '电子邮箱',
            dataIndex: 'email',
            width: 128,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
            hideInSearch: true,
            width: 96,
        },
        {
            title: '校验结果',
            dataIndex: 'errorMessage',
            ellipsis: true,
            hideInSearch: true,
            width: 280,
            render: (_, r) => {
                if (r.isSuccess) {
                    return '通过';
                }
                return `${r.errorMessage?.join('、')}有误`;
            },
        },
        {
            title: '操作',
            valueType: 'option',
            fixed: 'right',
            width: 112,
            align: 'center',
            render: (_, r) => {
                return (
                    <>
                        <Button type="link" size="small" onClick={() => {
                            currentRef.current = { ...r };
                            setEditOpen(true);
                        }}>修改</Button>
                        <Button type="link" size="small" onClick={() => handleDelete(r.rowNumber)}>删除</Button>
                    </>
                );
            },
        },
    ];

    return (
        <PageContainer
            title="监测教师批量导入"
            onBack={handleBack}
            extra={
                <Button
                    type="link"
                    icon={<BulbOutlined />}
                    onClick={() => {
                        window.scrollTo({ top: 0 });
                        setTourOpen(true);
                    }}
                >查看操作指引</Button>
            }
        >
            <ProCard
                title={<CardStepTitle>第一步：下载模板</CardStepTitle>}
                extra={
                    <Button
                        type="primary"
                        ref={tourDownloadRef}
                        onClick={() => {
                            window.open('/doc-templates/教师信息上报-填报模板.xlsx');
                        }}
                    >下载模板</Button>
                }
                style={{ marginTop: token.margin }}
            >
                <Typography.Paragraph>
                    <Typography.Text type="warning" strong>批量上传文件填写说明及注意事项：</Typography.Text>
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>模板格式：</Typography.Text>
                    模板文件中第一行为填写说明，第二行为标题行（从A至H列分别为姓名、证件类型、证件号码、性别、校内职务、手机号码、电子邮箱、备注）。
                    <Typography.Text type="danger">填报数据必须在第一个工作表，并不能删除填写说明和标题行，不能删除和添加表格列！</Typography.Text>
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>A. 姓名</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    教师真实姓名。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>B. 证件类型</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    有居民身份证时，必须选择居民身份证，特殊情况可选择其他证件类型。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>C. 证件号码</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    有证件类型时必须填写，居民身份证为18位系统会进行严格的验证。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>D. 性别</Typography.Text>：
                    证件类型选择为居民身份证时会自动处理。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>E. 校内职务</Typography.Text>：
                    校长、副校长必填，未填写校内职务的会自动识别为教师。
                </Typography.Paragraph>
            </ProCard>

            <ProCard
                title={<CardStepTitle>第二步：上传文件</CardStepTitle>}
                style={{ marginTop: token.margin }}
                ref={tourChooseFileRef}
            >
                <Space direction="vertical" style={{ width: '100%' }}>
                    <Upload.Dragger {...uploadProps}>
                        <p className="ant-upload-drag-icon"><InboxOutlined /></p>
                        <p className="ant-upload-text">点击或拖入文件到此处</p>
                    </Upload.Dragger>

                    <Space>
                        <Button
                            type="primary"
                            disabled={fileList.length === 0}
                            loading={uploading}
                            onClick={handleUpload}
                            ref={tourUploadRef}
                        >{uploading ? '上传中' : '立即上传'}</Button>
                        <UploadWrongLocalHeaderError />
                    </Space>

                    {data?.structureCorrect === false &&
                        <Alert
                            type="error"
                            showIcon
                            message={data?.errorMessage?.join('')}
                        />
                    }
                </Space>
            </ProCard>

            <ProCard
                style={{ marginTop: token.margin }}
                title={<CardStepTitle>第三步：确认数据</CardStepTitle>}
                subTitle="根据表格验证提示修改数据无误后提交导入"
            >
                <div ref={tourTeacherCountRef}>
                    <Typography.Title level={5}>1.人数统计</Typography.Title>
                    <Typography.Paragraph>
                        总数量：<Typography.Text style={{ marginRight: token.marginLG }}>{data?.totalRowCount ?? 0}</Typography.Text>
                        验证通过：<Typography.Text type="success" style={{ marginRight: token.marginLG }}>{data?.successRowCount ?? 0}</Typography.Text>
                        验证失败：<Typography.Text type="danger" style={{ marginRight: token.marginLG }}>{data?.errorRowCount ?? 0}</Typography.Text>
                    </Typography.Paragraph>
                </div>
                <div ref={tourStuDetailRef}>
                    <ProTable<API.UploadExamTeacherOutput>
                        actionRef={actionRef}
                        cardProps={false}
                        columns={columns}
                        size="small"
                        rowKey="rowNumber"
                        bordered
                        options={false}
                        sticky={{ offsetHeader: 56 }}
                        dataSource={[...data?.rows ?? []]}
                        virtual
                        scroll={{ y: Math.min(document.body.clientHeight - 56 - 24, 800) }}
                        pagination={false}
                        rowClassName={(r) => {
                            if (!r.isSuccess) {
                                return 'yb-row-error';
                            }
                            return '';
                        }}
                        toolbar={{
                            title: <Typography.Title level={5}>2.教师明细</Typography.Title>,
                            actions: [
                                // <Radio.Group
                                //     key="importType"
                                //     options={getDictOptions('data_import_mode')}
                                //     value={dataImportMode}
                                //     onChange={e => setDataImportMode(e.target.value)}
                                // />,
                                <Typography.Text key="tooltip" type="warning">重要提示：导入前会删除已填报教师信息！</Typography.Text>,
                                <Button
                                    key="import"
                                    type="primary"
                                    disabled={!data?.structureCorrect}
                                    onClick={handleImport}
                                    ref={tourSubmitRef}
                                >确认导入</Button>
                            ],
                        }}
                        search={false}
                    />
                </div>
            </ProCard>

            <Tour
                steps={[
                    {
                        title: '下载模板',
                        description: '下载批量导入监测教师模板文件，请按模板填写说明及注意事项填写文件。',
                        target: () => tourDownloadRef.current,
                    },
                    {
                        title: '选择文件',
                        description: '拖动文件至此区域，或点击该区域选择文件上传。',
                        target: () => tourChooseFileRef.current,
                    },
                    {
                        title: '上传文件',
                        description: '选择好批量导入文件后，点击此按钮上传文件，后台解析后返回校验结果和数据。',
                        target: () => tourUploadRef.current,
                    },
                    {
                        title: '人数统计',
                        description: '上传文件后会显示人数、验证通过和失败的数量。',
                        target: () => tourTeacherCountRef.current,
                    },
                    {
                        title: '教师明细',
                        description: '所有上传的教师明细，请根据校验结果修改数据。',
                        target: () => tourStuDetailRef.current,
                    },
                    {
                        title: '确认导入',
                        description: '检查修改确认批量导入教师信息无误后确认导入。',
                        target: () => tourSubmitRef.current,
                    },
                ]}
                open={tourOpen}
                onClose={() => setTourOpen(false)}
            />

            {editOpen && currentRef.current &&
                <ExamTeacherImportEditModal
                    data={currentRef.current}
                    onFinish={handleEdit}
                    onClose={() => setEditOpen(false)}
                />
            }

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

export default OrgExamTeacherImport;
