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

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

interface AuditState {
    query: any;
    listLoading: boolean;
    list: any[];
    page: PageState;
    infoModalId: string;
    infoModalOpen: boolean;
}

interface AuditActions {
    setQuery: (query: any) => void;
    setListLoading: (loading: boolean) => void;
    setList: (list: any[]) => void;
    setPage: (page: PageState) => void;
    setInfoModalId: (id: string) => void;
    setInfoModalOpen: (open: boolean) => void;
}

export type AuditStore = AuditState & AuditActions & {
    fetchAuditList: () => Promise<void>;
    onAuditPass: (id: string) => Promise<void>;
    onAuditReject: (id: string, reason: string) => Promise<void>;
};

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

export const useAuditStore = create<AuditStore>((set, get) => ({
    ...initialState,
    
    setQuery: (query) => set({ query }),
    
    setListLoading: (loading) => set({ listLoading: loading }),
    
    setList: (list) => set({ list }),
    
    setPage: (page) => set({ page }),
    
    setInfoModalId: (id) => set({ infoModalId: id }),
    
    setInfoModalOpen: (open) => set({ infoModalOpen: open }),
    
    fetchAuditList: async () => {
        set({ listLoading: true });
        try {
            const { query, page } = get();
            const res: any = await apis.fetchAuditList({
                ...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 });
        }
    },
    
    onAuditPass: async (id: string) => {
        try {
            await apis.auditPass(id);
            message.success('审核通过');
            get().fetchAuditList();
        } catch (error) {
            message.error('审核失败');
        }
    },
    
    onAuditReject: async (id: string, reason: string) => {
        try {
            await apis.auditReject(id, reason);
            message.success('已拒绝');
            get().fetchAuditList();
        } catch (error) {
            message.error('操作失败');
        }
    },
}));

export default useAuditStore;
