import {getUserList} from './api/auth';
import {ContractAssist} from './api/contract';
import {SpotAssist} from './api/spot';
import {getSymbolList} from './api';

// 用户列表key
export const localUserKey = 'trade_user';
// 合约辅助列表key
export const localContractHelpKey = 'contract_help';
// 现货辅助列表key
export const localSpotHelpKey = 'spot_help';
// 交易对的key
export const localSymbolKey = 'symbol_list';

// 合约交易记录key
export const localContractRecordKey = 'contract_record';
// 现货交易记录key
export const localSpotRecordKey = 'spot_record';

// 数据存本地
export const setLocal = (key: string, data: any, type: 'local' | 'session') => {
    if (type === 'local') {
        window.localStorage.setItem(key, JSON.stringify(data));
    } else {
        window.sessionStorage.setItem(key, JSON.stringify(data));
    }
}

// 取本地数据
export const getLocal = (key: string, type: 'local' | 'session') => {
    let data = null;
    if (type === 'local') {
        let localData = window.localStorage.getItem(key);
        if (localData) {
            data = JSON.parse(localData);
        }
    } else {
        let localData = window.sessionStorage.getItem(key);
        if (localData) {
            data = JSON.parse(localData);
        }
    }
    return data;
}

// 本地缓存是否到期
export const isLocalUserExpire = (key: string, expired: number) => {
    let users = window.localStorage.getItem(key);
    if (users) {
        users = JSON.parse(users);
        const time = users.time;
        const now = new Date().valueOf();
        if (now - time > expired) {
            return true;
        }
    } else {
        return true;
    }
    return false;
}

// 数据存本地--带缓存时间的
export const setLocalData = (key: string, users: any[]) => {
    let params = {
        time: new Date().valueOf(),
        list: users
    }
    window.localStorage.setItem(key, JSON.stringify(params));
}

// 取本地的用户名
export const getUserName = (id: number | string) => {
    let users = window.localStorage.getItem(localUserKey);
    if (users) {
        users = JSON.parse(users);
        const list = users.list;
        let obj = list.find((item: any) => item.id == id);
        if (obj) {
            return obj.name;
        }
    }
    return 'Null';
}

// 取本地的用户列表
export const getLocalUserList = (change: boolean = true, add: boolean = true) => {
    let users = window.localStorage.getItem(localUserKey);
    if (users) {
        users = JSON.parse(users);
        const list = users.list;
        if (list && list.length) {
            // 是否转换数据，用作select
            if (change) {
                let newList: any[] = list.map((item: any) => {
                    return {
                        label: item.name,
                        value: item.id,
                    }
                });
                if (add) {
                    // 头部添加
                    newList.unshift({
                        label: '全部',
                        value: '',
                    })
                }
                return newList
            }
            return list;
        }
    }
    return [];
}

// 获取接口数据并存本地
export const getAdminUserList = async () => {
    // 清空
    // window.localStorage.setItem(localUserKey, '')
    if (isLocalUserExpire(localUserKey, 60 * 60 * 1000)) {
        try {
            const res: any = await getUserList();
            if (res.code == 0) {
                // 存本地
                setLocalData(localUserKey, res.data.data);
            }
        } catch (e) {
            console.log(e)
        }
    }

}

// 请求合约辅助列表
export const getContractHelpList = async (skip: boolean = false) => {
    // 清空
    window.localStorage.setItem(localContractHelpKey, '')
    if (isLocalUserExpire(localContractHelpKey, 24 * 60 * 60 * 1000) || skip) {
        try {
            const res: any = await ContractAssist();
            // console.log(res.data)
            if (res.code == 0) {
                // 存本地
                setLocalData(localContractHelpKey, res.data);
                return res.data;
            }
        } catch (e) {
            console.log(e)
        }
    } else {
        // 打印本地数据
        // const data = window.localStorage.getItem(localContractHelpKey);
        // console.log(JSON.parse(data));
    }
    return null;
}

