import {
  axios,
  caseInfo,
  caseSceneList,
  getCasePsw,
  repCaseScenes,
  setCasePsw,
  syncInfo,
  updateCaseFile,
  caseInquestInfo,
  newFileupload,
  getDictFileList,
  delDictFileList,
  getByTree,
  getListFileList,
  addByMediaLibrary,
  addByMediaLibrarys,
  updateFileType,
  saveOrUpdate,
  criminalInfo,
  getSceneList,
  newCaseInfo,
  casesaveOrUpdate,
  saveApiOrUpdate,
  uploadImagesAndSave,
  caseApiDel,
  caseApiList,
  caseApiUpdateSort,
  saveCaseImgTag,
  getCaseImgTag,
  ffmpegMergeImage,
  caseInquestInfoOld,
  caseInquestOpt,
  caseInquestExport,
  sceneListHasAi,
  caseaddOrUpdate,
  isdyrh,
  getTips,
  getTipsName,
  getUrlByKeyList,
  mediaList,
  dictFiledel,
  del,
  addOrUpdate,
  fileaddOrUpdate,
  uploadUrl,
} from "@/request";
import { router } from "@/router";
import { ModelScene, QuoteScene, Scene, SceneType } from "./scene";
import { CaseFile } from "./caseFile";
import { ref } from "vue";
import { getUrlData } from "@/store/user";

export type Case = {
  caseId: number;
  caseTitle: string;
  createTime: string;
  name: string;
  tbStatus: string;
  userName: number;
};
let isloadList = false;
export const treeList = ref([]);
export const lang = ref(localStorage.getItem("lang") || "zh");
export const sceneList = ref([]);
export const caseInfoData = ref({
  caseTitle: '',
});

export const setCaseSharePWD = (params: { caseId: number; randCode: string }) =>
  axios.post(setCasePsw, params);

export const setCaseaddOrUpdate = (params) =>
  axios.post(caseaddOrUpdate, params);

export const setFileaddOrUpdate = (params) =>
  axios.post(fileaddOrUpdate, params);


export const getCaseSharePWD = async (params: { caseId: number }) =>
  (await axios.get<string>(getCasePsw, { params })).data;

export const getByKeyList = async (params: { caseId: number }) =>
  (await axios.get<string>(getUrlByKeyList, { params })).data;

export const getdictFiledel = async (params) =>
  (await axios.post<string>(dictFiledel, params)).data;

export const getaddOrUpdate = async (params) =>
  (await axios.post<string>(addOrUpdate, params)).data;


export const getfzdel = async (params) =>
  (await axios.post<string>(del, params)).data;


export const getmediaList = async (params) =>
  (await axios.post<string>(mediaList, params)).data;

export const addByMediaLiBrary = async (params) =>{
  const newUrl = params.uploadIds?.length ? addByMediaLibrarys : addByMediaLibrary
  return (await axios.post<string>(newUrl, params)).data;
}

export const AddsaveOrUpdate = async (params) =>
  (await axios.post<string>(saveOrUpdate, params)).data;

export const getcaseInDate = async (params) =>
  (await axios.get<string>(criminalInfo, {params})).data;
  // (await axios.get<string>(info, { params:params })).data;

export const getSceneListData = async (params) =>
  (await axios.get<string>(getSceneList, { params })).data;
  // (await axios.get<string>(info, { params:params })).data;

export const getCaseInfo = async (caseId) => {
  caseInfoData.value =  (await axios.get<Case>(caseInfo, { params: { caseId } })).data
  return caseInfoData.value;
}
  

export const getCaseInquestInfo = async (caseId: number) =>
  (await axios.get(newCaseInfo, { params: { caseId } })).data;

export const casesaveOrUpDate = async (params) =>
  (await axios.post<string>(casesaveOrUpdate, params)).data;


export const updateCaseInfo = async (caseFile: CaseFile) =>
  await axios.post(updateCaseFile, {
    filesId: caseFile.filesId,
    filesTitle: caseFile.filesTitle,
  });

export const getCaseSceneList = async (caseId: number): Promise<Scene[]> => {
  let mylist = (await axios.get(caseSceneList, { params: { caseId } })).data;
  sceneList.value = mylist && mylist.filter(item => item.type != 3);
  return sceneList.value;
};

