import { toValueEnum } from "@/common/converter";
import { CardStepTitle, StatusIcon, UploadWrongLocalHeaderError } from "@/components";
import ExamGradeController from "@/services/apis/ExamGradeController";
import ExamPlanController from "@/services/apis/ExamPlanController";
import ExamTeacherCourseController from "@/services/apis/ExamTeacherCourseController";
import SysOrgController from "@/services/apis/SysOrgController";
import { CertificateType, DataImportMode } from "@/services/enums";
import { BulbOutlined, InboxOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProCard, ProColumns, ProForm, ProFormInstance, ProFormSelect, ProTable } from "@ant-design/pro-components";
import { useModel, useParams } from "@umijs/max";
import { useRequest } from "ahooks";
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 ExamTeacherCourseImportEditModal from "./components/ExamTeacherCourseImportEditModal";

type ImportFormData = {
    sysOrgBranchId?: number;
};


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

    const formRef = useRef<ProFormInstance<ImportFormData>>();
    const actionRef = useRef<ActionType>();

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

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

    const { getDictValueEnum, getKeyDict } = useModel('useDict');
    const educationStages = getKeyDict('education_stage');
    const { initialState } = useModel('@@initialState');
    const { currentUser } = initialState ?? {};

    const { baseData } = useModel('useBaseData');

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

    const { data: examBranchPlan, loading } = useRequest(async () => {
        const res1 = await ExamGradeController.getListByExamPlanId({ examplanid: reqParams.examPlanId });
        const res2 = await SysOrgController.getOrgBranchByOrgId({ orgid: currentUser?.sysOrgId ?? 0 });
        const res3 = await ExamPlanController.getById({ id: reqParams.examPlanId });
        return {
            examGrades: res1 ?? [],
            branches: res2 ?? [],
            plan: res3,
            hasDistrict: (res2?.length ?? 0) > 0,
        };
    });

    const tourDistrictRef = useRef(null);
    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.UploadExamTeacherCourseOutput[]) => {
        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 ExamTeacherCourseController.upload(formData);
            setData(res);
        }
        catch { }
        finally {
            setUploading(false);
        }
    }

    // 保存编辑
    const handleEdit = (v: API.UploadExamTeacherCourseOutput) => {
        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;
        // }
        try {
            const importFormValues = await formRef.current?.validateFields();
            if (examBranchPlan?.hasDistrict && !importFormValues) {
                return;
            }

            const items = [...(data?.rows ?? [])];
            if (items.some(t => t.isSuccess === false)) {
                message.error('还有校验未通过的数据不能导入');
                return;
            }
            await ExamTeacherCourseController.importAction({
                examPlanId: reqParams.examPlanId,
                ...(importFormValues || {}),
                items: items.map(t => ({
                    examPlanId: reqParams.examPlanId,
                    certificateType: t.certificateType ? JSON.parse(`${t.certificateType}`) : CertificateType.NONE,
                    idNumber: t.idNumber?.toUpperCase(),
                    name: t.name,
                    classNumber: t.classNumber ?? 0,
                    courseId: t.courseId ?? 0,
                    gradeId: t.gradeId ?? 0,
                    examGradeId: t.examGradeId ?? 0,
                    remark: t.remark,
                })),
                dataImportMode: DataImportMode.CLEAR_APPEND,
            });
            message.success('导入成功');
            handleBack();
        }
        catch {
            message.error('校区未选择');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    const columns: ProColumns<API.UploadExamTeacherCourseOutput>[] = [
        {
            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: 'gradeId',
            width: 64,
            align: 'center',
            valueEnum: toValueEnum(baseData?.grades ?? [])
        },
        {
            title: '班级',
            dataIndex: 'classNumber',
            width: 48,
            align: 'center',
        },
        {
            title: '科目',
            dataIndex: 'courseName',
            width: 144,
            align: 'center',
        },
        {
            title: '教师姓名',
            dataIndex: 'name',
            align: 'center',
            width: 120,
        },
        {
            title: '证件类型',
            dataIndex: 'certificateType',
            valueEnum: getDictValueEnum('certificate_type'),
            width: 120,
            align: 'center',
        },
        {
            title: '证件号码',
            dataIndex: 'idNumber',
            width: 160,
            align: 'center',
        },
        {
            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>
                    </>
                );
            },
        },
    ];

    let educationStage: API.SysDictDataOutput | undefined;
    if (examBranchPlan?.plan) {
        educationStage = educationStages[examBranchPlan.plan.educationStage];
    }

    return (
        <PageContainer
            title="监测教师任教科目批量导入"
            onBack={handleBack}
            loading={loading}
            extra={
                <Button
                    type="link"
                    icon={<BulbOutlined />}
                    onClick={() => {
                        window.scrollTo({ top: 0 });
                        setTourOpen(true);
                    }}
                >查看操作指引</Button>
            }
        >
            {examBranchPlan?.hasDistrict &&
                <ProCard
                    title={<CardStepTitle>第一步：选择校区</CardStepTitle>}
                    ref={tourDistrictRef}
                >
                    <Alert type="warning" showIcon message="每个校区教师任教科目填写在一个批量导入文件中，每个校区分开导入，有几个校区导入几次！" closable style={{ marginBottom: token.margin, color: token.colorError }} />
                    <ProForm<ImportFormData>
                        layout="inline"
                        submitter={false}
                        formRef={formRef}
                        scrollToFirstError={true}
                    >
                        {examBranchPlan?.branches && examBranchPlan.branches.length > 0 &&
                            <ProFormSelect
                                label="校区"
                                name="sysOrgBranchId"
                                options={examBranchPlan.branches.map(t => ({ label: t.name, value: t.id }))}
                                style={{ width: 240 }}
                                required
                                rules={[{ required: true, message: '校区必须选择' }]}
                            />
                        }
                    </ProForm>
                </ProCard>
            }

            <ProCard
                title={<CardStepTitle>第{examBranchPlan?.hasDistrict ? '二' : '一'}步：下载模板</CardStepTitle>}
                extra={educationStage &&
                    <Button
                        type="primary"
                        ref={tourDownloadRef}
                        onClick={() => {
                            window.open(`/doc-templates/教师任教科目（${educationStage?.name}）上报-填报模板.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>）：
                    学前：1~3，小学：1~6，初中：7~9，高中：1~3。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>B. 班级号</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    填写班级数字序号，
                    <Typography.Text mark>有多个校区的请先上报学生信息。</Typography.Text>
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>C. 科目</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    任教科目，语文、数学等。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>D. 教师姓名</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    教师真实姓名。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>E. 证件类型</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    有居民身份证时，必须选择居民身份证，特殊情况可选择其他证件类型。
                </Typography.Paragraph>
                <Typography.Paragraph>
                    <Typography.Text strong>F. 证件号码</Typography.Text>
                    （<Typography.Text type="danger">必填</Typography.Text>）：
                    有证件类型时必须填写，居民身份证为18位系统会进行严格的验证。
                </Typography.Paragraph>

                <Typography.Text type="danger">特别提醒：在填报电子表格文件时，一定要注意拖动复制单元格时年级号和班级号自动增长的情况。</Typography.Text>
            </ProCard>

            <ProCard
                title={<CardStepTitle>第{examBranchPlan?.hasDistrict ? '三' : '二'}步：上传文件</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>第{examBranchPlan?.hasDistrict ? '四' : '三'}步：确认数据</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.UploadExamTeacherCourseOutput>
                        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 &&
                <ExamTeacherCourseImportEditModal
                    examGrades={examBranchPlan?.examGrades ?? []}
                    data={currentRef.current}
                    onFinish={handleEdit}
                    onClose={() => setEditOpen(false)}
                />
            }

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

export default OrgExamTeacherCourseImport;
