import { confirm } from "@/helper/message";
import {
  PaggingReq,
  PaggingRes,
  axios,
  cancelUModel,
  checkGenMeshScene,
  delScene,
  deleteModel,
  genMeshSceneByCloud,
  getModelRunProgress,
  getModelSceneList,
  getSceneList,
  updateModelScene,
  uploadModel,
} from "@/request";
import { ElMessage } from "element-plus";

interface BaseScene {
  title: string;
  time: string;
  type: SceneType;
  id: string;
}

// 只有当location 为4 时，才能生成obj
export enum LocationEnum {
  Scene_Location_Slam, //slam\n" +
  Scene_Location_SFM, //sfm\n" +
  Scene_Location_SFMAI, //SFM + AI\n" +
  Scene_Location_MutiFloor, //多楼层\n" +
  Scene_Location_PointCloud, //点云\n" +
  Scene_Location_SLAMPoint, //slam实时拍\n" +
  Scene_Location_SLAMPointAndSFMAI, //slam实时拍+站点\n" +
}

export type QuoteScene = BaseScene & {
  hasSynchronized: boolean;
  sceneNum: string;
  sceneName: string;
  createTime: string;
  vrLink: string;
  num: string;
  snCode: string;
  location: LocationEnum;
  viewCount: number;
  step?: number;
  status: QuoteSceneStatus;
};

// 普通场景状态
export enum QuoteSceneStatus {
  DEL = -1,
  RUN = 0,
  ERR = 1,
  SUCCESS = 2,
  ARCHIVE = 3,
  RERUN = 4,
}

export interface ModelScene extends BaseScene {
  modelTitle: string;
  modelId: number;
  createStatus: ModelSceneStatus;
  modelSize: string;
  sysLevel: boolean;
  modelDateType: string;
  progress?: number;
  createTime: string;
}

export type Scene = QuoteScene | ModelScene;

export enum SceneType {
  SWKK,
  SWKJ,
  SWSS,
  SWMX,
  SWSSMX,

  SWYDSS,
  SWYDMX,
  QJKK,
}

// 模型场景状态
export enum ModelSceneStatus {
  ERR = -1,
  RUN = 0,
  SUCCESS = 1,
  CANCEL = -2,
}

export const setModelScene = (scene: ModelScene) =>
  axios.post(updateModelScene, {
    modelId: scene.modelId,
    modelTitle: scene.modelTitle,
  });

export const cancelUploadModelScene = (scene: ModelScene) =>
  axios.get(cancelUModel, { params: { modelId: scene.modelId } });

export const delModelScene = (scene: ModelScene) =>
  axios.post(deleteModel, { modelId: scene.modelId });

export const uploadModelScene = async (
  file: File,
  progressCallback: (progress: number) => void
) => {
  let done = false;
  await axios<undefined>({
    method: "POST",
    url: uploadModel,
    data: { file },
    onUploadProgress(event: any) {
      if (!done) {
        const p = Math.round((event.loaded / event.total) * 100);
        if (p === 100) {
          progressCallback(0);
        } else {
          progressCallback(p || 0);
        }
        console.log("进度：", p);
      }
    },
  });
  console.log("上传完成");
  done = true;
  progressCallback(0);
};

export const getModelSceneStatus = async (scene: ModelScene) => {
  const progress = (
    await axios.get<number>(getModelRunProgress, {
      params: { modelId: scene.modelId },
    })
  ).data;

  return {
    progress,
    status:
      progress >= 100
        ? ModelSceneStatus.SUCCESS
        : progress < 0
        ? ModelSceneStatus.ERR
        : ModelSceneStatus.RUN,
  };
};

// *-----公用

type ScenePaggingParams = PaggingReq<
  Pick<BaseScene, "type"> & {
    modelTitle: string;
    sceneName: string;
    status?: number;
    caseId?: number;
    deptId: string;
    snCode: string;
  }
>;

export const getSceneStep = async (scene: QuoteScene) => {
  const data = (await axios.get<{ step: number }>(
    `/fusion/scene/getSceneProgress`,
    { params: { num: scene.num } }
  )) as any;
  console.log(data.data.data.progress);
  return data.data.data.progress;
};

export const getScenePagging = async (params: ScenePaggingParams) => {
  const urls = {
    [SceneType.SWMX]: getModelSceneList,
    [SceneType.QJKK]: "/fusion/scene/overallList",
  };
  const url = urls[params.type] || getSceneList;
  if (params.type === SceneType.QJKK) {
    let data = (await axios.post(url, params)).data as PaggingRes<any>;
    data = data || { list: [], total: 0 };
    // calc_status;
    data.list.forEach((item) => {
      item.type = SceneType.QJKK;
      item.calcStatus =
        item.calcStatus === 1
          ? QuoteSceneStatus.SUCCESS
          : item.calcStatus === 0
          ? QuoteSceneStatus.RUN
          : item.calcStatus === -1
          ? QuoteSceneStatus.ERR
          : QuoteSceneStatus.ARCHIVE;
    });

    return data;
  } else {
    return (await axios.get(url, { params })).data as PaggingRes<Scene>;
  }
};

export const delQuoteScene = (scene: QuoteScene) =>
  axios.get(delScene, { params: { num: scene.num } });

export const genMeshScene = async (scene: QuoteScene) => {
  const res = (await axios.post(checkGenMeshScene, { id: scene.id })).data;
  if (res?.buildObjStatus === 2) {
    ElMessage.error("Mesh场景正在计算中，请耐心等待。");
  } else if (
    res?.buildObjStatus !== 1 ||
    (await confirm("重新生成obj，Mesh场景将覆盖现有信息，确定要重新生成吗？"))
  ) {
    await axios.post(genMeshSceneByCloud, { id: scene.id });
    ElMessage.success("生成obj将同时生成Mesh场景，需要较长时间，请耐心等待；");
  }
};
