import axios from "axios";
// import Api from '../../../../commons/utils/api_manager'
// import CloudEStore from '../stores/CloudEStore'
// import { Actions, Constants } from '../../../../commons/utils/constants'
// import MessageUtil from '../../../../commons/utils/MessageUtil'
// import ApiUtils from '../../../../commons/utils/ApiUtils'
import { APIOPTION, urlToken } from "./raysyncApi";
// import UserStore from '../../../../console/common/stores/UserStore'
import { ApiUtils } from "./utils";
import Base64 from "crypto-js/enc-base64";
import { getUrlThroughParams } from "@/utils/util";
import Utf8 from "crypto-js/enc-utf8";
import { getLoaclStorageOfKey } from "./utils";

let headers: any = {
  "Content-Type": "application/json",
};

type IGetDatasetItemsListParams = {
  type?: string;
  projectId: string;
  token: string;
  filetoken: string;
  path: string; // 数据集路径
  name: string; // 数据集名称
  page: number; // 
  size: number; // 
  query?: string; // 搜索的关键词
  index?: string; // 选择的属性
  sort?: string; // 排序
}

type IGetDatasetSizeParams = {
  type?: string; // 产品id
  projectId: string;
  token: string;
  filetoken: string;
  path: string; // 数据集路径
  name: string; // 数据集名称
}

type ISaveDatasetParams = {
  type?: string;
  projectId: string;
  token: string;
  filetoken: string;
  path: string; // 数据集路径
  name: string; // 数据集名称
  dpath: string; // 目标路径
  dname: string; // 目标数据集名称
  id: string; // 每个分子的index,逗号分隔
  baseurl?: string; // 需要回调后台插入数据集元数据的url，比如http://47.57.4.97/)
}

type IDownloadDatasetItemsParams = {
  type?: string;
  projectId: string;
  token: string;
  filetoken: string;
  path: string; // 数据集路径
  name: string; // 数据集名称
  id: string; // 每个分子的index,逗号分隔
  downloadType: string; // 下载格式”，可选 SMILES(.smi)、SD(.sdf)、PDB(.pdb)、MOL(.mol)、MOL2(.mol2)
}

