import { CardStepTitle, FileLink, FileUpload } from "@/components";
import ExamDataReportController from "@/services/apis/ExamDataReportController";
import { ExamStatus, ResourceFileType } from "@/services/enums";
import { ActionType, ProTable } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { App, Button, Space, Typography, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import ExamDataReportEditModal from "./ExamDataReportEditModal";

/** 监测上报类型管理 */
const ExamDataReportList: React.FC<{ examPlanId: number, examPlanStatus?: ExamStatus }> = ({ examPlanId, examPlanStatus }) => {
    const { token } = theme.useToken();

    const actionRef = useRef<ActionType>();
    const dataRef = useRef<API.ExamDataReportOutput[]>();
    const currentRef = useRef<Partial<API.ExamDataReportOutput>>();

    const [editOpen, setEditOpen] = useState(false);

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

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

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

    // 开始
    const handleStart = useCallback(async (id: number) => {
        modal.confirm({
            title: '提示',
            content: '确定立即开始吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamDataReportController.start({ id });
                message.success('已开始');
                actionRef.current?.reload();
            },
        });
    }, []);

    // 结束
    const handleStop = useCallback(async (id: number) => {
        modal.confirm({
            title: '提示',
            content: '确定立即结束吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamDataReportController.stop({ id });
                message.success('已结束');
                actionRef.current?.reload();
            },
        });
    }, []);

    // // 取消
    // const handleCancel = useCallback(async (id: number) => {
    //     modal.confirm({
    //         title: '提示',
    //         content: '确定立即取消吗',
    //         okText: '确定',
    //         cancelText: '取消',
    //         centered: true,
    //         onOk: async () => {
    //             await ExamDataReportController.cancel({ id });
    //             message.success('已取消');
    //             actionRef.current?.reload();
    //         },
    //     });
    // }, []);

    // 删除附件
    const handleDeleteAttachment = useCallback(async (id: number, fileId: string) => {
        modal.confirm({
            title: '警告',
            content: '确定立即删除吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamDataReportController.delAttachment({ sourceId: id, fileId })
                message.success('已删除');
                actionRef.current?.reload();
            },
        });
    }, []);

    return (
        <>
            <ProTable<API.ExamDataReportOutput>
                headerTitle={<CardStepTitle>上报内容</CardStepTitle>}
                style={{ marginTop: token.margin }}
                search={false}
                size="small"
                bordered
                scroll={{ x: '100%' }}
                sticky={{ offsetHeader: 56 }}
                actionRef={actionRef}
                options={{ density: false, fullScreen: false, setting: false }}
                pagination={false}
                columns={[
                    {
                        title: '序',
                        valueType: 'option',
                        fixed: 'left',
                        width: 32,
                        align: 'center',
                        render: (_, r, index) => {
                            return index + 1;
                        },
                    },
                    {
                        title: '上报类型',
                        dataIndex: 'type',
                        valueEnum: getDictValueEnum('data_report_type'),
                        width: 160,
                        fixed: 'left',
                    },
                    {
                        title: '应上报机构',
                        dataIndex: 'count',
                        width: 88,
                        align: 'center',
                    },
                    {
                        title: '已上报机构',
                        dataIndex: 'reportedCount',
                        width: 88,
                        align: 'center',
                        renderText: (v) => <Typography.Text type="success">{v}</Typography.Text>,
                    },
                    {
                        title: '未上报机构',
                        dataIndex: 'unreportCount',
                        width: 88,
                        align: 'center',
                        renderText: (v) => <Typography.Text type="danger">{v}</Typography.Text>,
                    },
                    {
                        title: '上报状态',
                        dataIndex: 'status',
                        valueEnum: getDictValueEnum('exam_status', true),
                        width: 88,
                        align: 'center',
                    },
                    {
                        title: '开始时间',
                        dataIndex: 'beginTime',
                        width: 144,
                        align: 'center',
                    },
                    {
                        title: '结束时间',
                        dataIndex: 'endTime',
                        width: 144,
                        align: 'center',
                    },
                    {
                        title: '上报说明',
                        dataIndex: 'remark',
                        ellipsis: true,
                        width: 400,
                    },
                    {
                        title: '附件',
                        valueType: 'option',
                        hideInSearch: true,
                        width: 280 + token.paddingXS * 2,
                        // className: 'minw-280',
                        // fixed: 'right',
                        render: (_, r) => {

                            const li = r.attachmentList?.map((t, i) => {
                                return (
                                    <FileLink
                                        key={i}
                                        fileExtName={t.fileExtName}
                                        fileName={t.fileName}
                                        url={`${AppConfig.fileViewRoot}?id=${t.fileId}`}
                                        thumbUrl={t.thumbFileId && t.thumbFileId !== '0' ? `${AppConfig.fileViewRoot}?id=${t.thumbFileId}` : undefined}
                                        card
                                        onDelete={async () => handleDeleteAttachment(r.id, t.fileId)}
                                    />
                                );
                            });
                            return (
                                <Space direction="vertical" style={{ width: 280 }}>
                                    {li}
                                    {(li?.length ?? 0) < 9 &&
                                        <FileUpload
                                            addText="添加文件"
                                            // tipText="仅支持PDF或图片文件"
                                            accept="*.png,*.jpg,*.jpeg,*.gif,*.pdf,*.doc,*.docx,*.xls,*.xlsx,*.ppt,*.pptx,*.zip"
                                            limitSize={1024}
                                            onUpload={async (file, onUploadProgress) => {
                                                const fsp = file.name.split('.');
                                                let extName = '';
                                                if (fsp.length > 1) {
                                                    extName = fsp[fsp.length - 1].toLowerCase();
                                                }
                                                if (extName === '' || !['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip'].includes(extName)) {
                                                    message.error('文件类型错误，请重新选择！')
                                                    return { success: false, errorType: 'fileTypeError', errorMessage: '文件类型错误' };
                                                }

                                                try {
                                                    const formData = new FormData();
                                                    formData.append('type', `${ResourceFileType.EXAM_ABSENT_REPLACE}`);
                                                    formData.append('sourceId', `${r.id}`);
                                                    formData.append('fileName', `${file.name}`);
                                                    formData.append('file', file);
                                                    await ExamDataReportController.uploadAttachment(formData, {
                                                        onUploadProgress: (p: any) => {
                                                            const progress = parseFloat((p.loaded / p.total * 100).toFixed(1));
                                                            onUploadProgress?.(progress);
                                                        }
                                                    });
                                                    actionRef.current?.reload();
                                                    return { success: true };
                                                }
                                                catch {
                                                    return { success: false };
                                                }
                                            }}
                                        />
                                    }
                                </Space>
                            );
                        },
                    },
                    {
                        title: '操作',
                        valueType: 'option',
                        width: 196,
                        fixed: 'right',
                        render: (_, r) => {
                            return (
                                <>
                                    <Button
                                        type="link"
                                        size="small"
                                        disabled={!examPlanStatus || [ExamStatus.STOPPED, ExamStatus.CANCELLED].includes(examPlanStatus) || r.status !== ExamStatus.READY}
                                        onClick={() => {
                                            currentRef.current = r;
                                            setEditOpen(true);
                                        }}
                                    >修改</Button>
                                    <Button
                                        type="link"
                                        size="small"
                                        disabled={!examPlanStatus || [ExamStatus.STOPPED, ExamStatus.CANCELLED].includes(examPlanStatus) || r.status !== ExamStatus.READY}
                                        onClick={() => handleRemove(r.id)}
                                    >移出</Button>
                                    <Button
                                        type="link"
                                        size="small"
                                        disabled={examPlanStatus !== ExamStatus.ACTIVE || r.status !== ExamStatus.READY}
                                        onClick={() => handleStart(r.id)}
                                    >开始</Button>
                                    <Button
                                        type="link"
                                        size="small"
                                        disabled={r.status !== ExamStatus.ACTIVE}
                                        onClick={() => handleStop(r.id)}
                                    >结束</Button>
                                    {/* <Button
                                        type="link"
                                        size="small"
                                        disabled={r.status !== ExamStatus.ACTIVE}
                                        onClick={() => handleCancel(r.id)}
                                    >取消</Button> */}
                                </>
                            );
                        },
                    }
                ]}
                rowKey="id"
                toolbar={{
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            // disabled={examPlanStatus !== ExamStatus.READY}
                            onClick={() => {
                                currentRef.current = { id: 0, examPlanId };
                                setEditOpen(true);
                            }}
                        >添加类型</Button>,
                    ],
                }}
                request={async () => {
                    const res = await ExamDataReportController.getListByExamPlanId({ examplanid: examPlanId });
                    dataRef.current = res ?? [];
                    return {
                        data: res,
                        success: true,
                    };
                }}
            />
            {editOpen && currentRef.current &&
                <ExamDataReportEditModal
                    data={currentRef.current}
                    onClose={() => setEditOpen(false)}
                    onFinish={() => actionRef.current?.reload()}
                />
            }
        </>
    );
}

export default ExamDataReportList;
