/** @format */
import * as React from 'react';
import {GET_BRTCH_LIST, DELETE_TASK, MERCHANT_EXPORT_TASK} from '../const/path';
import Axios from '../utils/xhr';
interface baseParasmProps {
    page_number?: number;
    page_size?: number;
    type: 2 | 1;
    is_all?: boolean;
    api_name?: string;
}

export interface ITaskRecordProps {
    task_name: string;
    api_name: string;
    api_router: string;
    created_at: string;
    download_file: string;
    file_name: string;
    id: number;
    status_code: number;
    merchant: string;
}

/**
 * 获取dataApi批量任务列表
 */
export const useBatchList = (params: baseParasmProps) => {
    const [state, setState] = React.useState({
        error: null,
        deepData: {
            page_number: 1,
            type: 1,
            is_all: false,
            page_size: 10,
            api_name: '',
            ...params,
        },
        loading: false,
        dataSource: [],
        total: 0,
    });
    const requestData = (params?: Partial<baseParasmProps>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_BRTCH_LIST,
            params: combineParams,
        }).then(({code, data}) => {
            if (code === 0) {
                if (!data.tasks) {
                    data.tasks = [];
                }
                const basePage = data.page_size * (data.page_number - 1);
                setState(preState => ({
                    ...preState,
                    ...params,
                    loading: false,
                    total: data.total,
                    dataSource: data.tasks.map((element: ITaskRecordProps, index: number) => {
                        return {
                            ...element,
                            index: basePage + index + 1,
                            merchant: element.merchant ? element.merchant.split('(')[0] : '',
                            isUseMerchant: element.merchant.includes('使用内部账号') ? '否' : '是',
                        };
                    }),
                }));
            }
        });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};

interface CreateTasksParams {
    api_name: string;
    provider_api_id: number;
    thirdpart_host: string;
    thirdpart_api_router: string;
    platform_code: string;
}
/**
 * 创建dataApi批量任务
 *
 * */
export const useCreateTasks = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: CreateTasksParams, file: FormData) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: '/provider/try',
            method: 'POST',
            params: params,
            data: file,
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(preState => ({...preState, loading: false, error: null}));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 删除dataApi任务(批量任务)
 *
 */
export const useDeleteTask = () => {
    const [state, setState] = React.useState({
        loading: false,
    });
    const requestData = (task_id: number) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: DELETE_TASK,
            method: 'DELETE',
            params: {
                task_id: task_id,
            },
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    setState(preState => ({...preState, loading: false}));
                } else {
                    return msg;
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};
/**
 * 更新dataApi任务状态（暂停 or 继续）
 */
export const useUpdateTask = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
        deepData: {
            task_id: 0,
            status: 3,
        },
    });
    const requestData = (data: {task_id: number; status: 1 | 3}) => {
        setState(preState => ({...preState, loading: true, error: null, deepData: data}));
        return Axios({url: '/base_api/try_api_task', method: 'PUT', data: data})
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(preState => ({...preState, loading: false}));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};
interface MerchantExportTaskParams {
    api_id_list: number[];
    end_timestamp: number;
    export_name: string;
    merchant_id: number | '';
    start_timestamp: number;
    time_list: string;
}
/**
 * 商户导出任务(控制面板-统计报表-商户查询统计)
 */
export const useMerchantExportTask = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: MerchantExportTaskParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: MERCHANT_EXPORT_TASK,
            data: params,
            method: 'POST',
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(preState => ({...preState, loading: false}));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};
