import { rootUrl,whiteListUrl } from "@/apis/config" //根路径
// #ifdef MP-WEIXIN
import { logInfo } from '@/utils/log'
// #endif
import { jumpPage } from "@/utils/uniapi.js";
import { store } from '@/store'



/**
 * 根路径的类型
 */
const rootType = (type) => {
    let rootType = type ? type : 'wxC4' // 默认为wxC4
    // if (rootType === 'wxC4' && store.getters['indexPage/isGy']) rootType = 'wxGy'
    if (rootType === 'wxC4' && store.getters['indexPage/dns']) {
        rootType = store.getters['indexPage/dns']
    }
    return rootType
}

/**
 * header
 */
const headerType = (options) => {
    if (options) {
        if (options.method === 'POST' || options.method === 'PUT') {
            return {
                'content-type': 'application/x-www-form-urlencoded'
            }
        }
    } else {
        return ''
    }

}

/**
 * 请求日志
 */
const logInfoItem = (url, options, startTime, endTime, token, data,rootUrl) => {
    // #ifdef MP-WEIXIN
    let logJson = {
        rootUrl:rootUrl,
        url: url,
        params: options.data,
        time: endTime - startTime,
        token,
        data: JSON.stringify(data)
    }
    logInfo(logJson)
    // #endif
}

const request = (url, options = {}, root) => {
    return new Promise((resolve, reject) => {
        let type = rootType(root)   // 根路径类型

        let apiUrl = rootUrl[type] + url

        // #ifdef H5
        apiUrl = url
        // #endif

        // header
        options.header = headerType(options)

        // token
        let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
        if(whiteListUrl.includes(url) && !store.getters['indexPage/isMaterial']) token = ''

        let startTime = +new Date() // 开始时间

        // store.commit('showLoad')
        uni.request({
            url: apiUrl,
            method: options.method || 'GET',
            data: options.data,
            // timeout: 15000,         // 15s
            header: {
                token: token || '',
                ...options.header
            },
            success: ({ data, statusCode }) => {
                const endTime = +new Date() // 结束时间
                // console.log(apiUrl, '花费时间', endTime - startTime)
                if (statusCode !== 200 && statusCode !== 304) {
                    console.log(statusCode)
                    let msg = '请求出错'
                    reject(msg)
                }

                let errMessage = ''
                let code, res, desc

                if (root === 'gdMap') {
                    code = data.status === '1' ? '0' : data.status

                    res = data.regeocode ? JSON.stringify(data.regeocode) : JSON.stringify(data)

                    if (data.info !== 'ok') errMessage = data.info
                } else {
                    code = data.code
                    res = data.data
                    desc = data.desc
                }

                if (code !== '-104') logInfoItem(url, options, startTime, endTime, token, data,rootUrl[type]) // 请求日志 微信


                if (code === '0') {
                    resolve(JSON.parse(res))
                } else if (code === '-1') {
                    // 注册
                    if (url.includes('RegisterUser') && desc === '用户标识已经存在' || desc === '要登录类型已经存在') {
                        resolve(desc)
                    } else if (url.includes('CreateOrder') && desc.includes('配送范围')) {
                        resolve(desc)
                    } else {
                        errMessage = desc
                    }

                    // 校验地址范围
                } else if (code === '-104') {
                    resolve({
                        ...data
                    })
                } else {
                    if (code === '-2') {
                        // 清空登录信息
                        store.commit('login/changeLoginStatus', '')

                        // 清空购物车
                        store.commit('cartPage/saveCartList', [])

                        errMessage = '身份验证过期，请重新登录'

                        jumpPage('switchTab', '/pages/mine/index', 800)
                    } else if (code === '-3') {
                        errMessage = code
                    } else {
                        if (desc === '需要正式TOKEN' || desc === "token过期或无效，请重新登录") {
                            errMessage = '登录过期，请重新登录'
                            jumpPage('switchTab', '/pages/mine/index', 800)
                        } else {
                            errMessage = desc
                        }
                    }
                }
                if (errMessage) reject(new Error(errMessage))
                // store.commit('hideLoad')
            },
            fail: (err) => {
                console.log('请求错误', err)
                const endTime = +new Date()
                logInfoItem(url, options, startTime, endTime, token, err,rootUrl[type]) // 请求日志 微信
                // store.commit('hideLoad')
                reject(err)
            }

        })
    })

}

export default request