import useUserStore from 'mocp/store/user'

const baseURL = 'https://hna-platform.anyremote.cn'

class ServiceLoading {
    open(loading) {
        if (loading || loading === '') {
            let loadingText = '加载中'
            if (typeof loading === 'string' && loading !== '') {
                loadingText = loading
            }
            uni.showLoading({
                title: loadingText,
                mask: true
            })
        }
    }
    close(loading) {
        if (loading || loading === '') {
            uni.hideLoading()
        }
    }
}
const serviceLoading = new ServiceLoading()
//请求拦截器
export const httpInterceptor = (options) => {
    const userStore = useUserStore()
    //responseType
    if (options.config?.arraybuffer) {
        options.responseType = 'arraybuffer'
    }
    //loading
    const loading = options.config?.loading
    serviceLoading.open(loading)
    //重组提交数据
    if (options.data) {
        options.data = {
            ...options.data,
            apiPwd: 'Ifar$2_0160_525_Mocp',
            requestFrom: '6',
            realUserId: userStore.userInfo?.id
        }
    }
    // 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
        options.url = baseURL + options.url
    }
    // 请求超时, 默认 60s
    options.timeout = 60000
    // 添加小程序端请求头标识
    if (options.name == 'file') {
        options.formData = {
            ...options.formData,
            apiPwd: 'Ifar$2_0160_525_Mocp',
            requestFrom: '6',
            uid: userStore.userInfo?.id
        }
        options.header = {
            ...options.header
        }
    } else {
        options.header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            ...options.header
        }
    }
    // 添加 token 请求头标识
    if (userStore.token) {
        options.header.Authorization = `Bearer ${userStore.token}`
    }
    console.log('接口请求信息:', options)
    return options
}
//http请求
export const http = (options) => {
    options = httpInterceptor(options)
    //loading
    const loading = options.config?.loading
    // 1. 返回 Promise 对象
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                console.log('接口响应结果:', res)
                serviceLoading.close(loading)
                const statusCode = res.statusCode
                if (statusCode >= 200 && statusCode < 300) {
                    if (res.data.code == 403) {
                        const userStore = useUserStore()
                        uni.$mocpMessage.error(res.data.message)
                        setTimeout(() => {
                            userStore.handleLogOut()
                        }, 500)
                        reject(res)
                    } else {
                        resolve(res.data)
                    }
                } else if (statusCode == 401) {
                    const userStore = useUserStore()
                    uni.$mocpMessage.error(res.data.message)
                    setTimeout(() => {
                        userStore.handleLogOut()
                    }, 500)
                    reject(res)
                } else {
                    uni.$mocpMessage.error(res.data.message || '请求错误')
                    reject(res)
                }
            },
            fail(err) {
                serviceLoading.close(loading)
                uni.$mocpMessage.error('网络错误，换个网络试试')
                reject(err)
            }
        })
    })
}
//upload请求
export const upload = (options) => {
    options = httpInterceptor(options)
    //loading
    const loading = options.config?.loading
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            ...options,
            success: (res) => {
                console.log('接口响应结果:', res)
                serviceLoading.close(loading)
                const statusCode = res.statusCode
                if (statusCode >= 200 && statusCode < 300) {
                    if (res.data.code == 403) {
                        const userStore = useUserStore()
                        uni.$mocpMessage.error(res.data.message)
                        setTimeout(() => {
                            userStore.handleLogOut()
                        }, 500)
                        reject(res)
                    } else {
                        resolve(JSON.parse(res.data))
                    }
                } else if (statusCode == 401) {
                    const userStore = useUserStore()
                    uni.$mocpMessage.error(res.data.message)
                    setTimeout(() => {
                        userStore.handleLogOut()
                    }, 500)
                    reject(res)
                } else {
                    uni.$mocpMessage.error(res.data.message || '请求错误')
                    reject(res)
                }
            },
            fail: (err) => {
                serviceLoading.close(loading)
                uni.$mocpMessage.error('上传失败')
                reject(err)
            }
        })
    })
}
