import useUserStore from 'mocp/store/user'

// const baseURL = 'https://hna-platform.anyremote.cn' //测试
// const baseURL = 'https://moc.hnatechnic.com/api' //生产
// const baseURL = 'http://10.123.48.67/api' //Amms内网
// const baseURL = 'http://10.121.48.157/gky_mocp_bs/api' //北数高可用测试环境
const baseURL = 'https://hnaelbtest.hnatechnic.com/mocptest/api' //内网

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)
    //application
    const application = options.application || 'form'
    //重组提交数据
    if (options.data) {
        if (application == 'json') {
            //传对象
        } else {
            options.data = {
                ...options.data,
                apiPwd: 'Ifar$2_0160_525_Mocp',
                requestFrom: '1',
                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: '1',
            uid: userStore.userInfo?.id
        }
        options.header = {
            ...options.header
        }
    } else {
        if (application == 'json') {
            options.header = {
                'Content-Type': 'application/json',
                Requestfrom: '1',
                Realuserid: userStore.userInfo?.id,
                ...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 {
                    const path = res.data.path || options.url.replace(baseURL, '')
                    uni.$mocpMessage.error(path + '接口错误')
                    reject(res)
                }
            },
            fail(err) {
                serviceLoading.close(loading)
                uni.$mocpMessage.error('网络错误，换个网络试试')
                reject(err)
            }
        })
    })
}
//post请求
export const post = (options) => {
    options = {
        application: 'json',
        ...options
    }
    return http(options)
}
//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)
            }
        })
    })
}
