import {reactive, ref, toRefs, watch} from "vue";
import {getCookieForName, throttle} from "@/api/method";
import JSONBigInt from 'json-bigint';

const JSONBigIntStr = JSONBigInt({storeAsString: true});

export function useBoeApiPage(_url, params = {}, config = {
    init: true,
    result: res => res.result,
    totalPage: res => res.result.totalPage,
    total: res => res.result.totalElement
}) {

    const state = reactive({
        data: [],
        loading: false,
        page: 1,
        pageSize: 10,
        totalPage: 0,
        total: 0
    })

    function fetch() {
        state.loading = true
        return request(_url, params).then(r => {
            state.data = config.result(r)
            state.totalPage = config.totalPage(r)
            state.total = config.total(r)
            state.loading = false
            state.page = params.page
        })
    }

    function reset(){
        state.data = []
        state.loading = false
        state.page = 1
        state.totalPage = 0
        state.total = 0
    }

    config.init && fetch()
    return {
        ...toRefs(state),
        fetch,
        reset
    };
}

export function useBoeApi(_url, params = {}, config = {
    init: true,
    result: res => res.result,
}) {

    const state = reactive({
        data: [],
        loading: false,
    })
    watch(() => params, () => {
        fetch()
    })

    function fetch() {
        state.loading = true
        return request(_url, params).then(r => {
            state.data = config.result(r)
            state.loading = false
        })
    }

    config.init && fetch()
    return {
        ...toRefs(state),
        fetch,
    };
}

export function useBoeUserListPage(_url, params = {}, init = true) {

    const state = reactive({
        data: [],
        loading: false,
        total: 0,
        totalPage: 0,
        page: 1,
        ...params
    })

    watch(() => params.keyword, throttle(fetch, 600))
    watch(() => params.page, fetch)

    function fetch() {
        state.loading = true
        if (!params.keyword) {
            state.loading = false
            return
        }
        return request(_url, params).then(r => {
            state.data = params.page === 1 ? r.result.userInfoList : [...state.data, ...r.result.userInfoList]
            state.totalPage = r.result.totalPage
            state.total = r.result.totalElement
            state.loading = false
        })
    }

    init && fetch()
    return {
        ...toRefs(state),
        fetch,
    };
}

export function usePage(_url, params = {}, init = true) {

    const state = reactive({
        data: [],
        loading: false
    })

    watch(params, () => {
        fetch()
    })

    function fetch() {
        state.loading = true
        return request(_url, params).then(r => {
            console.log('fetch')
            console.log(r)
            state.data = r.result
            state.loading = false
        })
    }

    init && fetch()
    return {
        ...toRefs(state),
        fetch,
    };
}

export function useRequest(_url, params = {}, init = true) {

    const data = ref({})
    const loading = ref(false)

    watch(params, () => {
        fetchData()
    })

    function fetchData() {
        loading.value = true
        request(_url, params).then(r => {
            data.value = r
            loading.value = false
        })
    }

    init && fetchData()
    return {
        data,
        loading,
        fetchData,
    };
}

export async function request(_url, params) {
    const s = _url.split(' ')
    let url = s[0]
    const method = s[1]?.toLowerCase() || 'get'
    if (method === 'get') {
        let paramsArray = [];
        //拼接参数
        if (params) {
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
    }
    const body = method !== 'get' ? params || {} : {}
    url = process.env.NODE_ENV === 'development' ? url : process.env.VUE_APP_BOE_API_URL + url
    return fetch(url, {
        method,
        headers: {
            token: getCookieForName('token'),
            ...method !== 'get' ? {'Content-Type': 'application/json'} : {}
        },
        ...method !== 'get' ? {body: JSON.stringify(body)} : {}
    }).then(res => {
        return res.text()
    }).then(res => {
        return JSONBigIntStr.parse(res)
    })
    // return axios({
    //     url,
    //     method,
    //     headers: {
    //         token: getCookie('token'),
    //         ...method !== 'get' ? {'Content-Type': 'application/json'} : {}
    //     },
    //     baseURL: '',
    //     ...method !== 'get' ? {data: JSON.stringify(body)} : {}
    // }).then(resp => {
    //     return resp.data
    // }).then(response => {
    //     console.log(response)
    //     return response
    // }).catch(e => {
    //     console.log(2222)
    //     console.log(e)
    //     // router.push({path: '/login'})
    // })
}