import axios from "axios";
import router from "../../router";
import qs from "qs";
// import { Message as iviewMessage, Notice as iviewNotice } from 'view-design'
import { MessageBox, Toast } from "mint-ui";
//接口报错弹出
let CommonAlert = function (msg) {
  if (msg.length > 0) {
    return Toast({
      message: msg,
      duration: 1500,
    });
  }
};

// axios.defaults.timeout = 5000;
if (process.env.NODE_ENV == "development") {
  // axios.defaults.baseURL = 'https://inno.sh-sict.com/screening-api/';
} else {
  axios.defaults.baseURL = process.env.VUE_APP_URL;
}
window.baseURL = axios.defaults.baseURL;
//http request 拦截器
axios.create({
  withCredentials: true,
});
axios.interceptors.request.use(
  (config) => {
    config.data = config.data;
    config.headers["user-cookie"] = localStorage.getItem("token");
    if (config.url === "/ewell-tumors-user/province/list") {
      //坐下判断如果是获取省市接口则不做拦截
    }
    //  else if(!localStorage.getItem("token")){
    //     toLogin()
    //   }
    return config;
  },
  (error) => {
    return Promise.reject(err);
  }
);

/**
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  router.replace({
    path: "/register",
    query: {
      redirect: router.currentRoute.fullPath,
    },
  });
};

//响应拦截器即异常处理
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === 0 || response.data.code === -1) {
      CommonAlert(response.data.message);
    } else if (response.data.code === -100) {
      localStorage.removeItem('token')
      window.location.hash = "/register";
    }
    return response;
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          CommonAlert("错误请求");
          console.log("错误请求");
          break;
        case 401:
          CommonAlert("未授权，请重新登录");
          toLogin();
          console.log("未授权，请重新登录");
          break;
        case 403:
          CommonAlert("拒绝访问");
          console.log("拒绝访问");
          break;
        case 404:
          CommonAlert("请求错误,未找到该资源");
          console.log("请求错误,未找到该资源");
          break;
        case 405:
          CommonAlert("请求方法未允许");
          console.log("请求方法未允许");
          break;
        case 408:
          CommonAlert("请求超时");
          console.log("请求超时");
          break;
        case 500:
          CommonAlert("服务器端出错");
          console.log("服务器端出错");
          break;
        case 501:
          CommonAlert("网络未实现");
          console.log("网络未实现");
          break;
        case 502:
          CommonAlert("网络错误");
          console.log("网络错误");
          break;
        case 503:
          CommonAlert("服务不可用");
          console.log("服务不可用");
          break;
        case 504:
          CommonAlert("网络超时");
          console.log("网络超时");
          break;
        case 505:
          CommonAlert("http版本不支持该请求");
          console.log("http版本不支持该请求");
          break;
        default:
          CommonAlert(`连接错误${err.response.status}`);
          console.log(`连接错误${err.response.status}`);
      }
    } else {
      CommonAlert("连接到服务器失败");
      console.log("连接到服务器失败");
    }
    return Promise.resolve(err.response);
  }
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, {
        params,
      })
      .then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}
export function postForm(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(data), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
      .then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}

//用来导出excel
export function expoertExcel(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(data), {
        responseType: "blob",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
      .then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}

//下载excel
export function downloadExcel(url, data = {}, title = "筛查信息导出表") {
  return axios({
    method: "post",
    url: url,
    data: data,
    responseType: "blob",
  })
    .then((res) => {
      if ("msSaveOrOpenBlob" in navigator) {
        //兼容ie
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel",
        });
        window.navigator.msSaveOrOpenBlob(blob, `${title}.xlsx`);
        return;
      } else {
        const link = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", `${title}.xlsx`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    })
    .catch((error) => {
      // this.$Notice.error({
      //   title: '错误',
      //   desc: '系统数据错误',
      // })
      CommonAlert("系统数据错误");
      console.log(error);
    });
}
/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function Delete(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

export function getUrl() {
  return axios.defaults.baseURL;
}
