import { create } from 'zustand';
import { message } from 'antd';
import { apis } from '@/apis';
import { downloadFile } from '@/utils';

interface PageState {
    pageNum: number;
    pageSize: number;
    total: number;
}

interface DataExportState {
    query: any;
    listLoading: boolean;
    list: any[];
    page: PageState;
}

interface DataExportActions {
    setQuery: (query: any) => void;
    setListLoading: (loading: boolean) => void;
    setList: (list: any[]) => void;
    setPage: (page: PageState) => void;
}

export type DataExportStore = DataExportState & DataExportActions & {
    fetchDataExportList: () => Promise<void>;
    onDownload: (record: any) => Promise<void>;
};

const initialState: DataExportState = {
    query: undefined,
    listLoading: false,
    list: [],
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
    },
};

export const useDataExportStore = create<DataExportStore>((set, get) => ({
    ...initialState,
    
    setQuery: (query) => set({ query }),
    
    setListLoading: (loading) => set({ listLoading: loading }),
    
    setList: (list) => set({ list }),
    
    setPage: (page) => set({ page }),
    
    fetchDataExportList: async () => {
        set({ listLoading: true });
        try {
            const { query, page } = get();
            const res: any = await apis.fetchDataExportList({
                ...query,
                pageNum: page.pageNum,
                pageSize: page.pageSize,
            });
            
            if (res.code === 200) {
                set({
                    list: res.rows || [],
                    page: {
                        ...page,
                        total: res.total || 0,
                    },
                });
            }
        } catch (error) {
            console.error('获取数据导出列表失败:', error);
        } finally {
            set({ listLoading: false });
        }
    },
    
    onDownload: async (record: any) => {
        try {
            const blob = await apis.downloadDataExport(record.id);
            downloadFile(blob, `${record.name}.txt`);
            message.success('下载成功');
        } catch (error) {
            message.error('下载失败');
        }
    },
}));

export default useDataExportStore;
