import axios from 'axios'
import {Toast} from "vant";
import { tansParams } from "../api/tansParams";
import { getUrlLink } from '@/config/config';
/**
 * 封装axios
 * @param url 请求地址
 * @param params 传递参数 格式：{ name:'张三',age:18,sex:'男'}
 * @param type 请求方式
 * @returns {Promise<unknown>} 最终返回一个Promis
 * {
 *
 * }
 */
export default function ajax(url = '', params = {}, type = 'GET') {
   axios.defaults.headers.common['Authorization'] = sessionStorage.getItem('token');
    // 1 定义变量，接收最终输出
    let promise;
    // 2 返回一个promise对象
    return new Promise((resolve, reject) => {
        // 2.1 请求类型
        if (type.toUpperCase() === 'GET') {
            // get 请求 如果是get请求，url最终为 baseURL?name=张三&age=18&sex=男
            // 2.2 拼接字符串
            let paramsStr = '';
            // 2.3 遍历
            Object.keys(params).forEach(key => {
                paramsStr += key + '=' + params[key] + '&';
            });
            // 2.4 过滤最后的&
            /*
              注意：为了防止请求缓存，在尾部加了时间戳
            */
            // if (paramsStr) {
            //     paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'));
            //     url += '?' + paramsStr;
            // } else {
            //     if (url.indexOf('47.98.157.152') === -1) {
            //         url += '?itlike=' + randomCode(20)
            //     }
            // }
            // 2.6 发起get请求
            promise = axios.get(url);
        } else if (type.toUpperCase() === 'POST') {
            // post 请求
            // 2.7 发起post请求
            promise = axios.post(url, params);
        }else if(type.toUpperCase() === 'PUT'){
            
            console.log(params,'params')
            let urlStr=url+'?'+tansParams(params)
            promise = axios.put(urlStr);
        }
        // 2.8 处理结果并返回
        promise.then((response) => {
            console.log(response)
            if (response.status && response.status !== 200) {
                Toast('请求失败！')
              } else {
                if (response.data.code === 200 || response.data.code == '00000000') {
                    resolve(response.data)
                }else if(response.data.code == 500){
                    if(response.data.msg){
                        Toast(response.data.msg)
                    }else{
                        Toast('接口异常')
                    }
                }else if(response.data.code === 401){
                    Toast('token已失效');
                    sessionStorage.removeItem('token');
                    sessionStorage.removeItem('userInfo');
                    if(localStorage.getItem("appId")){
                        window.location.href = getUrlLink(localStorage.getItem("appId"), localStorage.getItem("agentId"));
                    }
                }else{
                    Toast(response.data.msg)
                }
              }
        }).catch((error) => {
            if (error.message.substr(-3) == '401') {
                console.log(22222222)
                const u = navigator.userAgent;
                const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
                if (isiOS) {
                    window.webkit.messageHandlers.zrubApp.postMessage({
                        method: 'logout'
                    })
                } else {
                    window.android.logout();
                }
                console.log(error.message.substr(-3))
            }else if(error.message.substr(-3) == '403'){
                Toast('您没有权限访问，请联系管理员')
            }
            reject(error);
        })
    })
}

/*生成指定长度的随机数*/
function randomCode(length) {
    let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let result = "";
    for (let i = 0; i < length; i++) {
        let index = Math.ceil(Math.random() * 9);
        result += chars[index];
    }
    return result;
}
