const Base64 = require("js-base64").Base64;
//复制到剪贴板
const copyContent = (d,call,env = 'test') => {
    const url = env === 'test' ? `http://web-share-page-test.arioncc.cn/${Base64.encode(JSON.stringify(d))}` : `http://web-share-page.arioncc.cn/${Base64.encode(JSON.stringify(d))}`;
    let input = document.createElement('input')
    input.setAttribute('readonly','readonly')
    input.setAttribute('value', url)
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    call()
}

//下载，已知文件的静态资源地址
const newDownLoad = async (src) => {
    const res = await fetch(src);
    const blob = await res.blob();
    const blobUrl = URL.createObjectURL(blob);
    let link = document.createElement("a");
    link.href = blobUrl;
    link.target = "_blank";
    let index = src.lastIndexOf("/");
    let name = index == -1 ? src : src.substring(
    index + 1,
    src.length
    );
    link.setAttribute("download", name);
    link.style.display = "none";
    link.click();
}
const getNameText = (d) => {
    if(!d) return '';
    if(d.lastIndexOf('.') != -1){
      return d.slice(0,d.lastIndexOf('.'))
    } else {
      return d
    }
  }
const getNameType = (d) => {
  if(!d) return '';
  if(d.lastIndexOf('.') != -1){
    console.log(d.substring(d.lastIndexOf('.') + 1,d.length));
    return d.substring(d.lastIndexOf('.') + 1,d.length)
  } else {
    return ''
  }
}
  //查看时获得下拉选中的label
  const getSelectLabel = (v,arr,key,name) => {
    if(!v) return '';
    let label = '';
    arr.forEach(item => {
      if(item[key ? key : 'value'] == v) label = item[name ? name : 'label']
    })
    return label
  }

  const httpproxyMethod = (value) => {
    if (!value) return '';
    return `${window.location.origin}/api/file-path/proxy?url=${value}`;
  }

  const parseHttpMethod = (val) => {
    if(!val) return '';
    // const urlPattern = /(http?:\/\/|www\.)[a-zA-Z_0-9\-@]+(\.\w[a-zA-Z_0-9\-:]+)+(\/[\(\)~#&\-=?\+\%/\.\w]+)?/g;
    const urlPattern = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    val = val.replace(srcReg, function(match,capture){
      return `src="${window.location.origin}/api/file-path/proxy?url=${capture}"`;
    })
    return val
  }
  const getHttpStr = (val) => {
    if(!val) return '';
    const urlPattern = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    val = val.replace(srcReg, function(match,capture){
      let index = capture.indexOf('url')
      if(~index) {
        capture = capture.slice(index + 4)
      }
      return `src="${capture}"`;
    })
    return val
  }
  
export {
    copyContent,
    newDownLoad,
    getNameText,
    getSelectLabel,
    getNameType,
    httpproxyMethod,
    parseHttpMethod,
    getHttpStr
}