import {
  axios,
  caseInfo,
  newupload,
  getMapConfig,
  caseSceneList,
  caseNewList,
  caseFusionList,
  caseFusionDel,
  getCasePsw,
  repCaseScenes,
  setCasePsw,
  addFusionIds,
  uploadSceneCheck,
  uploadSceneOrig,
  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,
  getByImage,
  caseOverviewAdd,
  caseTabulationAdd,
  getByCaseId,
  getFloor,
  addUserOrUpdate,
  caseTabulationList,
  caseOverviewList,
  caseOverviewExport,
  casePhotoRollList,
  getAllPhoto,
  casePhotoRollUpdate,
  casePhotoRolldel,
} from "@/request";
import { router } from "@/router";
import { ModelScene, QuoteScene, Scene, SceneType } from "./scene";
import { user } from "@/store/user";
import { CaseFile } from "./caseFile";
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { RouteName } from "@/router/config";

export type Case = {
  caseId: number;
  caseTitle: string;
  createTime: string;
  name: string;
  tbStatus: string;
  userName: number;
};
let isloadList = false;
export const treeList = ref([]);
export const show = ref(false);
export const Extract = ref(false);
export const sceneList = ref([]);
export const caseInfoData = ref({
  caseTitle: '',
});
export const sceneType = ref('edit');

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

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

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

export const getFloorList = async (caseId) =>
  (await axios.get<string>(getFloor+caseId, {})).data;

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

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

export const addUserOrUpDate = async (params) =>{
  return (await axios.post<string>(addUserOrUpdate, 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 getcaseMap = async (params) =>
    (await axios.get<string>(getMapConfig, {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
  if(!caseInfoData.value || !caseInfoData.value.viewAuth){
      return ElMessageBox.alert("您没有访问权限", "提示", {
        confirmButtonText: "我知道了",
        type: "warning",
        showClose: false
      }).then(async () => {
        router.replace({ name: RouteName.login});
        // window.open(window.location.origin + "/admin/#/statistics/scene");
      });
    ;
  }
  if(!caseInfoData.value.editAuth && !show.value){
    show.value = true;
    return ElMessageBox.alert("您没有编辑权限", "提示", {
      confirmButtonText: "去查看",
      type: "warning",
      showClose: false
    }).then(async () => {
      window.open(window.location.origin + "/mix3d/?show=true#/abstract/" + caseId)
      // router.replace({ name: RouteName.login});
      // window.open(window.location.origin + "/admin/#/statistics/scene");
    });
  }
  if(caseInfoData.value?.caseTitle){
    document.title = caseInfoData.value.caseTitle
  }
  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 overviewAdd = async (params) =>
  (await axios.post<string>(caseOverviewAdd, params)).data;

export const TabulationAdd = async (params) =>
  (await axios.post<string>(caseTabulationAdd, params)).data;
export const getcaseByCaseId = async (caseId) =>
  (await axios.get(getByCaseId, { params: { caseId } })).data;
export const caseOverview = async (caseId) =>
  (await axios.get('/fusion/caseOverview/getByCaseId', { params: { caseId } })).data;

export const caseOverviewDel = async ({tabulationId, overviewId, type}) =>
  (await axios.post(type=='方位图'?'/fusion/caseTabulation/del':'/fusion/caseOverview/del', { tabulationId, overviewId } )).data;


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

export const getCaseSceneList = async (caseId: number, refresh = false): Promise<Scene[]> => {
  if (!refresh && sceneList.value.length) {
      return sceneList.value;
  }
  let mylist = (await axios.get(caseSceneList, { params: { caseId, } })).data;
  sceneList.value = mylist.filter(item => item.type != 3);
  return sceneList.value;
};
export const getCaseList = async (params): Promise<Scene[]> => {
  return (await axios.get(caseNewList, {params})).data;
};
export const getCaseFusionList = async (params): Promise<Scene[]> => {
  return (await axios.post(caseFusionList, params)).data;
};
export const getCaseFusionImgList = async (params): Promise<Scene[]> => {
  return (await axios.post(params.type?caseTabulationList:caseOverviewList, params)).data;
};
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 getCasePhotoRollList = async (caseId = router.currentRoute.value?.params?.caseId): Promise<Scene[]> => {
  return (await axios.get(casePhotoRollList, { params: { caseId } })).data;
};
export const getAllPhotoList = async (filesTypeId): Promise<Scene[]> => {
  return (await axios.get(getAllPhoto, { params: { caseId: router.currentRoute.value?.params?.caseId, filesTypeId } })).data;
};
export const casePhotoUpdate = (params) =>
  axios.post(casePhotoRollUpdate, params);
export const casePhotodel = (params) => {
  console.log(params)
  return  axios.post(casePhotoRolldel, params);
}
  

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 casefusionDel = (fusionId: number) => axios.post(caseFusionDel, { fusionId });


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 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) => axios<undefined>({
    method: "POST",
    url: newFileupload,
    data: data,
  });
export const caseExportImg = (data) => axios<undefined>({
    method: "POST",
    url: caseOverviewExport,
    data: data,
  });

export const uploadFiles = (data) => axios<undefined>({
  method: "POST",
  url: newupload,
  data: data,
});

export const SceneCheck = (data) => axios<undefined>({
  method: "POST",
  url: uploadSceneCheck,
  data: data,
});

export const SceneOrig = (data) => axios<undefined>({
  method: "POST",
  url: uploadSceneOrig,
  data: data,
});


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.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.map((item) => {
    if(item.sceneType == 2 || item.sceneType == 5 || 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 token = user.value.token
  if(!item.viewAuth){
    return ''
  }
  let SceneType = {
    0: `/spg.html?m=${item.num}`,
    1: `/spg.html?m=${item.num}`,
    2: `/mega/index.html?m=${item.num}`,
    3: `/swss/index.html?m=${item.num}`,
    4: `/spg.html?m=${item.num}`,
    // 5: `/spg.html?m=${item.num}`,
    // 5: `index.html?caseId=${caseId}&modelId=${item.num}#sign-model`,
    5: `/mega/index.html?m=${item.num}`,
    6: `/spg.html?m=${item.num}`,
    7: `/spg.html?m=${item.num}`,
    99: `/code/index.html?caseId=${caseId}&single#/show`,
  };
  let SceneEditType = {
    0: `/spg.html?m=${item.num}&token=${token}&pure=1`,
    1: `/spg.html?m=${item.num}&token=${token}&pure=1`,
    2: `/mega/index.html?m=${item.num}`,
    3: `/swss/index.html?m=${item.num}`,
    4: `/spg.html?m=${item.num}&token=${token}&pure=1`,
    // 5: `/spg.html?m=${item.num}`,
    // 5: `index.html?caseId=${caseId}&modelId=${item.num}#sign-model`,
    5: `/mega/index.html?m=${item.num}`,
    6: `/spg.html?m=${item.num}&token=${token}&pure=1`,
    7: `/spg.html?m=${item.num}&token=${token}&pure=1`,
    99: `/code/index.html?caseId=${item.fusionId || caseId}&single#/show`,
    100: `/code/index.html?caseId=${item.fusionId || caseId}&pure=1#/show`,
  };
  
  console.log(sceneType.value, 'sceneType.value')
  return sceneType.value == 'view' ? SceneEditType[item.type]: SceneEditType[item.type];
}