export const getFilepageList = async (params): Promise<Scene[]> => {
  return (await axios.post(getListFileList, params)).data;
};
export const getupdateFileType = async (params): Promise<Scene[]> => {
  return (await axios.post(updateFileType, params)).data;
};

export const getDictFileLists = async (type: number): Promise<Scene[]> => {
  return (await axios.get(getDictFileList, { params: { type: type } })).data;
};
export const delDictFileLists = async (id: number): Promise<Scene[]> => {
  return (await axios.post(delDictFileList, { id })).data;
};


export const getcaseLists = async (caseId: number): Promise<Scene[]> => {
  return (await axios.get(isdyrh, { params: { caseId } })).data;
};

export const updateByTreeFileLists = async (caseId = router.currentRoute.value?.params?.caseId): Promise<Scene[]> => {
  let list = (await axios.get(getByTree, { params: { caseId:caseId } })).data
  // function getTreeList(lists: any[]) {
  //   return lists.map(item => {
  //     return {
  //       ...item,
  //       caseFilesList: item.caseFilesList && item.caseFilesList.reverse(),
  //       childrenList: item.childrenList && getTreeList(item.childrenList)
  //     }
  //   })
  // }
  treeList.value = list;
  return list;
};
export const updateSelectByTreeFileLists = async (): Promise<Scene[]> => {
  function getTreeList(list: any[]) {
    return list.map(item => {
      if (item.childrenList) {
        return {
          value: item.filesTypeId,
          label: item.filesTypeName,
          children: getTreeList(item.childrenList)
        };
      }
      return {
        value: item.filesTypeId,
        label: item.filesTypeName,
      }
    })
  }
  return getTreeList((await axios.get(getByTree, { params: { caseId: '' } })).data)
};
export const caseImgList = (caseId: number, orderBy: string | null) =>
  axios.post(caseApiList, { orderBy: orderBy || "", caseId });

export const caseDel = (id: number) => axios.post(caseApiDel, { id });

export const saveOrUpDate = (params: CaseImg) =>
  axios.post(saveApiOrUpdate, { ...params });

export const caseUpdateSort = (list: [CaseImg]) =>
  axios.post(caseApiUpdateSort, { paramList: list });

export const saveOrAndSave = (params) =>
  axios.post(uploadImagesAndSave, { ...params });

export const uploadFile = async (params) => {
  return (await axios.post<string>(uploadUrl, params)).data;
};

export const getByTreeFileLists = async () => {
  return treeList.value
};

export const getCaseInquestInfoOld = (caseId: number) =>
  axios.get(caseInquestInfoOld, { params: { inquestFileId: caseId } });

export const saveCaseInquestInfo = (params) =>
  axios.post(caseInquestOpt, params
  );

export const exportCaseInquestInfo = (caseId: number) =>
  axios.get(caseInquestExport, {
    params: { inquestFileId: caseId, ingoreRes: true },
    responseType: "blob",
  });

export const getSyncSceneInfo = async (caseId: number) => {
  return (await axios.post<string>(syncInfo, { caseId })).data;
};

export const getSceneKey = (scene: Scene) =>
  scene.type === SceneType.SWMX
    ? (scene as ModelScene).modelId
    : (scene as QuoteScene).num;

export type CaseScenes = { type: SceneType; numList: (string | number)[] }[];
export const getCaseScenes = (scenes: Scene[]) => {
  const typeIdents = [
    { type: SceneType.SWKJ, numList: [] },
    { type: SceneType.SWKK, numList: [] },
    { type: SceneType.SWMX, numList: [] },
    { type: SceneType.SWSS, numList: [] },
    { type: SceneType.SWSSMX, numList: [] },
    { type: SceneType.SWYDSS, numList: [] },
    { type: SceneType.SWYDMX, numList: [] },
  ] as CaseScenes;

  for (const scene of scenes) {
    const typeIdent = typeIdents.find((ident) => ident.type === scene.type)!;
    typeIdent.numList.push(getSceneKey(scene));
  }
  return typeIdents;
};

export const replaceCaseScenes = (caseId: number, caseScenes: CaseScenes) =>
  axios.post(repCaseScenes, { sceneNumParam: caseScenes, caseId });

export const uploadNewFile = (data) => {
  console.log('uploadNewFile',data);
  return axios<undefined>({
    method: "POST",
    url: newFileupload,
    data: data,
    // onUploadProgress(event: any) {
    //   data.onProgress(Math.round((event.loaded / event.total) * 100) || 0);
    // },
  });
}

