import { TrueOrFalseValueEnum } from "@/common/valueEnum";
import { CardStepTitle, TagStatus } from "@/components";
import ExamGradeController from "@/services/apis/ExamGradeController";
import { EducationStage, ExamStatus } from "@/services/enums";
import { PlusOutlined, RightCircleOutlined } from "@ant-design/icons";
import { ActionType, ProTable } from "@ant-design/pro-components";
import { history } from "@umijs/max";
import { App, Button, Space, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import ExamGradeAddModal from "./ExamGradeAddModal";
import ExamGradeSettingModal from "./ExamGradeSettingModal";

/** 监测年级管理 */
const ExamGradeList: React.FC<{
    /** 监测计划ID */
    examPlanId: number;
    /** 监测状态 */
    examPlanStatus?: ExamStatus;
    /** 学段 */
    educationStage: EducationStage;
    /** 学期ID */
    semesterId: number;
}> = ({ examPlanId, examPlanStatus, educationStage, semesterId }) => {
    const { token } = theme.useToken();

    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [gradeAddShow, setGradeAddShow] = useState(false);
    const [gradeSettingShow, setGradeSettingShow] = useState(false);

    const actionRef = useRef<ActionType>();
    const currentRef = useRef<API.ExamGradeOutput>();

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

    // 移出
    const handleRemove = useCallback(async (idList: number[]) => {
        modal.confirm({
            title: '警告',
            content: '确定立即移出吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamGradeController.remove({ idList });
                message.success('已移出');
                actionRef.current?.reload();
                setSelectedRowKeys([]);
            },
        });
    }, []);

    return (
        <>
            <ProTable<API.ExamGradeOutput>
                headerTitle={<CardStepTitle>监测年级</CardStepTitle>}
                style={{ marginTop: token.margin }}
                search={false}
                size="small"
                bordered
                sticky={{ offsetHeader: 56 }}
                actionRef={actionRef}
                options={{ density: false, fullScreen: false, setting: false }}
                pagination={false}
                scroll={{ x: 'max-content' }}
                columns={[
                    {
                        title: '序',
                        valueType: 'option',
                        width: 32,
                        align: 'center',
                        render: (_, r, index) => {
                            return index + 1;
                        },
                    },
                    {
                        title: '年级简称',
                        dataIndex: ['grade', 'name'],
                        width: 96,
                        align: 'center',
                    },
                    {
                        title: '年级全称',
                        dataIndex: ['grade', 'fullName'],
                    },
                    {
                        title: '级',
                        dataIndex: 'gradeBeginName',
                        width: 96,
                        align: 'center',
                    },
                    {
                        title: '届',
                        dataIndex: 'gradeEndName',
                        width: 96,
                        align: 'center',
                    },
                    {
                        title: '需要自编监测号',
                        dataIndex: 'isRequiredSelfExamNumber',
                        width: 120,
                        align: 'center',
                        render: (v, r) => {
                            const s = TrueOrFalseValueEnum[`${r.isRequiredSelfExamNumber}`];
                            return (<TagStatus status={s.status}>{s.text}</TagStatus>);
                        },
                    },
                    {
                        title: '自编监测号长度',
                        dataIndex: 'selfExamNumberLength',
                        width: 120,
                        align: 'center',
                    },
                    {
                        title: '需要抽样监测',
                        dataIndex: 'isRequiredSample',
                        width: 112,
                        align: 'center',
                        render: (v, r) => {
                            const s = TrueOrFalseValueEnum[`${r.isRequiredSample}`];
                            return (<TagStatus status={s.status}>{s.text}</TagStatus>);
                        },
                    },
                    {
                        title: '监测科目',
                        dataIndex: 'examCoruses',
                        className: 'minw-80',
                        render: (_, r) => {
                            return r.examCourses?.map(t => t.course?.name).join('、');
                        },
                    },
                    {
                        title: '备注',
                        dataIndex: 'remark',
                        className: 'minw-80',
                    },
                    {
                        title: '操作',
                        valueType: 'option',
                        width: 120,
                        align: 'center',
                        fixed: 'right',
                        render: (_, r) => (
                            <Space>
                                <Button
                                    type="link"
                                    size="small"
                                    // disabled={examPlanStatus !== ExamStatus.READY}
                                    onClick={() => { currentRef.current = r; setGradeSettingShow(true); }}
                                >配置</Button>
                                <Button
                                    type="link"
                                    size="small"
                                    disabled={examPlanStatus !== ExamStatus.READY}
                                    onClick={() => handleRemove([r.id])}
                                >移出</Button>
                            </Space>
                        ),
                    }
                ]}
                rowKey="id"
                toolbar={{
                    actions: [
                        <Button
                            key="course"
                            icon={<RightCircleOutlined />}
                            onClick={() => history.push(`/exam-c/plan/course/${examPlanId}`)}
                        >监测科目及成绩上报模板管理</Button>,
                        <Button
                            key="add"
                            type="primary"
                            icon={<PlusOutlined />}
                            disabled={examPlanStatus !== ExamStatus.READY}
                            onClick={() => setGradeAddShow(true)}
                        >添加年级</Button>,
                    ],
                }}
                request={async () => {
                    const res = await ExamGradeController.getListByExamPlanId({ examplanid: examPlanId });
                    return {
                        data: res,
                        success: true,
                    };
                }}
                rowSelection={examPlanStatus === ExamStatus.READY ? {
                    selectedRowKeys,
                    onSelect: (record, selected, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                    onSelectAll: (_, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                } : false}
                tableAlertRender={({ selectedRowKeys, onCleanSelected }) => {
                    return (
                        <Space size="large">
                            <span>已选 {selectedRowKeys.length} 项</span>
                            <a onClick={() => {
                                setSelectedRowKeys([]);
                                onCleanSelected();
                            }}>取消选择</a>
                        </Space>
                    );
                }}
                tableAlertOptionRender={({ selectedRows }) => {
                    return (<a onClick={async () => handleRemove(selectedRows.map(t => t.id))}>批量移出</a>);
                }}
            />
            {gradeAddShow &&
                <ExamGradeAddModal
                    examPlanId={examPlanId}
                    semesterId={semesterId}
                    educationStage={educationStage}
                    onSelect={() => { }}
                    onClose={() => {
                        setGradeAddShow(false);
                        actionRef.current?.reload();
                    }}
                />
            }
            {gradeSettingShow && currentRef.current &&
                <ExamGradeSettingModal
                    data={currentRef.current}
                    onOk={() => { actionRef.current?.reload(); }}
                    onClose={() => setGradeSettingShow(false)}
                />
            }
        </>
    );
}

export default ExamGradeList;