// 合约辅助指定字段的列表
export const getLocalContractHelperList = (key: string) => {
    let users = window.localStorage.getItem(localContractHelpKey);
    if (users) {
        users = JSON.parse(users);
        const data = users.list;
        let list = []
        if (key == 'order_type') {
            list = data.order_type;
        } else if (key == 'position_side') {
            list = data.position_side;
        } else if (key == 'side') {
            list = data.side;
        } else if (key == 'exchange') {
            list = data.exchange;
        }
        return list;
    }
    return [];
}

// 获取合约辅助列表中字段
export const getLocalContractHelper = (key: string, value: string) => {
    const list = getLocalContractHelperList(key);
    if (list.length) {
        const obj = list.find((item: any) => item.value == value);
        if (obj) {
            return obj.label;
        } else {
            return 'error';
        }
    }
}

// 获取合约辅助列表select列表
export const getLocalContractHelperSelect = (key: string, add: boolean = true) => {
    const list = getLocalContractHelperList(key);
    if (list.length) {
        let newList: any[] = list.map((item: any) => {
            return {
                label: item.label,
                value: item.value,
            }
        })
        if (add) {
            // 头部添加
            newList.unshift({
                label: '全部',
                value: ''
            })
        }
        return newList;
    }
    return [];
}

// 现货辅助列表-存本地
export const setLocalSpotHelper = async (data: any, skip: boolean = false) => {
    // 清空
    window.localStorage.setItem(localSpotHelpKey, '')
    if (isLocalUserExpire(localSpotHelpKey, 24 * 60 * 60 * 1000) || skip) {
        try {
            const res: any = await SpotAssist();
            // console.log(res.data);
            if (res.code == 0) {
                // 存本地
                setLocalData(localSpotHelpKey, res.data);
                return res.data;
            }
        } catch (e) {
            console.log(e)
        }
    } else {
        // 打印本地数据
        // const data = window.localStorage.getItem(localSpotHelpKey);
        // console.log(JSON.parse(data));
    }
    return null;
}

// 现货辅助列表-指定字段
export const getLocalSpotHelperList = (key: string) => {
    let users = window.localStorage.getItem(localSpotHelpKey);
    if (users) {
        users = JSON.parse(users);
        const data = users.list;
        let list = []
        if (key == 'direction') {
            list = data.direction;
        } else if (key == 'order_type') {
            list = data.order_type;
        } else if (key == 'status') {
            list = data.status;
        }
        return list;
    }
    return [];
}

// 获取现货辅助列表中字段
export const getLocalSpotHelper = (key: string, value: string) => {
    const list = getLocalSpotHelperList(key);
    if (list.length) {
        const obj = list.find((item: any) => item.value == value);
        if (obj) {
            return obj.label;
        }
        return value;
    }
    return value;
}

// 获取现货辅助select列表
export const getLocalSpotHelperSelect = (key: string, add: boolean = true) => {
    const list = getLocalSpotHelperList(key);
    if (list.length) {
        let newList: any[] = list.map((item: any) => {
            return {
                label: item.label,
                value: item.value,
            }
        })
        if (add) {
            // 头部添加
            newList.unshift({
                label: '全部',
                value: ''
            })
        }
        return newList;
    }
    return [];
}

// 获取交易对列表--5分钟更新一次
export const getLocalSymbolList = async (priorityLocal: boolean = true) => {
    // 优先获取本地的交易对
    if (priorityLocal) {
        let localData = window.localStorage.getItem(localSymbolKey);
        // 存在数据且没有到期
        if (localData && !isLocalUserExpire(localSymbolKey, 5 * 60 * 1000)) {
            const data = JSON.parse(localData);
            return data.list;
        }
    }
    // 请求接口
    try {
        const res: any = await getSymbolList();
        if (res.code == 0) {
            // 存本地
            setLocalData(localSymbolKey, res.data);
            return res.data;
        }
        return [];
    } catch (e) {
        console.log(e)
        return [];
    }
}
