/** @format */

import * as React from 'react';
import Axios from '../utils/xhr';
import {
    GET_ACCOUNT_LIST,
    DELETE_admin,
    PUT_ADMIN,
    GET_GROUP_LIST,
    GET_NODE_LIST,
    POST_Logging_LIST,
    PUT_Logging_LIST,
    DELETE_GROUP,
    POST_ADD_GROUP,
    PUT_ADD_GROUP,
    GET_ACCOUNT_INFO,
} from '../const/path';
import {SelectOptionProp} from '../components/select/select';
import {ValuesProps} from '../pages/users/list/components/adminSet'
import {message} from 'antd';

interface IaccountList {
    page_number?: number;
    page_size?: number;
    search?: string;
}
export interface IaccountItem {
    admin_email: string;
    admin_name: string;
    admin_phone: string;
    created_at: string;
    group_name: string;
    id: number;
    status: number;
}
// export const IaccountItem extends ReciveAccountItemProps {
//     index:number
// }
interface AccountState {
    loading: boolean;
    dataSource: IaccountItem[];
    error: null | string;
    total: number;
    deepData: IaccountList;
}
interface AdminStartProp {
    admin_id: number;
    status: number;
}
/**
 * 账号列表
 */
export const useAccountList = (params: IaccountList) => {
    const [state, setState] = React.useState<AccountState>({
        loading: false,
        dataSource: [],
        error: null,
        total: 0,
        deepData: {
            page_number: 1,
            page_size: 10,
            search: '',
        },
    });
    const requestData = (params: IaccountList) => {
        const combineParams = {...state.deepData, ...params};
        setState(prevState => ({...prevState, loading: true, deepData: combineParams}));
        Axios({
            url: GET_ACCOUNT_LIST,
            params: combineParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    const baseIndex = (data.page_number - 1) * data.page_size;
                    if (!data.admins) {
                        data.admins = [];
                    }
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                        total: data.total,
                        dataSource: data.admins.map((item: IaccountItem, idx: number) => {
                            return {
                                ...item,
                                index: baseIndex + idx + 1,
                            };
                        }),
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    // 跳入访问出错页面
                }
            })
            .catch(error => {
                setState(prevState => ({...prevState, loading: false, error: error}));
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};

/**
 * 账号删除： 需返回一个promise
 */
export const useAdminDelete = () => {
    const [state, setState] = React.useState({
        error: null,
        loading: false,
    });
    const requestData = (id: number) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: DELETE_admin,
            method: 'DELETE',
            params: {admin_id: id},
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(prevState => ({...prevState, loading: false}));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(prevState => ({...prevState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 账号启用： 需返回一个promise
 */
export const useAdminStart = (param: {checked: boolean}) => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
        ...param,
    });
    const requestData = (param: AdminStartProp) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            method: 'PUT',
            url: PUT_ADMIN,
            data: param,
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(prevState => ({...prevState, checked: !prevState.checked, loading: false}));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(prevState => ({...prevState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 组列表：
 */
interface GroupListProps {
    loading: boolean;
    error: string | null;
    dataSource: SelectOptionProp[];
    names: string[];
}
export interface GroupItemProps {
    id: number;
    name: string;
    node: string[];
}
export const useGroupList = () => {
    const [state, setState] = React.useState<GroupListProps>({
        loading: false,
        error: null,
        dataSource: [],
        names: [],
    });
    const requestData = () => {
        setState(prevState => ({...prevState, loading: true}));
        Axios({
            url: GET_GROUP_LIST,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    if(!data.list) {
                        data.list = []
                    }
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                        names: data.list.map((ele: GroupItemProps, index: number) => {
                            return ele.name;
                        }),
                        dataSource:  data.list.map((ele: GroupItemProps, index: number) => {
                            return {
                                key: ele.id,
                                value: ele.id,
                                label: ele.name,
                                node: ele.node,
                                index: index + 1,
                            };
                        }),
                    }));
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    React.useEffect(() => {
        requestData();
    }, []);
    return [state, requestData] as const;
};

/**
 * 获取所有node列表：
 */
interface NodeItemProps {
    id: number;
    name: string;
    pid: number;
}
export interface GroupEleProps {
    key: number;
    id: number;
    name: string;
}
export const useNodeList = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
        dataSource: [],
        nodes: [],
    });
    const requestData = () => {
        setState(prevState => ({...prevState, loading: true}));
        Axios({
            url: GET_NODE_LIST,
        })
            .then(({list, code, msg}) => {
                if (code === 0) {
                    const groupList: any[] = [];
                    if (!list.list) {
                        list.list = []
                    }
                   list.list.forEach((item: NodeItemProps) => {
                        if (item.pid === 0) {
                            groupList.push({
                                ...item,
                                children: [],
                            });
                        }
                    });
                     list.list.forEach((ele: GroupEleProps) => {
                        groupList.forEach(item => {
                            if (item.id === ele.pid) {
                                item.children.push(ele);
                            }
                        });
                    });
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                        nodes: list.list.map(ele => {
                            return ele.id;
                        }) ,
                        dataSource: groupList?.map((item: any) => {
                            if (!item.children.length) {
                                return {
                                    ...item,
                                    children: [{...item, pid: item.id}],
                                };
                            }
                            return item;
                        }),
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    React.useEffect(() => {
        requestData();
    }, []);
    return [state] as const;
};

/**
 * 账户信息——新增保存
 */
export interface AccountSaveProps {
    admin_email: string;
    admin_name: string;
    admin_passwd: string;
    admin_phone: string;
    group_id: number;
    node_id: string;
}
export const useAccountSave = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: AccountSaveProps) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: POST_Logging_LIST,
            method: 'POST',
            data: params,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    message.success('保存成功');
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    message.error(msg);
                    return msg;
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 账户信息——编辑展示
 */
interface EditDataProps {
    loading: boolean,
    error: null,
    dataSource: {} | ValuesProps,
}
export const useEditDatas = (params: number) => {
    const [state, setState] = React.useState<EditDataProps>({
        loading: false,
        error: null,
        dataSource: {},
    });
    const requestData = (params: number) => {
        setState(prevState => ({...prevState, loading: true}));
        Axios({
            url: GET_ACCOUNT_INFO,
            method: 'GET',
            params: {admin_id: params},
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                        dataSource: data,
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};
/**
 * 账户信息——编辑保存
 */
export const useAccountEdit = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: AccountSaveProps) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: PUT_Logging_LIST,
            method: 'PUT',
            data: params,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 分组删除： 需返回一个promise
 */
export const useGroupDelete = () => {
    const [state, setState] = React.useState({
        error: null,
        loading: false,
    });
    const requestData = (id: number) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: DELETE_GROUP,
            method: 'DELETE',
            params: {id: id},
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState(prevState => ({...prevState, loading: false}));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(error => {
                setState(prevState => ({...prevState, loading: false, error: error.message}));
                return error.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 添加分组
 */
interface GroupAddProps {
    name: string;
    node_id: string;
}
export const useGroupAdd = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: GroupAddProps) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: POST_ADD_GROUP,
            method: 'POST',
            data: params,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    message.success('添加成功');
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 分组——修改
 */
interface GroupEditProps {
    id: number;
    name: string;
    node_id: string;
}
export const useGroupEdit = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: GroupEditProps) => {
        setState(prevState => ({...prevState, loading: true}));
        return Axios({
            url: PUT_ADD_GROUP,
            method: 'PUT',
            data: params,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                    }));
                    message.success('更新成功');
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    return msg;
                }
            })
            .catch(err => {
                setState(prevState => ({...prevState, loading: false, error: err.message}));
                return err.message;
            });
    };
    return [state, requestData] as const;
};
