import { CardStepTitle } from "@/components";
import ExamPaperController from "@/services/apis/ExamPaperController";
import ExamPaperQuestionMinorController from "@/services/apis/ExamPaperQuestionMinorController";
import { AuditStatus } from "@/services/enums";
import { ReloadOutlined } from "@ant-design/icons";
import { ActionType, EditableFormInstance, EditableProTable, PageContainer, ProCard, ProColumns, ProDescriptions } from "@ant-design/pro-components";
import { history, useModel, useParams } from "@umijs/max";
import { App, Button, Space, Tag, Typography, theme } from "antd";
import lodash from 'lodash';
import { useCallback, useEffect, useRef, useState } from "react";

type ExamPaperQuestionMinorItem = API.ExamPaperQuestionMinorOutput & {
    majorCount: number;
    isFirstMinor: boolean;
};

/**
 * 双向细目表详细
 */
const TwclDetail: React.FC = () => {
    const reqParams = useParams() as unknown as { examPaperId: number };
    const { token } = theme.useToken();

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

    const { getDictOptions } = useModel('useDict');

    // const currentEditRef = useRef<React.Key>();
    const actionRef = useRef<ActionType>();
    const editorFormRef = useRef<EditableFormInstance<ExamPaperQuestionMinorItem>>();
    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();

    const [dataSource, setDataSource] = useState<ExamPaperQuestionMinorItem[]>();
    const [data, setData] = useState<API.ExamPaperOutput>();
    const [loading, setLoading] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    // 构建表格数据源
    const buildDataSource = (ms: API.ExamPaperQuestionMinorOutput[]) => {
        // 各大题小题数量
        const majors = lodash.countBy(ms, 'examPaperQuestionMajorId');
        // 各大题下第一个小题
        const minMinors = lodash.mapValues(lodash.groupBy(ms, 'examPaperQuestionMajorId'), g => lodash.minBy(g, 'sequence')?.id);
        let ds = [...ms] as ExamPaperQuestionMinorItem[];
        ds.sort((a, b) => {
            // 按大题和小题顺序排序
            return (a.examPaperQuestionMajor?.sequence || 0 + a.sequence) - (b.examPaperQuestionMajor?.sequence || 0 + b.sequence);
        }).forEach(d => {
            if (d.examPaperQuestionMajorId) {
                d.majorCount = majors[d.examPaperQuestionMajorId]
                if (d.id === minMinors[d.examPaperQuestionMajorId]) {
                    d.isFirstMinor = true;
                }
            }
        });
        setDataSource(ds);
    }

    // 加载数据
    const loadData = useCallback(async () => {
        try {
            setLoading(true);
            const res = await ExamPaperController.getById({ id: reqParams.examPaperId });
            setData(res);
            buildDataSource(res?.examPaperQuestionMinors ?? []);
        }
        catch { }
        finally {
            setLoading(false);
        }
    }, [reqParams]);
    useEffect(() => { loadData(); }, []);

    // 未提交状态
    const unsubmit = [AuditStatus.UNSUBMIT, AuditStatus.REJECTED].includes(data?.twclStatus ?? AuditStatus.UNSUBMIT);

    // 列定义
    const columns: ProColumns<ExamPaperQuestionMinorItem>[] = [
        {
            title: '序',
            width: 40,
            align: 'center',
            render: (_, r, ri) => ri + 1,
            editable: false,
            rowScope: 'rowgroup',
            fixed: 'left',
        },
        {
            title: '大题',
            dataIndex: ['examPaperQuestionMajor', 'title'],
            editable: false,
            // width: 160,
            render: (v, r) => {
                const m = r.examPaperQuestionMajor;
                if (!m) {
                    return '';
                }
                return `${m.number}${m.title !== '' ? '、' : ''}${m.title}（${m.score}分）`;
            },
            onCell: (r) => {
                if (r.isFirstMinor) {
                    if (r.majorCount > 1) {
                        return { rowSpan: r.majorCount };
                    }
                    return {};
                }
                return { rowSpan: 0 };
            },
        },
        {
            title: '小题号',
            dataIndex: 'name',
            editable: false,
            // width: 96,
        },
        {
            title: '分值',
            dataIndex: 'score',
            valueType: 'digit',
            width: 64,
            align: 'center',
            editable: false,
            fieldProps: {
                precision: 2,
            },
        },
        {
            title: '题型',
            dataIndex: 'questionCatalog',
            valueType: 'select',
            width: 96 + token.paddingMD,
            align: 'center',
            fieldProps: {
                options: getDictOptions('question_catalog').filter(t => t.value > 0),
                style: { width: 96 },
            },
            formItemProps: {
                required: true,
                rules: [{ required: true }],
            },
        },
        {
            title: '认知能力',
            dataIndex: 'cognitiveAbility',
            valueType: 'select',
            width: 96 + token.paddingMD,
            align: 'center',
            fieldProps: {
                options: getDictOptions('cognitive_ability').filter(t => t.value > 0),
                style: { width: 96 },
            },
            formItemProps: {
                required: true,
                rules: [{ required: true }],
            },
        },
        {
            title: '预估难度',
            dataIndex: 'estimatedDifficulty',
            tooltip: '预估难度取值范围为：大于0，小于等于1',
            valueType: 'digit',
            width: 80 + token.paddingMD,
            fieldProps: {
                style: { width: 80 },
                min: 0,
                max: 1,
                precision: 2,
                step: 0.1,
            },
            formItemProps: {
                required: true,
                rules: [
                    { required: true },
                    () => ({
                        validator: (_, value) => {
                            if (value === undefined || value === null || value === '' || (value > 0 && value <= 1)) {
                                return Promise.resolve();
                            }
                            return Promise.reject('预估难度取值范围为：大于0，小于等于1');
                        },
                    }),
                ],
            },
            render: (v, r) => {
                if ((r.estimatedDifficulty ?? 0) > 0) {
                    return v;
                }
                return <Typography.Text type="warning">{v}</Typography.Text>;
            },
        },
        {
            title: '知识模块',
            dataIndex: 'knowledgeModule',
            valueType: 'text',
            className: 'minw-160',
            fieldProps: {
                maxLength: 200,
                showCount: true,
            },
            formItemProps: {
                required: true,
                rules: [{ required: true }],
            },
        },
        {
            title: '知识点',
            dataIndex: 'knowledgePoint',
            valueType: 'text',
            className: 'minw-160',
            fieldProps: {
                maxLength: 200,
                showCount: true,
            },
            formItemProps: {
                required: true,
                rules: [{ required: true }],
            },
        },
        {
            title: '选做',
            dataIndex: 'isChoose',
            valueType: 'switch',
            width: 80,
            align: 'center',
            fieldProps: {
                checkedChildren: '是',
                unCheckedChildren: '否'
            },
        },
    ];
    if (unsubmit) {
        columns.push({
            title: '操作',
            valueType: 'option',
            width: 88,
            fixed: 'right',
            render: (v, r, _, action) => [
                <a key="edit" onClick={() => action?.startEditable?.(r.id)}>编辑</a>,
            ],
        });
    }

    // 提交
    const handleSubmit = useCallback(async () => {
        modal.confirm({
            content: '提交后不能再修改，确定立即提交吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                try {
                    setSubmitting(true);
                    await ExamPaperController.submitTwcl({ id: reqParams.examPaperId });
                    message.success('已提交');
                    loadData();
                }
                catch { }
                finally {
                    setSubmitting(false);
                }
            },
        });
    }, []);

    let actions = [<Button key="reload" type="text" icon={<ReloadOutlined />} onClick={loadData} />];
    if (unsubmit) {
        actions = [
            <Typography.Text key="tip" type="warning">所有小题编辑完成后，点击“立即提交”按钮完成该科编制。</Typography.Text>,
            <Button key="submit" type="primary" loading={submitting} onClick={handleSubmit}>立即提交</Button>,
            ...actions
        ];
    }

    return (
        <PageContainer
            title={`${data?.examPlan?.fullName ?? ''} - 双向细目表编制`}
            onBack={() => history.back()}
            loading={loading}
        >
            <ProCard
                title={<CardStepTitle>基本信息</CardStepTitle>}
                extra={
                    <Space>
                        <Tag color={unsubmit ? 'error' : 'success'}>{unsubmit ? '未提交' : '已提交'}</Tag>
                    </Space>
                }
            >
                <ProDescriptions size="small">
                    <ProDescriptions.Item label="年级">
                        {data?.grade?.name}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="科目">
                        {data?.course?.name}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="总分">
                        {data?.score}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="备注">
                        {data?.remark}
                    </ProDescriptions.Item>
                </ProDescriptions>
            </ProCard>

            <EditableProTable<ExamPaperQuestionMinorItem>
                toolbar={{
                    title: (<CardStepTitle>双向细目表</CardStepTitle>),
                    actions,
                }}
                style={{ marginTop: token.margin }}
                scroll={{ x: 'max-content' }}
                value={dataSource}
                columns={columns}
                bordered
                actionRef={actionRef}
                editableFormRef={editorFormRef}
                rowKey="id"
                // controlled
                editable={{
                    editableKeys,
                    // onValuesChange: (record, recordList) => {
                    //     if (!data) { return; }
                    //     const d = { ...data, examPaperQuestionMinors: recordList };
                    //     setData(d);
                    //     buildDataSource(recordList);
                    // },
                    onChange: setEditableRowKeys,
                    actionRender: (r, config, dom) => [dom.save, dom.cancel],
                    onSave: async (key, record) => {
                        const p: API.UpdateExamPaperQuestionMinorInput = {
                            id: record.id,
                            examPaperId: record.examPaperId,
                            examPaperQuestionMajorId: record.examPaperQuestionMajorId ?? 0,
                            questionCatalog: record.questionCatalog ? JSON.parse(`${record.questionCatalog}`) : undefined,
                            cognitiveAbility: record.cognitiveAbility ? JSON.parse(`${record.cognitiveAbility}`) : undefined,
                            sequence: record.sequence,
                            columnName: record.columnName,
                            name: record.name,
                            score: record.score,
                            knowledgeModule: record.knowledgeModule,
                            knowledgePoint: record.knowledgePoint,
                            estimatedDifficulty: record.estimatedDifficulty,
                            isChoose: record.isChoose,
                            isLeaf: record.isLeaf,
                        };
                        await ExamPaperQuestionMinorController.update(p);
                        const rls = data?.examPaperQuestionMinors ?? [];
                        const ti = rls.findIndex(t => t.id === key);
                        if (ti !== -1) {
                            rls[ti] = record;
                            buildDataSource(rls);
                        }
                    },
                    // onCancel: async (key, record) => {
                    //     console.log(key);
                    //     console.log(record);
                    //     console.log(dataSource);
                    //     buildDataSource(data?.examPaperQuestionMinors ?? []);
                    // },
                }}
                recordCreatorProps={false}
            // onRow={(r) => {
            //     return {
            //         onClick: () => {
            //             if (currentEditRef.current === r.id) {
            //                 return;
            //             }
            //             else if (currentEditRef.current) {
            //                 actionRef.current?.cancelEditable?.(currentEditRef.current);
            //             }
            //             currentEditRef.current = r.id;
            //             actionRef.current?.startEditable?.(r.id);
            //         },
            //     };
            // }}
            />
        </PageContainer>
    );
}

export default TwclDetail;

