import { TrueOrFalseValueEnum } from "@/common/valueEnum";
import { CardStepTitle, StatusIcon, TagStatus } from "@/components";
import ExamOrgController from "@/services/apis/ExamOrgController";
import ExamOrgDataReportController from "@/services/apis/ExamOrgDataReportController";
import { DataReportStatus } from "@/services/enums";
import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { App, Button, Space, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import ExamOrgAddDrawer from "./ExamOrgAddDrawer";

/** 监测机构管理 */
const ExamOrgList: React.FC<{ examPlanId: number, examDataReports: API.ExamDataReportOutput[] }> = ({ examPlanId, examDataReports }) => {
    const { token } = theme.useToken();
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [orgAddShow, setAddChooseShow] = useState(false);

    const searchKeyWordsRef = useRef<string>();
    const orgActionRef = useRef<ActionType>();

    const { getDictValueEnum, getKeyDict } = useModel('useDict');
    const dataReportTypeDict = getKeyDict('data_report_type');
    const dataReportStatusDict = getKeyDict('data_report_status');

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

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

    // 退回上报
    const handleReject = useCallback(async (id: number) => {
        modal.confirm({
            title: '警告',
            content: '确定立即退回吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamOrgDataReportController.reportReject({ id });
                message.success('已退回');
                orgActionRef.current?.reload();
            },
        });
    }, []);

    // 切换是否参与监测
    const handleSwitch = useCallback(async (id: number, isRequiredExam: boolean) => {
        modal.confirm({
            content: `确定立即${isRequiredExam ? '加入' : '取消'}监测吗`,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamOrgController.switchRequiredSample({ id, isRequiredExam });
                message.success('操作成功');
                orgActionRef.current?.reload();
            },
        });
    }, []);

    let columns: ProColumns<API.ExamOrgOutput>[] = [
        {
            title: '机构代码',
            dataIndex: ['sysOrg', 'code'],
            width: 80,
            align: 'center'
        },
        {
            title: '城乡类别',
            dataIndex: ['sysOrg', 'urbanRuralType'],
            valueEnum: getDictValueEnum('urban_rural_type'),
            width: 96,
            align: 'center',
        },
        {
            title: '机构全称',
            dataIndex: ['sysOrg', 'fullName'],
            className: 'minw-160',
        },
        // {
        //     title: '机构名称',
        //     dataIndex: ['sysOrg', 'name'],
        // },
        ...(examDataReports?.sort((a, b) => a.type - b.type)?.map(t => ({
            title: dataReportTypeDict[t.type].name,
            valueType: 'option' as any,
            width: 136,
            render: (v: any, r: API.ExamOrgOutput) => {
                const rt = r.dataReportList?.find(k => k.type === t.type);
                if (rt) {
                    const drs = dataReportStatusDict[rt.status];
                    return (
                        <>
                            <Space size="small">
                                <StatusIcon
                                    filled
                                    status={drs?.antStatus as any ?? 'warning'}
                                />
                                {drs?.name}
                            </Space>
                            {rt.status === DataReportStatus.REPORTED &&
                                <Button type="link" size="small" onClick={() => handleReject(rt.id)}>退回</Button>
                            }
                        </>
                    );
                }
                return (
                    <Space size="small">
                        <StatusIcon status="warning" />
                        {dataReportStatusDict[DataReportStatus.UNREPORT].name}
                    </Space>
                );
            },
        }))),
        {
            title: '参与监测',
            dataIndex: 'isRequiredExam',
            width: 96,
            align: 'center',
            fixed: 'right',
            render: (_, r) => {
                // const s = TrueOrFalseValueEnum[`${r.isRequiredExam}`];
                // return (<TagStatus status={s.status}>{s.text}</TagStatus>);
                const s = TrueOrFalseValueEnum[`${r.isRequiredExam}`];
                return (
                    <Space>
                        <TagStatus status={s.status}>{s.text}</TagStatus>
                        <a onClick={() => handleSwitch(r.id, !r.isRequiredExam)}>{r.isRequiredExam ? '取消' : '加入'}</a>
                    </Space>
                )
            },
        },
        {
            title: '操作',
            valueType: 'option',
            width: 80,
            align: 'center',
            fixed: 'right',
            render: (_, r) => <a onClick={() => handleRemove([r.id])}>移出</a>,
        }
    ];

    return (
        <>
            <ProTable<API.ExamOrgOutput>
                headerTitle={<CardStepTitle>监测机构</CardStepTitle>}
                style={{ marginTop: token.margin }}
                search={false}
                size="small"
                bordered
                sticky={{ offsetHeader: 56 }}
                scroll={{ x: 'max-content' }}
                actionRef={orgActionRef}
                options={{ density: false, fullScreen: false, setting: false }}
                columns={columns}
                rowKey="id"
                pagination={{ pageSize: 10, showSizeChanger: true }}
                toolbar={{
                    search: true,
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            onClick={() => setAddChooseShow(true)}
                        >添加机构</Button>,
                    ],
                    onSearch: (name: string) => {
                        searchKeyWordsRef.current = name;
                        orgActionRef.current?.reset?.();
                    },
                }}
                request={async (params) => {
                    const res = await ExamOrgController.queryPageList({
                        pageIndex: params.current ?? 1,
                        pageSize: params.pageSize ?? 20,
                        examPlanId,
                        orgName: searchKeyWordsRef.current
                    });
                    return {
                        data: res?.items,
                        success: true,
                        total: res?.totalCount,
                    };
                }}
                rowSelection={{
                    selectedRowKeys,
                    onSelect: (record, selected, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                    onSelectAll: (_, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                }}
                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>);
                }}
            />
            {orgAddShow &&
                <ExamOrgAddDrawer
                    examPlanId={examPlanId}
                    onSelect={() => { }}
                    onClose={() => {
                        setAddChooseShow(false);
                        orgActionRef.current?.reload();
                    }}
                />
            }
        </>
    );
}

export default ExamOrgList;