export type CaseImg = {
  id: number;
  caseId: number;
  imgInfo: string | null;
  imgUrl: string | null;
  status: number | null;
  sort: number | null;
};



export const saveCaseImgTagData = (params: any) =>
  axios.post(saveCaseImgTag, { ...params });

export const getCaseImgTagData = (caseId: number) =>
  axios.get(getCaseImgTag, { params: { caseId } });

export const getSceneListHasAi = (caseId: number) =>
  axios.get(sceneListHasAi, { params: { caseId } });

export const getTipsList = (key) =>
  axios.get(getTips, { params: { 
    basic: 'y',
    key,
    location: '113.05,22.61',
   } });

export const getTipsNames = (name) =>
  axios.get(getTipsName, { params: { name } });

export const submitMergePhotos = (data) => axios.post(ffmpegMergeImage, { ...data })

export const getCaseInfoData = () => caseInfoData.value
export const getCaseSceneListData = (caseId) => {
  if(sceneList.value && sceneList.value.length == 0 && !isloadList) return getCaseSceneList(caseId).then(res => {
    isloadList = true
    sceneList.value = res
    return sceneList.value
  })
  return sceneList.value
}

export const getSceneListTree = (list = sceneList.value) => {
  let myData = {
    0: [],//点云
    1: [],//mesh
  };
  list && list.map((item) => {
    if(item.type == 2 || item.type == 5 ) {
      myData[0].push(item.num)
    }else{
      myData[1].push(item.num)
    }
  });
  return [{numList:myData[0],type: 0}, {numList:myData[1],type: 1}]
}

export const getUrlSrc = (item, caseId) => {
  let param = {
    root:'',
    ossRoot:'',
    serviceUrl:'',
    laserRoot:'',
    swssUrl:'',
    swkkUrl:'',
    swssmxUrl: '',
    fuse: '',
  }
  let params = getUrlData();
  let langKey = params.lang || "zh";
  const ip = params.ip ? params.ip + ":" : "";
  param.root = `${ip}${params.laserServicePort}`;
  param.ossRoot = `${ip}${params.laserServicePort}${params.static}`;
  param.serviceUrl = `${ip}${params.servicePort}/fusion`;
  param.laserRoot = param.root;

  param.swssUrl = `${params.swssUrl}?lang=${langKey}&serve_link=${param.laserRoot}&basePath=${param.laserRoot}&m=${item.num}`;
  param.swssmxUrl = `${params.swssUrl}?lang=${langKey}&serve_link=${param.laserRoot}&basePath=${param.laserRoot}&m=${item.num}`;
  param.swkkUrl = `${params.swkkUrl}?lang=${langKey}&app_server=${params.ip}${params.swkkPort}&m=${item.num}`;
  param.fuse = `${params.fuse}?caseId=${caseId}&single&ip=${params.ip}&swkkPort=${params.swkkPort}&swssUrl=${params.swssUrl}&swkkUrl=${params.swkkUrl}&laserServicePort=${params.laserServicePort}&servicePort=${params.servicePort}&lang=${langKey}&app_server=${ip}${params.swkkPort}&testMap&static=&m=${item.num}`;
  let SceneType = {
    0: params.swkkUrl,//`/spg.html?m=${item.num}`,
    1: params.swkkUrl,//`/spg.html?m=${item.num}`,
    2: param.swssmxUrl,//`/mega/index.html?m=${item.num}`,
    3: params.swkkUrl,//`/swss/index.html?m=${item.num}`,
    4: params.swkkUrl,//`/spg.html?m=${item.num}`,
    5: param.swssmxUrl,//`/mega/index.html?m=${item.num}`,
    6: params.swkkUrl,//`/spg.html?m=${item.num}`,
    7: params.swkkUrl,//`/spg.html?m=${item.num}`,
    99: param.fuse + '#/show/summary',//多元融合查看页面`/code/index.html?caseId=${caseId}&single#/show`,
    100: param.fuse + '#/fuseEdit/merge',//多元融合编辑页面`/code/index.html?caseId=${caseId}&single#/show`,
    101: param.fuse +`title=${item.fileName}&type=${item.fileFormat}&fileUrl=${item.fileUrl}`+ '#/sign-model',//多元融合模型查看页面`/code/index.html?caseId=${caseId}&single#/show`,
    102: param.root,//资源访问链接,
  };
  return SceneType[item.type];
}
