import { getConfig } from "@/utils";
import axios from "axios";

// 创建axios实例
const service = axios.create({
  timeout: 60000,
});

service.interceptors.request.use(
  async (config) => {
    const { mapConfig } = await getConfig();
    const { server, key } = mapConfig;
    config.baseURL = server;
    if (config.method.toUpperCase() === "POST") {
      config.data = {
        ...config.data,
        key: key,
      };
    } else if (config.method.toUpperCase() === "GET") {
      config.params = {
        key: key,
        ...config.params,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const ipLocation = (params) => {
  return new Promise((resolve, reject) => {
    return service({
      url: "/v3/ip?",
      method: "GET",
      params,
    })
      .then((res) => {
        const { status, data } = res;
        if (status === 200) {
          resolve(data.city);
          return data.city;
        }
      })
      .catch((err) => {
        reject(new Error(err));
      });
  });
};

/**
 * 搜索POI
 * @param params
 * @returns {Promise<AxiosResponse<any>>}
 */
export const place = (params) => {
  return service({
    // url: "/v3/place/text?",
    url: "/v3/assistant/inputtips?",
    method: "GET",
    params,
  });
};
