import { Upload } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import { PORT_NONE } from "@/api/config/servicePort";
import httpStore from "@/api/indexStore";
import http from "@/api";
import axios from "axios";
import { ResultEnum } from "@/enums/httpEnum";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage } from "element-plus";
import { LOGIN_URL } from "@/config";
import router from "@/routers";

// 使用 alienStore 前缀的 axios 实例（用于价目表等页面上传）
const httpStoreAlienStore = axios.create({
  baseURL: import.meta.env.VITE_API_URL_STORE as string,
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials: true
});
httpStoreAlienStore.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (config.headers) (config.headers as any).Authorization = userStore.token;
    return config;
  },
  error => Promise.reject(error)
);
httpStoreAlienStore.interceptors.response.use(
  response => {
    const data = response.data;
    const userStore = useUserStore();
    if (data.code == ResultEnum.OVERDUE) {
      userStore.setToken("");
      router.replace(LOGIN_URL);
      ElMessage.error(data.msg);
      return Promise.reject(data);
    }
    if (data.code && data.code !== ResultEnum.SUCCESS) {
      ElMessage.error(data.msg);
      return Promise.reject(data);
    }
    return data;
  },
  error => Promise.reject(error)
);

/**
 * @name 文件上传模块
 */
// 图片上传（默认使用 alienStorePlatform）
export const uploadImg = (params: FormData) => {
  return httpStore.post<Upload.ResFileUrl>(PORT_NONE + `/file/uploadMore`, params, { cancel: false });
};

// 图片上传（使用 alienStore 前缀，用于价目表等页面）
export const uploadImgStore = (params: FormData) => {
  return httpStoreAlienStore.post<Upload.ResFileUrl>(PORT_NONE + `/file/uploadMore`, params, { cancel: false });
};

// 视频上传
export const uploadVideo = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT_NONE + `/file/upload/video`, params, { cancel: false });
};
