import Vue from "vue";
import axios from "axios";
import user from "@/store/modules/user";
import { Message } from "@/utils/message";
import md5 from "js-md5";
import { getErrMsg } from "@/utils";
import i18n from "@/lang";
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 3000,
  withCredentials: true
});
const appKey = "cd72c223-923f-44a3-aede-b9f07dcd56b8";
const plat = "steelfurniture";
const v = "1.0";
instance.interceptors.request.use(
  ({
    headers: { timestamp = Date.now(), token = user.Token, ...h },
    ...x
  }) => ({
    headers: {
      timestamp,
      appKey,
      plat,
      v,
      token,
      sign: md5(`timestamp${timestamp}plat${plat}v${v}appKey${appKey}`),
      ...h,
      language: i18n.locale
    },
    ...x
  })
);

instance.interceptors.response.use(
  x => x,
  err => ({
    data: {
      code: -100,
      data: err
    }
  })
);
const getResult: <T>(x: IBaseResult) => IResult<T> = <T>({
  data,
  code
}: IBaseResult<T>) => {
  if (code === 0) return [null, data];
  Message.error(getErrMsg(code));
  return [{ code }, (data || {}) as T];
};
export const post: IRequest = async <T>(url: string, params: any) => {
  const { data } = await instance.post<IBaseResult<T>>(url, params);
  return getResult<T>(data);
};
export const get: IRequest = async <T>(url: string, params: any) => {
  const { data } = await instance.get<IBaseResult<T>>(url, { params });
  return getResult<T>(data);
};
export default {
  install(vue: typeof Vue) {
    Object.assign(vue.prototype, {
      $get: get,
      $post: post
    });
  }
};