class CloudEController {
  // 新建文件夹
  static JobFileNewFolder(url: any, filetoken: string, projectId: string) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      url = url += urlToken(filetoken, projectId);
      headers["Content-Type"] = "multipart/form-data";
      return axios.post(
        APIOPTION() + "/createdir" + url,
        {},
        {
          headers: headers,
        }
      );
    }
  }
  //文件 删除
  static JobOutFileDel(urls: any, filetoken: string, projectId: string) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      headers["delfilepath"] = Base64.stringify(Utf8.parse(urls));
      let url = "";
      if (getLoaclStorageOfKey("userinfo")) {
        url += urlToken(filetoken, projectId);
      }
      return axios.get(APIOPTION() + "/delete/" + url, {
        headers: headers,
      });
      // .then(function (response) {
      //   console.log(response);
      // })
      // .catch(function (error) {
      //   console.log(error);
      // });
    }
  }
  // 文件树
  static JobOutFileDirtree(
    url: any,
    filetoken: string,
    projectId: string,
    showHide = false,
    items?: any
  ) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      if (getLoaclStorageOfKey("userinfo")) {
        url += urlToken(filetoken, projectId);
      }
      return axios.get(
        APIOPTION() + "/dirtree" + url + "&showhidden=" + showHide,
        {
          headers: headers,
        }
      );
    }
  }
  // 文件列表
  static JobOutFileList(
    url: any,
    filetoken: string,
    projectId: string,
    showHide = false,
    items?: any
  ) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      // headers['parentName'] = ''
      if (getLoaclStorageOfKey("userinfo")) {
        url += urlToken(filetoken, projectId);
      }
      return axios.get(
        APIOPTION() + "/list" + url + "&showhidden=" + showHide,
        {
          headers: headers,
        }
      );
    }
  }
  // 全局搜索 文件名
  static JobSearchFileList(
    url: any,
    base: any,
    filetoken: string,
    projectId: string,
    showHide = false
  ) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      if (getLoaclStorageOfKey("userinfo")) {
        url = urlToken(filetoken, projectId) + "&q=" + url;
      }
      return axios.get(
        APIOPTION() + "/search" + base + url + "&showhidden=" + showHide,
        {
          headers: headers,
        }
      );
    }
  }

  // 文件移动
  // static JobOutFileListMove(url: any, filetoken: string, projectId: string) {
  //   if (ApiUtils.getAuthorizationHeaders(headers)) {
  //     headers["Cache-Control"] = "no-cache";
  //     if (getLoaclStorageOfKey("userinfo")) {
  //       url += urlToken(filetoken, projectId);
  //     }
  //     return axios.get(APIOPTION() + "/download" + url, {
  //       headers: headers,
  //     });
  //   }
  // }
  // 文件移动
  static JobFileMove(
    url: any,
    original_filepath: any,
    value: any,
    filetoken: string,
    projectId: string
  ) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      url = url += urlToken(filetoken, projectId);
      headers["Content-Type"] = "multipart/form-data";
      headers["originalfilepath"] = encodeURIComponent(original_filepath);
      let param = new FormData();
      param.append("", value);
      return axios.post(APIOPTION() + "/rename" + url, param, {
        headers: headers,
      });
    }
  }

  // 文件批量移动
  static JobFileBatchMove(
    url: any,
    original_filepath: Array<string>,
    value: any,
    filetoken: string,
    projectId: string
  ) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      url = url + urlToken(filetoken, projectId) + "&batch=true";
      headers["Content-Type"] = "multipart/form-data";
      headers["originalfilepath"] = Base64.stringify(
        Utf8.parse(original_filepath.join(" "))
      );
      let param = new FormData();
      param.append("", value);
      return axios.post(APIOPTION() + "/rename" + url, param, {
        headers: headers,
      });
    }
  }

  // 文件下载
  static JobFileDownload(url: any, filetoken: string, projectId: string) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      url = url + urlToken(filetoken, projectId);
      headers["Content-Type"] = "multipart/form-data";
      const div = document.createElement("div");
      const elink: any = document.createElement("a");
      elink.style.display = "none";
      elink.href = APIOPTION() + "/download" + url;
      document.body.appendChild(div);
      div.appendChild(elink);
      div.addEventListener("click", (event) => {
        event.stopPropagation();
      });
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      div.removeChild(elink);
      document.body.removeChild(div);
    }
  }

  // 获取文件文本内容（字符串）
  static JobFileDownloadText(url: any, filetoken: string, projectId: string) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      url = url + urlToken(filetoken, projectId);
      headers["Cache-Control"] = "no-cache";
      headers["Content-Type"] = "multipart/form-data";
      return axios.get(
        APIOPTION() + "/download" + url + "&showhidden=false",
        {
          headers: headers,
        }
      );
    }
  }

  // 获取dataset条数
  static GetDatasetSize(params: IGetDatasetSizeParams) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      let url = getUrlThroughParams(params, ['filetoken','path','token'], '?')
      return axios.get(
        `${APIOPTION()}:5003/size${url}`,
        {
          headers: headers,
        }
      );
    }
  }

  // 获取分子列表
  static GetDatasetItemsList(params: IGetDatasetItemsListParams) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      let url = getUrlThroughParams(params, ['filetoken','path','token'], '?')
      return axios.get(
        `${APIOPTION()}:5003/find/dataset${url}`,
        {
          headers: headers,
        }
      );
    }
  }

  // 分子另存为
  static SaveDataset(params: ISaveDatasetParams) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      let url = getUrlThroughParams(params, ['filetoken','path','token','dpath'], '?')
      return axios.post(`${APIOPTION()}:5003/save${url}`,{}, {
        headers: headers,
      });
    }
  }

  // 数据集分子下载
  static DownloadDatasetItems(params: IDownloadDatasetItemsParams) {
    if (ApiUtils.getAuthorizationHeaders(headers)) {
      headers["Cache-Control"] = "no-cache";
      let url = getUrlThroughParams(params, ['filetoken','path','token'], '?')
      return axios.get(
        `${APIOPTION()}:5003/download${url}`,
        {
          headers: headers,
        }
      );
    }
  }

  // 生成文件并下载
  static FunDownload(content: string, filename: string) {
    // 创建隐藏的可下载链接
    let eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    let blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
  }
}
export default CloudEController;
