import { makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis } from '@/apis';
import { downloadFile } from '@/utils';
import { State, ReadonlyState, StateAction, DataExportStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    query: undefined,
    listLoading: false,
    list: [],
    page: {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
    },
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setQuery: (query) => {
            state.query = query;
        },
        setListLoading: (loading) => {
            state.listLoading = loading;
        },
        setList: (list) => {
            state.list = list;
        },
        setPage: (page) => {
            state.page = page;
        },
    };
};

// 使用仓库
const useDataExportStore = (): DataExportStore => {
    const state = makeAutoObservable(stateGenerator());
    const actions = stateActionsGenerator(state);

    const api = {
        // 获取聊天记录列表
        fetchChatHistoryList: async () => {
            actions.setListLoading(true);
            try {
                const data = {
                    ...state.query,
                    pageNumber: state.page.pageNumber,
                    pageSize: state.page.pageSize,
                };
                const res = await apis.fetchChatHistoryList(data);
                actions.setList(res.rows);
                actions.setPage({
                    ...state.page,
                    total: res.total,
                });
            } catch (error: any) {
                console.error(error);
            } finally {
                actions.setListLoading(false);
            }
        },
        // 导出聊天记录
        exportChatHistory: async (id: string, fileName: string) => {
            try {
                const blob = await apis.exportChatHistory(id);
                fileName = `${fileName}.xlsx`;
                downloadFile(blob, fileName);
                message.success('导出成功');
            } catch (error: any) {
                message.error(error.msg);
            }
        },
    }

    // 点击查询
    const onClickSearch: DataExportStore['onClickSearch'] = async (query) => {
        const initialPageNumber = stateGenerator().page.pageNumber;

        actions.setQuery(query);
        actions.setPage({
            ...state.page,
            pageNumber: initialPageNumber,
        });
        // 获取聊天记录列表
        await api.fetchChatHistoryList();
    }

    // 点击重置
    const onClickReset: DataExportStore['onClickReset'] = async (query) => {
        const initialPage = stateGenerator().page;

        actions.setQuery(query);
        actions.setPage(initialPage);
        // 获取聊天记录列表
        await api.fetchChatHistoryList();
    }

    // 更改分页
    const onChangePagination: DataExportStore['onChangePagination'] = async (pageNumber, pageSize) => {
        actions.setPage({
            ...state.page,
            pageNumber: pageNumber,
            pageSize: pageSize,
        });
        // 获取聊天记录列表
        await api.fetchChatHistoryList();
    }

    // 点击导出
    const onClickDownload: DataExportStore['onClickDownload'] = async (id, name) => {
        // 导出聊天记录
        await api.exportChatHistory(id, name);
    }

    // 初始渲染
    const init: DataExportStore['init'] = async () => {
        // 获取聊天记录列表
        await api.fetchChatHistoryList();
    }

    // 状态重置
    const reset: DataExportStore['reset'] = () => {
        const initialQuery = stateGenerator().query;
        const initialListLoading = stateGenerator().listLoading;
        const initialList = stateGenerator().list;
        const initialPage = stateGenerator().page;

        actions.setQuery(initialQuery);
        actions.setListLoading(initialListLoading);
        actions.setList(initialList);
        actions.setPage(initialPage);
    }

    return {
        state,
        onClickSearch,
        onClickReset,
        onChangePagination,
        onClickDownload,
        init,
        reset
    };
};

export default useDataExportStore();