import qs from 'qs'
import md5 from 'js-md5'
import config from '../js/config'
import fn from '../js/function'
import plugin from '../js/plugin'
import router from '../js/router'
import store from '../store'

const http = {
    /**
     * ajax请求处理
     * @param type
     * @param url
     * @param data
     * @param map
     * @param repeat
     * @param awaitTime
     * @param isJson
     * @returns {Promise<*|Promise<any>|Promise<Promise<any>|*>>}
     */
    async ajax(type, url, data = {}, { map = {}, repeat = false, awaitTime = 1000, isJson = false } = {}) {
        const self = this
        let httpKey = md5(url + qs.stringify(data))
        let ContentType = 'application/x-www-form-urlencoded;charset=UTF-8;'

        // 重复请求检测
        if (repeat) {
            let httpInfo = store.state.http[httpKey]

            if (httpInfo && self.isRepeat(httpKey)) {
                console.warn('重复请求过滤')
                return new Promise((resolve) => {
                    resolve({
                        code: '-1',
                        data: '',
                        message: '正在处理中，请稍等...',
                        requestData: '',
                    })
                })
            } else {
                // 记录请求信息
                store.commit('http/add', httpKey)
            }
        }

        // 请求数据处理
        data = self.request(data, map)

        // get请求url处理
        if (type === 'GET') {
            data = qs.stringify(data)
            url = url + '?' + data
        }

        // json请求类型处理，兼容后台接口混乱问题
        if (isJson) {
            ContentType = 'application/json;charset=UTF-8;'
        } else {
            data = qs.stringify(data)
        }

        // 添加请求基地址
        if (url.indexOf('http') < 0) {
            url = config.apiBaseUrl + url
        }

        // 发送请求
        let header = {
            'Accept': 'application/json',
            'Content-Type': ContentType,
            'appId': store.state.user.user ? (store.state.user.user.appId || '') : '',
            'companyId': store.state.user.user ? (store.state.user.user.companyId || '') : '',
            'userId': store.state.user.user ? (store.state.user.user.id || '') : '',
            'Authorization': 'Bearer ' + store.state.user.token,
            // 'StoreId': store.state.common.curShop.id || ''
        }
        if (store.state.user && store.state.user.user) {
            header.StoreId = store.state.user.user.storeId || '';
        }
        let response = await uni.request({
            url: url,
            data: data,
            header: header,
            method: type,
        })

        return self.response(response, {
            map: map,
            httpKey: httpKey,
            repeat: repeat,
            awaitTime: awaitTime,
            request: arguments,
        })
    },

    /**
     * 是否是重复请求处理
     * @param httpKey
     * @returns {boolean}
     */
    isRepeat(httpKey) {
        let httpInfo = store.state.http[httpKey]
        let nowTime = new Date().getTime()
        let outTime = 5

        return httpInfo && nowTime < httpInfo + outTime * 1000
    },

    /**
     * 请求参数处理
     * @param data
     * @param map
     * @returns {*}
     */
    request(data, map) {
        const self = this

        // data.device = data.device || 'web'
        // data.timestamp = data.timestamp || self.getTimestamp()
        // data.noncestr = data.noncestr || fn.uuid('')

        // 请求数据映射处理
        data = fn.deepClone(data)
        data = fn.objSetKey(data, map)

        for (let key in data) {
            if (data.hasOwnProperty(key) && (data[key] === undefined)) {
                delete data[key]
            }
        }

        // 签名处理
        // data = self.setSign(data)

        return data
    },

    /**
     * 获取时间戳
     */
    getTimestamp() {
        let differTimestamp = store.state.common.differTimestamp || 0
        let localTimestamp = parseInt(new Date().getTime() / 1000)

        return localTimestamp + differTimestamp
    },

    /**
     * 添加签名处理
     * @param data
     * @returns {*|{}}
     */
    setSign(data) {
        let sign = '' // 签名

        data = fn.objSort(data)
        sign = decodeURIComponent(qs.stringify(data))
        data.sign = md5(sign + config.salt)

        return data
    },

    /**
     * 请求响应处理
     * @param res
     * @param map
     * @param repeat
     * @param httpKey
     * @param awaitTime
     * @param request
     * @returns {Promise<any>}
     */
    response(res, { map = {}, httpKey = '', repeat = false, awaitTime = '', request = [] } = {}) {
        const self = this

        return new Promise(async resolve => {
            let response = res[1]
            let data = {
                success: response.data.success,
                affectedRows: response.data.affectedRows,
                code: response.data.code,
                message: '无法访问到服务器',
                data: '',
            }

            // 移除请求记录
            if (repeat) {
                setTimeout(function () {
                    store.commit('http/success', httpKey)
                }, awaitTime)
            }

            // 请求成功数据处理
            if (response.statusCode === 200) {
                //图片地址单独处理
                if (request[1] === '/Coupon/GetQrCode') {
                    data = response;
                } else {
                    data = {
                        success: response.data.success,
                        affectedRows: response.data.affectedRows,
                        code: response.data.code,
                        message: response.data.message || '',
                        data: fn.objSetKey(response.data.data, map, true),
                    }
                }
            } else if (response.statusCode === 401) {
                await plugin.getToken()
                data = await self.ajax(request[0], request[1], request[2], request[3])
                // router.push({
                //     path:'/pages/index/login',
                //     isTabBar:true
                // });
            } else {
                console.error(response.data)
            }

            resolve(data)
        })
    },
}

export default {
    /**
     * get请求(获取)
     * @param url
     * @param data
     * @param config
     * @returns {*}
     */
    get(url, data, config) {
        return http.ajax('GET', url, data, config)
    },

    /**
     * post请求（添加）
     * @param url
     * @param data
     * @param config
     * @returns {*}
     */
    post(url, data, config) {
        return http.ajax('POST', url, data, config)
    },

    /**
     * put请求（修改）
     * @param url
     * @param data
     * @param config
     * @returns {*}
     */
    put(url, data, config) {
        return http.ajax('PUT', url, data, config)
    },

    /**
     * delete请求（删除）
     * @param url
     * @param data
     * @param config
     * @returns {*}
     */
    delete(url, data, config) {
        return http.ajax('DELETE', url, data, config)
    },
}
