import axios from "axios";
import qs from "qs";
import { Message, Loading } from "element-ui";
import { getToken, setToken,getDeviceId } from "@/utils/auth";
import router from "../router";
import {GetUserInfo} from "@/api/permission";

axios.defaults.responsetype = "json";
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;

let timeout = 5 * 60 * 1000;
let fileName = "", type = ""; //下载的fileName, suffix

let loading;
let loadingCount = 0;

// 请求时的拦截器
axios.interceptors.request.use(
  (config) => {
    if (getToken() != undefined) {
      config.headers["Authorization"] = getToken();
    }
    if (getDeviceId() != undefined) {
      config.headers["deviceId"] = getDeviceId();
    }
    loading = Loading.service({
      text: "Loading",
      customClass: "loading"
    });
    loadingCount++;

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求完成后的拦截器
axios.interceptors.response.use(
  (response) => {
    console.log('response',response)

    loadingCount--;
    if (loadingCount < 1) {
      loading && loading.close();
    }
    // if (
    //   !(
    //     response.headers?.Authorization === undefined ||
    //     response.headers?.Authorization == null
    //   )
    // ) {
    //   setToken(response.headers.Authorization);
    // }
    if (response.headers["filename"]) {
      fileName = response.headers["filename"];
      let typeArr = fileName.split(".");
      type = typeArr[typeArr.length - 1];
    }
    if (response.data && response.data.code && response.data.code !== 200) {
      Message.error(response.data.message);
      return response.data;
    }
    return response.data;
  },
  (error) => {
    console.log('error',error)
    loadingCount--;
    if (loadingCount < 1) {
      loading && loading.close();
    }
    if(error.response.status === 403) {
      Message.error("Permission denied, Default adjustment to the user's permission page");
      const allMenuList = [
        { id: '1', name: 'Group Management', path: '/groupManagement' },
        { id: '2', name: 'Ticket Management', path: '/ticketManagement' },
        { id: '3', name: 'Configuration Management', path: '/configurationManagement' },
        { id: '4', name: 'Permission Management', path: '/permissionManagement/userList' },
        { id: '5', name: 'Data Source Management', path: '/datasourceManagement' },
      ]
      GetUserInfo().then(res => {
        if(res['resources'].length){
          let menuList = allMenuList.filter(item => res['resources'].map(item => item['resname']).includes(item.name));
          router.push({ path: menuList[0].path})
        }
      })
      return
    }
   
    if (error.response.status === 401) {
      // router['$keycloak'].logout()
      // window.location.reload();
    }else{
      Message.error(error.response.data.message)
    }
    return Promise.reject(error);
  }
);

const GET = (url, data) => {
  let requestHeaders = {
    "X-Requested-With": "XMLHttpRequest",
    Accept: "application/json",
    "Content-Type": "application/json; charset=UTF-8",
    Authorization: sessionStorage.getItem("token")
  };

  // http默认配置
  let httpDefaultOpts = {
    headers: requestHeaders,
    method: "get",
    url: url,
    timeout: timeout,
    params: data,
  };

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts).then((res) => {
      resolve(res);
    });
  });
  return promise;
};

const POST = (url, data, requestBody = false, params = {}) => {
  let requestHeaders;
  if (requestBody) {
    requestHeaders = {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": "application/json;charset=UTF-8",
      Authorization: sessionStorage.getItem("token"),
    };
  } else {
    requestHeaders = {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      Authorization: sessionStorage.getItem("token"),
    };
  }
  // http默认配置
  let httpDefaultOpts = {
    method: "post",
    url: url,
    timeout: timeout,
    params: params,
    data: requestBody ? JSON.stringify(data) : qs.stringify(data),
    headers: requestHeaders,
  };

  if (!requestBody) {
    delete httpDefaultOpts.params;
  }

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts).then((res) => {
      resolve(res);
    });
  });
  return promise;
};

const PUT = (url, data, requestBody = false, params = {}) => {
  let requestHeaders;
  if (requestBody) {
    requestHeaders = {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": "application/json;charset=UTF-8",
      Authorization: sessionStorage.getItem("token"),
    };
  } else {
    requestHeaders = {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      Authorization: sessionStorage.getItem("token"),
    };
  }
  // http默认配置
  let httpDefaultOpts = {
    method: "put",
    url: url,
    timeout: timeout,
    params: params,
    data: requestBody ? JSON.stringify(data) : qs.stringify(data),
    headers: requestHeaders,
  };

  if (!requestBody) {
    delete httpDefaultOpts.params;
  }

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts).then((res) => {
      resolve(res);
    });
  });
  return promise;
};

const Delete = (url, data) => {
  let requestHeaders = {
    "X-Requested-With": "XMLHttpRequest",
    Accept: "application/json",
    "Content-Type": "application/json; charset=UTF-8",
    Authorization: sessionStorage.getItem("token"),
  };

  // http默认配置
  let httpDefaultOpts = {
    headers: requestHeaders,
    method: "delete",
    url: url,
    timeout: timeout,
    params: data,
  };

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts).then((res) => {
      resolve(res);
    });
  });
  return promise;
};

const UploadFile = (url, data) => {
  let params = new FormData();
  for (const key in data) {
    params.append(key, data[key]);
  }
  return new Promise(function(resolve, reject) {
    axios
      .post(url, params, {
        timeout: 2 * 60 * 60 * 1000,
        headers: {
          "Content-Type": "multipart/form-dataUpload",
        },
      })
      .then((res) => {
        resolve(res);
      });
  });
};

const DownloadExcel = (url, data) => {
  Download(url, data).then((res) => {
    const blob = new Blob([res], {
      type: `application/${type || "ynd.ms-excel"}`,
    });
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
      const aEle = document.createElement("a"); // 创建a标签
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      aEle.href = href;
      aEle.download = fileName; // 下载后文件名
      document.body.appendChild(aEle);
      aEle.dispatchEvent(
        new MouseEvent("click", {
          bubbles: true,
          cancelable: true,
          view: window,
        })
      );
      document.body.removeChild(aEle); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    }
  });
};

const Download = (url, data) => {
  let httpDefaultOpts = {
    method: "get",
    url: url,
    timeout: timeout,
    params: data,
    responseType: "blob",
  };

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts).then((res) => {
      resolve(res);
    });
  });
  return promise;
};

export { POST, GET, Delete, UploadFile, DownloadExcel,PUT };
