import router from "@/router";
import {reactive, toRefs, watch} from "vue";
import axios from 'axios';
import {delCookie, getCookie} from "@/api/utils";
import JSONBigInt from 'json-bigint';
import {ElMessageBox} from 'element-plus'

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


export function usePage(_url, param, callback) {

    const state = reactive({
        data: {},
        loading: false,
        total: 0,
        size: 10,
        current: 1,
        params: { pageNo: 1, pageSize: 10, ...param }
    })

    watch(param, () => {
        state.params = { ...state.params, ...param }
        fetchData()
    })

    function fetchData() {
        state.loading = true
        request(_url, state.params).then(r => {
            state.params.pageNo === 1 ? (state.data = (r.data.records || r.data.rows)) : (state.data = [...state.data, ...(r.data.records || r.data.rows)])
            state.size = r.data.size
            state.total = r.data.total
            state.current = r.data.current
            state.loading = false
            callback(r)
        })
    }

    fetchData()
    return {
        ...toRefs(state),
        fetchData,
    };
}

export function useRequest(_url, params = {}, callback) {

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

    })

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

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

    fetchData()
    return {
        ...toRefs(state),
        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 || {} : {}
    return axios({
        url,
        method,
        headers: {
            'token': getCookie('token'),
            ...method !== 'get' ? { 'Content-Type': 'application/json' } : {}
        },
        baseURL: import.meta.env.VITE_BASE_API,
        ...method !== 'get' ? { data: JSON.stringify(body) } : {}
    }).then(resp => resp.data).then(response => {
        if (response.code !== 200 && response.code !== 0) {
            if (response.code === 1000) {
                delCookie();
                (import.meta.env.MODE === 'development' || import.meta.env.MODE === 'test') ? router.push({ path: '/login', query: { returnUrl: router.currentRoute.value.fullPath } }) : window.open(window.location.protocol + import.meta.env.VITE_BASE_LOGIN_URL + encodeURIComponent(window.location.protocol + import.meta.env.VITE_BOE_BASE_URL + import.meta.env.VITE_BASE + router.currentRoute.value.fullPath), '_top')
            }
            else if (response.code === 2001) {
                ElMessageBox.alert('抱歉，您不再本次参训名单中，请您联系管理员', '提示', {
                    confirmButtonText: '确定',
                    callback: () => router.push({ path: '/FaceTeachSignUp', query: { courseId: router.currentRoute.value.query.courseId, type: 3 } })
                })
            }
            else if (response.code === 2002) router.push({ path: '/FaceTeachNoCommon', query: { courseId: router.currentRoute.value.query.courseId, type: 3 } })
            else if (response.code === 9000) router.replace({ path: '/noData'})
            // if (import.meta.env.DEV && response.code === 1000) {
            //     router.push({path: '/login'})
            // } else {
            //     window.open()
            // response.showMsg && notification.open({
            //     message: response.showMsg,
            //     duration: 2,
            // });
            // }
        }
        return response
    })
}

export async function boeRequest(_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 || {} : {}
    return fetch(url, {
        method,
        headers: {
            token: getCookie('token'),
            ...method !== 'get' ? { 'Content-Type': 'application/json' } : {}
        },
        ...method !== 'get' ? { body: JSON.stringify(body) } : {}
    }).then(res => {
        return res.text()
    }).then(res => {
        return JSONBigIntStr.parse(res)
    })
}

const httpupload = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000 * 15,
    headers: { "Content-Type": "multipart/form-data" },
});

export const fileUp = (data) => httpupload.post(import.meta.env.VITE_BASE_API + "/file/upload", data, {
    headers: { "Content-Type": "multipart/form-data" },
});
export const videoUp = (data) => httpupload.post("/file/uploadunlimit", data, {
    headers: { "Content-Type": "multipart/form-data" },
});

