
export const clearToken = () => {
  localStorage.setItem('JWT-TOKEN', '');
};

export const storeToken = token => {
  localStorage.setItem('JWT-TOKEN', token);
};

export const getToken = () => {
  return localStorage.getItem('JWT-TOKEN');
};

/**
 *
 * @param {String} url
 *
 * create a DOM Element
 * <a href="url" download/>
 */
export const downloadFile = (url, fileName, encode = true) => {
  
  const downloadLink = document.createElement('a');
  const body = document.documentElement || document.body;
  body.appendChild(downloadLink);
  let tempUrl = url;
  if (encode) {
    let urlArr = tempUrl.split('/');
    urlArr[urlArr.length - 1] = encodeURIComponent(urlArr[urlArr.length - 1]);
    tempUrl = urlArr.join('/');
  }
  downloadLink.href = tempUrl;
  downloadLink.download = fileName;

  downloadLink.click();
  body.removeChild(downloadLink);
  // }
};
window.downloadFile = downloadFile;

export function IsImageFile(fileName) {
  return (
    fileName.lastIndexOf('.jpg') !== -1 ||
    fileName.lastIndexOf('.png') !== -1 ||
    fileName.lastIndexOf('.JPG') !== -1 ||
    fileName.lastIndexOf('.PNG') !== -1
  );
}

export function IsVedio(fileName) {
  return fileName.lastIndexOf('.mp4') !== -1 || fileName.lastIndexOf('.avi') !== -1;
}

export function GetTokenFromUrl() {
  const params = GetRequest(window.location.href);
  if (!params['JWT-TOKEN'] || params['JWT-TOKEN'] == 'undefined') return '';
  return params['JWT-TOKEN'];
}

/**
 * [获取URL中的参数名及参数值的集合]
 * 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
 * @param {[string]} urlStr [当该参数不为空的时候，则解析该url中的参数集合]
 * @return {[string]}       [参数集合]
 */
function GetRequest(urlStr) {
  if (typeof urlStr === 'undefined') {
    var url = decodeURI(location.search); //获取url中"?"符后的字符串
  } else {
    var url = '?' + urlStr.split('?')[1];
  }
  let theRequest = new Object();
  if (url.indexOf('?') != -1) {
    let str = url.substr(1);
    let strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1]);
    }
  }
  return theRequest;
}

export function GetFileType(url) {
  if (!url) return;
  if (url.match('pid-list')) {
    return 18;
  } else if (url.match('layout-plan')) {
    return 19;
  }
}

export function getUser(params) {
  let arr = [];
  if (!params) {
    return;
  } else {
    return (arr = params
      .map(item => {
        return item.Operator?.CName;
      })
      .join(','));
  }
}

export const UnityAction = {
  event: {},
  on(type, callback) {
    if (!UnityAction.event[type]) {
      UnityAction.event[type] = [];
    }
    UnityAction.event[type].push(callback);
  },
  off(type, callback) {
    if (callback) {
      let index = UnityAction.event[type].indexOf(callback);
      if (index == -1) return;
      UnityAction.event[type].splice(index, 1);
    } else {
      UnityAction.event[type] = [];
    }
    window[type] = null;
  },
  emit(type, e) {
    if (!UnityAction.event[type]) return;
    console.log('emit====== type:', type, '====== event:', e);
    UnityAction.event[type].forEach(item => {
      item && item(e);
    });
  },
  addEventListener(type, callback) {
    if (window.vuplex) {
      UnityAction.on(type, callback);
    } else {
      window[type] = callback;
    }
  },
  sendMsg(type, message) {
    console.log(`type====${type}`);
    console.log('message====', message);
    if (window.vuplex) {
      window.vuplex.postMessage({ type, message });
    } else if (window[type]) {
      window[type](message);
    }
  },
};
if (window.vuplex) {
  window.vuplex.addEventListener('message', e => {
    console.log('============================getMessageForUnity============================');
    const data = JSON.parse(e.data);
    console.log(data);
    UnityAction.emit(data.type, data.message);
  });
}

export function getGlobalData(key) {
  let data;
  try {
    data = JSON.parse(localStorage.GLOBAL_DATA);
  } catch (error) {
    data = {};
  }

  return key ? data[key] : data;
}

export function setGlobalData(key, value) {
  let data;
  if (!key) return;
  try {
    data = JSON.parse(localStorage.GLOBAL_DATA);
  } catch (error) {
    data = {};
  }
  data[key] = value;
  localStorage.GLOBAL_DATA = JSON.stringify(data);
}

// 根据token缓存数据
export function saveData(key, data) {
  let token = GetTokenFromUrl() || getToken();
  let cache = JSON.stringify({
    data,
    token,
  });
  localStorage.setItem(key, cache);
}

// 根据token获取缓存数据
export function getData(key) {
  let token = GetTokenFromUrl() || getToken();
  let oldData = {};
  try {
    oldData = JSON.parse(localStorage.getItem(key)) || {};
  } catch (error) {}
  // token不一致时认为数据失效，返回null
  if (oldData.token != token) return null;
  return oldData.data;
}

// 清空缓存
export function clearData(key) {
  localStorage.setItem(key, '');
}
