import $ from 'jquery';

function getWindowInnerHeight(){
  if(window.innerHeight!=undefined){
    return window.innerHeight;
  }else{
    let by = document.body, ele = document.documentElement;
    return Math.min(by.clientHeight,ele.clientHeight);
  }
};
function getWindowInnerWidth(){
  let width = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth
  return width
};
function getPageCoordinate(event,stic){//获取鼠标点击的位置
  let e = event || window.event;
  var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  var x = e.pageX || (e.clientX + scrollX);
  var y = (e.pageY+(stic?25:0)) || (e.clientY + scrollY + (stic?25:0));//弹窗位置偏下25
  let obj = {
    boxLeft : x ,
    boxTop : y+18
  }
  return obj;
}

 /**
 * @param {拖动元素/清除拖动事件监听} type add:添加事件监听  del:移除事件监听
 * @param {展开元素id} addDom 
 */
let width = '',//屏幕宽度
  height = '', //屏幕高度
  dragWrapper = '',//拖拽元素
  mouseX = 0,//鼠标距离页面左侧
  mouseY = 0,//鼠标距离页面上部
  dragX = 0,//鼠标可拖拽到左边的最大距离（元素定位左侧距离）
  dragY = 0,//鼠标可拖拽到上边的最大距离（元素定位上边距离）
  isDrag = false,//元素是否处于拖拽中
  addPart = null;//展开区域,这个展开的宽度应当是固定宽度了
/**
 * 
 * @param {事件对象} event
 * @param {被拖动的元素} dragModalWrap
 * @param {可拖动的区域} dragModalTitle 
 */
function handleMove(event) {
  let wrap = $("#"+dragWrapper); //被拖拽的元素
  let dragDes = $("#"+addPart); //展開区域
  let page = getPageCoordinate(event, '0');//获取鼠标位置
  let maxDragX = 0,dragDesWidth = 0;
  let wrapHeight = wrap[0].offsetHeight;//直接用.height()获取的高度不准确
  let wrapWidth = wrap[0].offsetWidth;
  let maxDragY = height - wrapHeight; //最大可拖拽y方向距离
  if (dragDes[0]) { //存在就有类似治疗方案的弹窗，最大可推拽x方向距离
    dragDesWidth = dragDes[0].offsetWidth//展开元素的宽度
    maxDragX = width - wrapWidth - dragDesWidth
  } else {
    maxDragX = width - wrapWidth
  }
  if (isDrag) {
    dragX = page.boxLeft - mouseX //鼠标可拖拽到左边的最大距离
    dragY = page.boxTop - mouseY //鼠标可拖拽到上边的最大距离
    if (dragX < 300) { //不能超出左边界
      dragX = 300
    }
    if (dragY < 100) { //不能超出上边界
      dragY = 100
    }
    if (dragDes[0]) {
      if (width - dragX - dragDesWidth < wrapWidth) { //不能超出右边界
        dragX = maxDragX
      }
    } else {
      if (width - dragX < wrapWidth) { //不能超出右边界
        dragX = maxDragX
      }
    }
    if (height - dragY < wrapHeight) { //不能超出下边界
      dragY = maxDragY
    }
    // isMove = true
    wrap.css({
      left: dragX + 'px',
      marginLeft: 0 + 'px',
      marginTop: 0 + 'px',
      top: dragY + 'px',
      bottom:'auto',
      right:'inherit',
    })
  }
}
/**
 * 鼠标弹起弹窗不在跟随鼠标移动
 */
