import { CardStepTitle } from "@/components";
import ExamPaperController from "@/services/apis/ExamPaperController";
import ExamPaperQuestionMajorController from "@/services/apis/ExamPaperQuestionMajorController";
import ExamPaperQuestionMinorController from "@/services/apis/ExamPaperQuestionMinorController";
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, Table, Typography, theme } from "antd";
import React, { useCallback, useEffect, useRef, useState } from "react";
import ExamPaperQuestionMajorModal from "./components/ExamPaperQuestionMajorModal";
import ExamPaperQuestionMinorSettingModal from "./components/ExamPaperQuestionMinorSettingModal";

/**
 * 试卷详情
 */
const ExamPaperDetail: React.FC = () => {
    const reqParams = useParams() as unknown as { examPaperId: number };
    const { token } = theme.useToken();

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

    const { message } = App.useApp();

    const [majorOpen, setMajorOpen] = useState(false);
    const [batchSettingOpen, setBatchSettingOpen] = useState(false);

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

    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

    const [data, setData] = useState<API.ExamPaperOutput>();
    const loadData = useCallback(async () => {
        const res = await ExamPaperController.getById({ id: reqParams.examPaperId });
        setData(res);
    }, [reqParams]);

    const [majorList, setMajorList] = useState<API.ExamPaperQuestionMajorOutput[]>();
    const loadMajor = useCallback(async () => {
        const ms = await ExamPaperQuestionMajorController.getListByExamPaperId({ exampaperid: reqParams.examPaperId });
        setMajorList(ms);
    }, []);

    useEffect(() => { loadData(); loadMajor(); }, []);

    // 批量设置
    const handleBatchSetting = () => {
        if (!selectedRowKeys || selectedRowKeys.length === 0) {
            message.error('至少选择一个小题');
            return;
        }
        setBatchSettingOpen(true);
    }

    const columns: ProColumns<API.ExamPaperQuestionMinorOutput>[] = [
        {
            title: '序',
            dataIndex: 'sequence',
            width: 72,
            align: 'center',
            fixed: 'left',
        },
        {
            title: '大题',
            dataIndex: 'examPaperQuestionMajorId',
            width: 144,
            className: 'minw-64',
            valueType: 'select',
            fieldProps: {
                options: majorList?.map(t => ({ label: `${t.number}${t.title !== '' ? '、' : ''}${t.title}`, value: t.id })) ?? []
            },
        },
        {
            title: '列名',
            dataIndex: 'columnName',
            width: 128,
        },
        {
            title: '小题号',
            dataIndex: 'name',
            width: 128,
        },
        {
            title: '分值',
            dataIndex: 'score',
            // width: 64,
            // align: 'center',
            // editable: false,
            tooltip: '分值取值范围为：大于0，且小于等于100',
            valueType: 'digit',
            width: 80 + token.paddingMD,
            fieldProps: {
                style: { width: 80 },
                min: 0,
                max: 100,
                precision: 2,
                step: 0.5,
            },
            formItemProps: {
                required: true,
                rules: [
                    { required: true },
                    () => ({
                        validator: (_, value) => {
                            if (value === undefined || value === null || value === '' || (value > 0 && value <= 100)) {
                                return Promise.resolve();
                            }
                            return Promise.reject('分值取值范围为：大于0，且小于等于100');
                        },
                    }),
                ],
            },
        },
        {
            title: '题型',
            dataIndex: 'questionCatalog',
            valueType: 'select',
            width: 96 + token.paddingMD,
            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,
            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');
            //             },
            //         }),
            //     ],
            // },
        },
        {
            title: '知识模块',
            dataIndex: 'knowledgeModule',
            valueType: 'text',
            className: 'minw-80',
            fieldProps: {
                maxLength: 200,
                showCount: true,
            },
            // formItemProps: {
            //     required: true,
            //     rules: [{ required: true }],
            // },
        },
        {
            title: '知识点',
            dataIndex: 'knowledgePoint',
            valueType: 'text',
            className: 'minw-80',
            fieldProps: {
                maxLength: 200,
                showCount: true,
            },
            // formItemProps: {
            //     required: true,
            //     rules: [{ required: true }],
            // },
        },
        {
            title: '选做',
            dataIndex: 'isChoose',
            valueType: 'switch',
            width: 72,
            align: 'center',
            fieldProps: {
                checkedChildren: '是',
                unCheckedChildren: '否'
            },
        },
        {
            title: '最小项',
            dataIndex: 'isLeaf',
            valueType: 'switch',
            width: 72,
            align: 'center',
            fieldProps: {
                checkedChildren: '是',
                unCheckedChildren: '否'
            },
        },
        {
            title: '操作',
            valueType: 'option',
            width: 88,
            fixed: 'right',
            render: (v, r, _, action) => [
                <a key="edit" onClick={() => action?.startEditable?.(r.id)}>编辑</a>,
            ],
        },
    ];

    return (
        <PageContainer
            title={`${data?.examPlan?.fullName ?? ''} - 双向细目表编制`}
            onBack={() => history.back()}
        >
            <ProCard title={<CardStepTitle>基本信息</CardStepTitle>}>
                <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<API.ExamPaperQuestionMinorOutput>
                toolbar={{
                    title: <CardStepTitle>双向细目表</CardStepTitle>,
                    actions: [
                        <Button key="major" type="primary" onClick={() => setMajorOpen(true)}>大题管理</Button>,
                        <Button key="reload" icon={<ReloadOutlined />} type="text" onClick={loadData} />,
                    ],
                }}
                sticky={{ offsetHeader: 56 }}
                style={{ marginTop: token.margin }}
                scroll={{ x: 'max-content' }}
                value={[...(data?.examPaperQuestionMinors ?? [])]}
                columns={columns}
                bordered
                actionRef={actionRef}
                editableFormRef={editorFormRef}
                rowKey="id"
                editable={{
                    editableKeys,
                    // onValuesChange: (record, recordList) => {
                    //     if (!data) { return; }
                    //     const d = { ...data, examPaperQuestionMinors: recordList };
                    //     setData(d);
                    // },
                    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 rdata = { ...data }
                        const ti = rdata?.examPaperQuestionMinors?.findIndex(t => t.id === key) ?? -1;
                        if (rdata.examPaperQuestionMinors && ti !== -1) {
                            rdata.examPaperQuestionMinors[ti] = record;
                            setData(rdata as API.ExamPaperOutput);
                        }
                    },
                    // onCancel: async () => {
                    //     currentEditRef.current = undefined;
                    // },
                }}
                recordCreatorProps={false}
                summary={(rows) => {
                    const tsc = rows.map(t => t.score).reduce((p, c) => p + c, 0);
                    const type = tsc !== data?.score ? 'danger' : 'success';
                    return (
                        <Table.Summary.Row style={{ fontWeight: 'bold' }}>
                            <Table.Summary.Cell index={0} colSpan={5} align="center">小题分值合计（总分）</Table.Summary.Cell>
                            <Table.Summary.Cell index={5}>
                                <Typography.Text type={type}>{tsc}</Typography.Text>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell index={6} colSpan={8}>
                                <Typography.Text type={type}>与科目总分（{data?.score}）{type === 'danger' ? `不符` : '相符'}</Typography.Text>
                            </Table.Summary.Cell>
                        </Table.Summary.Row>
                    );
                }}
                rowSelection={{
                    selectedRowKeys,
                    onSelect: (record, selected, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                    onSelectAll: (_, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                    alwaysShowAlert: true,
                }}
                tableAlertRender={({ selectedRowKeys, onCleanSelected }) => {
                    return (
                        <Space size="large">
                            <span>已选 {selectedRowKeys.length} 项</span>
                            {selectedRowKeys.length > 0 &&
                                <a onClick={() => {
                                    setSelectedRowKeys([]);
                                    onCleanSelected();
                                }}>取消选择</a>
                            }
                        </Space>
                    );
                }}
                tableAlertOptionRender={() => {
                    return (
                        <Space size="large">
                            <a onClick={() => handleBatchSetting()}>批量设置</a>
                        </Space>
                    );
                }}
            // 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);
            //         },
            //     };
            // }}
            />

            {majorOpen &&
                <ExamPaperQuestionMajorModal
                    examPaperId={reqParams.examPaperId}
                    totalScore={data?.score ?? 0}
                    onClose={() => {
                        setMajorOpen(false);
                        loadMajor();
                    }}
                />
            }
            {batchSettingOpen &&
                <ExamPaperQuestionMinorSettingModal
                    ids={selectedRowKeys}
                    examPaperQuestionMajorList={majorList ?? []}
                    onFinish={() => {
                        loadData();
                        setSelectedRowKeys([]);
                    }}
                    onClose={() => setBatchSettingOpen(false)}
                />
            }
        </PageContainer>
    );
}

export default ExamPaperDetail;

