import { DownloadService } from 'pc-component-v3';


export default {
  pageSize: 20,


  // 异常处理
  processException: function (XMLHttpRequest, textStatus, errorThrown) {
    var _self = this;
    console.log(XMLHttpRequest);
    if (XMLHttpRequest.status == 400) {
      // 400 Bad Request
      Notify.error('400', XMLHttpRequest.responseText, true);
    } else if (XMLHttpRequest.status == 401) {
      var currentUrl = window.location;
      var href = window.location.href;
      // 当前未处于登陆的界面
      // 系统未登录
      if (href.indexOf('login') < 0 && href.indexOf('redirectUrl=') < 0) {
        // 处理钉钉免登陆
        const clientId = this.getRouteParam('clientId');
        const appName = this.getRouteParam('appName');
        const corpId = this.getRouteParam('corpId');

        let newUrl;
        if (clientId != null && clientId.length > 0 && appName != null && appName.length > 0 && corpId != null && corpId.length > 0) {
          newUrl = _self.getRedirectUrl('#/login?clientId=' + clientId + '&appName=' + appName + '&corpId=' + corpId + '&redirectUrl=' + encodeURIComponent(currentUrl));
        } else {
          newUrl = _self.getRedirectUrl('#/login?redirectUrl=' + encodeURIComponent(currentUrl));
        }
        window.location = newUrl;
      }
    } else if (XMLHttpRequest.status == 500) {
      // 500 Internal Server Error
      Notify.error('500', XMLHttpRequest.responseText, true);
      if (XMLHttpRequest.responseText.indexOf('登录超时') > 0) {
        // 如果异常信息包含“登录超时”，则2秒后跳转到登录页面
        setTimeout(function () {
          window.location = _self.getRedirectUrl('#/login');
        }, 2 * 1000);
      }
    } else {
      Notify.error('服务器异常', XMLHttpRequest.responseText, true);
    }
  },


  /**
   * 获取主机地址
   */
  getRootPath: function () {
    var protocol = window.location.protocol;
    // console.log('protocol:' + protocol);
    var host = window.location.host;
    // console.log('host:' + host);
    var localhostPaht = protocol + '//' + host;
    // console.log('localhostPaht:' + localhostPaht);
    return localhostPaht;
  },

  getHostPageBaseURL: function () {
    if (typeof REMOTE_DEV_PORT !== 'undefined' && REMOTE_DEV_PORT != null) {
      return this.getRootPath() + '/proxy/' + REMOTE_DEV_PORT;
    } else {
      return this.getRootPath();
    }
  },


  // 获取API的地址
  getApiURL: function (apiName) {
    if (apiName.startsWith('/')) {
      return this.getHostPageBaseURL() + '/api' + apiName;
    } else {
      return this.getHostPageBaseURL() + '/api/' + apiName;
    }
  },

  /**
   * 获取API的地址 直接拼接
   * @param {*} apiName 
   * @returns 
   */
  getApiUrl2: function (apiName) {
    if (apiName.startsWith('/')) {
      return this.getHostPageBaseURL() + apiName;
    } else {
      return this.getHostPageBaseURL() + '/' + apiName;
    }
  },


  // 获取图片路径
  getImageUrl: function (imageName) {
    if (imageName == null || imageName == '') {
      return this.getHostPageBaseURL() + 'notFound.png';
    } else {
      return this.getHostPageBaseURL() + imageName;
    }
  },

  // 获取图片路径
  getImageSrc: function (className, imageName) {
    if (imageName == null) {
      return null;
    }
    return this.getHostPageBaseURL() + '/api/file/imageDownload?className=' + className + '&fileName=' + imageName;
  },


  // 获取略缩图图片路径
  getThumbnailImageSrc: function (className, imageName) {
    if (imageName == null) {
      return null;
    }
    return this.getHostPageBaseURL() + '/api/file/thumbnailImageDownload?className=' + className + '&fileName=' + imageName;
  },


  /**
   * 获取附件的路径
   * @param  {[type]} className [description]
   * @param  {[type]} imageName [description]
   * @return {[type]}           [description]
   */
  getAttachmentsSrc: function (className, imageName) {
    var accountId = localStorage.getItem('#accountId');
    return this.getHostPageBaseURL() + 'Files/' + accountId + '/Attachments/' + className + '/' + imageName;
  },

  // 获取图片路径
  getVideoSrc: function (className, imageName) {
    var accountId = localStorage.getItem('#accountId');
    if (imageName == undefined || imageName == '') {
      return this.getHostPageBaseURL() + 'static/image/noImage.jpg';
    }

    return this.getHostPageBaseURL() + 'Files/' + accountId + '/Video/' + className + '/' + imageName;
  },


  //获取资源路径   type： 图片image,视频video,文件file,
  getResourceUrl: function (type, className, resourceName) {
    var accountId = localStorage.getItem('#accountId');
    if (resourceName == undefined || className == undefined || type == undefined || resourceName == '' || className == '' || type == '') {
      return;
    }
    if (type == 'image') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Images/' + className + '/' + resourceName;
    }
    if (type == 'video') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Video/' + className + '/' + resourceName;
    }
    if (type == 'file') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Files/' + className + '/' + resourceName;
    }

  },
  // 后台接口返回的数据带className使用
  getResourceUrl1: function (type, resourceName) {
    var accountId = localStorage.getItem('#accountId');
    if (resourceName == undefined || type == undefined || resourceName == '' || type == '') {
      return;
    }
    if (type == 'image') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Images/' + resourceName;
    }
    if (type == 'video') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Video/' + resourceName;
    }
    if (type == 'file') {
      return this.getHostPageBaseURL() + '/Files/' + accountId + '/Files/' + resourceName;
    }

  },



  //设置路径到localStorage
  setHref: function () {
    var href = window.location.href;
    if (href.indexOf('http') == 0) {
      href = href.substring(0, href.indexOf('#') + 2);
      localStorage.setItem('href', href);
    } else {
      var hostPageBaseURL = localStorage.getItem('hostPageBaseURL');
      if (hostPageBaseURL == undefined) {
        href = href.substring(0, href.indexOf('#') + 2);
        localStorage.setItem('href', href);
      }
    }
  },

  //加载系统参数到localStorage
  loadSystemParam: function (systemParamName, success) {
    var that = this;
    $.ajax({
      url: that.getApiURL('SystemParamResource/loadSystemParam'),
      type: 'GET',
      dataType: 'text',
      data: {
        'systemParamName': systemParamName,
      },
      beforeSend: function (request) {
        that.addTokenToRequest(request);
      },
      success: function (data) {
        localStorage.setItem(systemParamName, data);
        success();
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        that.processException(XMLHttpRequest, textStatus, errorThrown);
      },
    });
  },

  // 给请求头中加上account和token信息
  addTokenToRequest: function (request) {
    // request.setRequestHeader('#accountId', localStorage.getItem('#accountId'));
    request.setRequestHeader('token', localStorage.getItem('#token'));
  },

  /**
   * 获取Token
   */
  getToken: function () {
    return localStorage.getItem('#token');
  },

  // 获取新建对象的Id
  getNewRecordId: function () {
    window.CRUDId++;
    return window.CRUDId;
  },

  // 清空 Cookie
  clearCookie: function () {
    // eslint-disable-next-line
    var keys = document.cookie.match('/[^ =;]+(?=\=)/g');
    if (keys) {
      for (var i = keys.length; i--;) {
        // 清除当前域名路径的有限日期
        document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();
        // Domain Name域名 清除当前域名的
        document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();
        // 清除一级域名下的或指定的
        document.cookie = keys[i] + '=0;path=/;domain=baidu.com;expires=' + new Date(0).toUTCString();
      }
    }
  },
  // 清空 Cookie
  clearAppCookie: function (loginInfo) {
    document.cookie.split(';').forEach(function (c) {
      document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
    });
    // $.removeCookie('token', { path: '/' });
    // $.removeCookie('token', { path: '/app' });
    // $.cookie('token', loginInfo.token, {
    //   expires: 7,
    //   path: '/',
    //   secure: true,
    //   sameSite: 'Strict',
    // });
  },
  clearLocalStorage: function (isClearWorkTabs) {
    // 清理localStorage时需要保留的参数列表
    var reserveParams = ['hostPageBaseURL', 'workShopId', 'resourceInstanceId',
      'resourceInstanceName', 'apsBaseUrl', 'cameraBaseURL', '#rememberPassword', '#userName', '#password', '#languageSelected','menuWidth'];
    if (!isClearWorkTabs) reserveParams.push('workTabs');
    //存放的信息
    var reserveParamValues = [];

    //获取参数信息 
    var len = reserveParams.length;
    for (let i = 0; i < len; i++) {
      var reserveParam = reserveParams[i];
      var reserveParamValue = '';
      if (localStorage.getItem(reserveParam) != undefined) {
        reserveParamValue = localStorage.getItem(reserveParam);
      }
      reserveParamValues.push(reserveParamValue);
    }

    //清理localStorage
    window.localStorage.clear();

    //还原参数信息
    for (let i = 0; i < len; i++) {
      localStorage.setItem(reserveParams[i], reserveParamValues[i]);
    }

  },

  showDialog: function (title, content, type) {
    if (type == 'success') {
      Notify.success(title, content, 4000);
    }
    else if (type == 'error') {
      Notify.error(title, content, -1);
    }
    else if (type == 'info') {
      Notify.info(title, content, 2000);
    }
    else if (type == 'notice') {
      Notify.notice(title, content, 2000);
    }
  },


  // 获取路由中的参数
  getRouteParam: function (name) {
    var reg = new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i');
    if (reg.test(location.href)) return unescape(RegExp.$2.replace(/\+/g, ' '));
    return '';
  },

  /**
   * 获取跳转的路径
   * @param {*} url 
   */
  getRedirectUrl: function (url) {
    var href = window.location.href;
    if (href.indexOf('pcapp') >= 0) {
      return this.getHostPageBaseURL() + '/pcapp/' + url;
    } else {
      return this.getHostPageBaseURL() + '/' + url;
    }
  },

  /**
   * 函数防抖
   * 在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则重新计时。
   * @param {*} fn 
   * @param {*} delay 
   * @returns 
   */
  debounce: function (fn, delay) {
    var timer; // 维护一个 timer
    return function () {
      var _this = this; // 取debounce执行作用域的this
      var args = arguments;
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(function () {
        fn.apply(_this, args); // 用apply指向调用debounce的对象，相当于_this.fn(args);
      }, delay);
    };
  },

  // trumbowyg 查看内容时通过对应的a标签进行附件下载
  downloadByA: function (element) {
    const contents = document.querySelectorAll(element);
    if (!contents.length) return;
    contents.forEach(content => {
      content.addEventListener('click', function (e) {
        const target = e.target;
        if (target && target.classList && target.classList.contains('trumbowyg-attachment-link')) {
          e.preventDefault();
          const fileName = target.getAttribute('file-name');
          const className = target.getAttribute('class-name');
          DownloadService.fileDownload(className, fileName);
        }
      });
    });
  },
};