function handleUp(){
  isDrag = false;
  return
}
export default {
  //判断字符串是否能转成json
  isJsonStr(str) {
    if (typeof str === 'string') {
      try {
        const myStr = str.replace(/^\s*/, '');
        const obj = JSON.parse(str);
        if (myStr[0] === '{') {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    }
  },
  tranformDate(time,str,flag='-'){
    if(!time){
      return time;
    }
    const year=time.getFullYear();
    const month = time.getMonth()+1;
    const day = time.getDate();
    return year+flag+(month>9?month:'0'+month)+flag+(day>9?day:'0'+day)+str;
  },
  //获取两个时间间隔天数
  getTimeRangeDay(timeArr) {
    if(!timeArr||timeArr.length==0){
      return null;
    }
    return (new Date(timeArr[1]) - new Date(timeArr[0])) / (1000 * 60 * 60 * 24);
  },
  //导出接口返回流下载
  downloadExportedData(data, fileName) {
    var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
    var downloadElement = document.createElement('a');
    var href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = fileName; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href);
  },
  emailReg: /^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-z\.]{2,6})$/,
  // pswReg: /^(?![0-9]+$)(?![a-zA-Z]+$)/,
  pswReg: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\W_]{6,16}$/,//与后台保持一致
  phoneReg: new RegExp(/^((13|14|15|16|17|18|19)\d{9})$/),
  url:/[a-zA-z]+:\/\/[^\s]*/,
	getDateStr(string,str){
	  var str_before = string.split(str)[0];
	  var str_after = string.split(str)[1];
	},
  exportCondition(time){
    const rangeDay = this.getTimeRangeDay(time);
    if (!time||time.length==0) {
      return '请先选择导出时间';
    }
    if (rangeDay > 30) {
      return '目前只能导出30天内数据，请重新筛选时间';
    }
    return true;
  },
  /**
   * 
   * @param {arr} 被操作的数组 
   * @param {val} 需要剔除或者判断的值 
   * @param {type} 是剔除(1)还是判断(2)是否存在，不存在返回[]
   * @param {des} 1数組元素是对象
   * 
   */
  filterArr(arr,val,type,des){  //数组剔除指定元素 
    if(type == 1){
      if(des){
        return arr.filter(item => item.id != val)  //判断id
      }else{
        return arr.filter(item => item != val)    //判断值
      }
    }else{
      let tmp = arr.filter(item => JSON.stringify(item) == JSON.stringify(val))   //判读是否存在
      if(JSON.stringify(tmp) == '[]'){
        return false;
      }else{
        return true;
      }
    }
  },

  /*返回n个row的数组
  *n:Number
  * row:Object
  * orderName:编号字段名称，默认orderNo
   */
  getInitRow(row,n,orderName){
    let arr = [];
    let obj = {};
    for(let i=0;i<n;i++){
      obj = Object.assign({},row);
      obj[orderName||'orderNo'] = i;
      arr.push(obj);
    }
    return arr;
  },
  //获取图片名称
  getImgName(url){
    const arr = url.split("/");
    return arr[arr.length-1];
  },
 
  dragBox(dragWrap,dragTop,type,addDom,img) {
    let drag = $("#"+dragTop); //拖拽区域
    let wrap = $("#"+dragWrap); //被拖拽的元素
    width = getWindowInnerWidth(); 
    height = getWindowInnerHeight();
    addPart = addDom||null;
    dragWrapper = dragWrap;
    if (type === 'del') {
      $(document).off('mousemove', handleMove)
      $(document).off('mouseup', handleUp)
    } else {
      drag.on('mousedown', function (event) {
        let lenHeight = wrap.height()
        if(img){
          $("#preImg").css("height",(lenHeight)+'px')
          $("#dragModalWrap").css("height",(lenHeight)+'px')
        }
        let page = getPageCoordinate(event, '0');
        mouseX = page.boxLeft - wrap.offset().left; //鼠标到拖拽元素的左边界的距离
        mouseY = page.boxTop - wrap.offset().top; //鼠标到拖拽元素的上边界的距离
        isDrag = true
      })
      $(document).on('mousemove', handleMove)
      $(document).on('mouseup', handleUp)
    }
  },
  getCurrentPage(currentChange, total, pageSize) {
    const currentPage =  currentChange > Math.ceil(total/pageSize) ? Math.ceil(total/pageSize) : currentChange
    return currentPage;
  }
}
