
import * as API from "@/common/js/api";
import axios from 'axios'
import state from '@/store/state'
//获取url上面的地址
export function getUrl () {
  var url = window.location.href;
  console.log(url);
  url = url.split('#/')[1]
  var strs = "";
  var therequest = new Object();
  if (url.indexOf("?") != -1) {
    url = url.split("?")[1];
    strs = url.split("&");
    for (var i = 0; i < strs.length; i++) {
      therequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
    }
  }
  console.log(therequest);
  return therequest
};

//下载文件
export function downloadFile (url) {
  try {
    var elemIF = document.createElement("iframe");
    elemIF.src = url;
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
  } catch (e) {

  }
}

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

export function fileDownload (url, fileName, binaryStream) {
  //兼容ie10+ firefox chrome
  if (window.navigator.msSaveOrOpenBlob) {
    try {
      window.navigator.msSaveOrOpenBlob(new Blob([binaryStream]), fileName)
    } catch (e) {
      console.log(e)
    }
  } else {
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.href = url
    a.download = fileName
    a.click()
    document.body.removeChild(a)
  }
}

//获取当前是第几周
// let date = new Date()  // date.setDate(date.getDate()-7);//设置天数 -1 天
export function getWeekOfYear (obj) {
  var today = obj || new Date();
  var firstDay = new Date(today.getFullYear(), 0, 1);
  var dayOfWeek = firstDay.getDay();
  var spendDay = 1;
  if (dayOfWeek != 0) {
    spendDay = 7 - dayOfWeek + 1;
  }
  firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
  var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
  var result = Math.ceil(d / 7);
  return result + 1;
};

//数组内对象排序
export function arrSort (parameter, sort) {
  let dataArray = [];
  let arr = parameter.sort(compare(sort));
  function compare (property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  }
  arr.forEach(item => {
    let obj = {};
    obj.name = item.name;
    obj.id = item.id;
    dataArray.push(obj)
  })
  return dataArray
}

/*
*上传文件公共方法
*options:{
*   vm:this,vue实例对象
*   file:file,
*   type:[],限制文件类型
*   size:2,限制文件大小：2M
*   typeErrMsg:'上传附件类型为:excel', 文件类型错误信息
*   sizeErrMsg:'上传附件大小不能超过2M!',文件大小错误信息
*}
*/
export function avatarUpload (options) {
  let fileSuffix = options.file.name.substring(options.file.name.lastIndexOf('.') + 1).toLowerCase()
  const fileType = options.type
  let isInArray = fileType.includes(fileSuffix)
  let isLt2M = (options.file.size / 1024 / 1024) < options.size

  if (!isInArray) {
    options.vm.$message.warning(options.typeErrMsg)
  }
  if (!isLt2M) {
    options.vm.$message.warning(options.sizeErrMsg)
  }
  return isInArray && isLt2M
}

export function isNull (value) {
  if (value === undefined || value == 'undefined' || value == null) {
    return ''
  } else {
    return value
  }
}

export function fileIsImage (fileName) {
  let fileSuffix = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
  let isImage = ['jpeg', 'jpg', 'png'].includes(fileSuffix)
  return isImage
}

export function imageRemoveSuffix (imageName) {
  return imageName.substring(0, imageName.lastIndexOf('.'))
}

export function json2tree (list, id, pid) {
  let result = [], temp = {}
  for (let i = 0; i < list.length; i++) {
    temp[list[i][id]] = list[i] //将nodes数组转成对象类型
  }
  for (let j = 0; j < list.length; j++) {
    let tempVp = temp[list[j][pid]] //获取每一个子对象的父对象
    if (tempVp) { //判断父对象是否存在，如果不存在直接将对象放到第一层
      if (!tempVp['children']) tempVp['children'] = [] //如果父元素的nodes对象不存在，则创建数组
      tempVp['children'].push(list[j]) //将本对象压入父对象的nodes数组
    } else {
      result.push(list[j]) //将不存在父对象的对象直接放入一级目录
    }
  }
  return result
}

export function removeAaary (_arr, _obj) {
  let length = _arr.length;
  _obj.forEach(item => {
    for (var i = 0; i < length; i++) {
      try {
        if (_arr[i].text == item) return _arr.splice(i, 1)
      } catch (e) {
        return _arr
      }
    }
  })
}

export function copyData (data) {
  return JSON.parse(JSON.stringify(data))
}

export function inArray (array, option) {
  for (var i = 0, length = array.length; i < length; i++) {
    if (option === array[i]) {
      return true
    }
  }
  return false
}

let timeout = null
export function debounce (fn, wait = 200) {
  if (timeout !== null) clearTimeout(timeout)
  timeout = setTimeout(fn, wait)
}

export function underLineToCamelCaseOfString (string) {
  return string.replace(/_([a-z])/g, (all, letter) => {
    return letter.toUpperCase()
  })
}
//获取最近3天日期
export function defaultPostTime (val) {
  return getDay(val);//当天日期
  // getDay(0);//当天日期
  // getDay(-3);//3天前日期
  function getDay (day) {

    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;

    today.setTime(targetday_milliseconds); //注意，这行是关键代码

    var tYear = today.getFullYear();

    var tMonth = today.getMonth();

    var tDate = today.getDate();

    tMonth = doHandleMonth(tMonth + 1);

    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate;
  }

  function doHandleMonth (month) {
    var m = month;
    if (month.toString().length == 1) {
      m = "0" + month;
    }
    return m;
  }
}

export function dynamicAddScriptDom ({ id, js }) {
  const script = document.createElement('script')
  script.id = id
  script.type = 'text/javascript'
  script.innerHTML = js
  document.getElementsByTagName('body')[0].appendChild(script)
}

export function dynamicAddStyleDom ({ id, css }) {
  if (document.all) { // ie
    window.style = css
    document.createStyleSheet('javascript:style')
  } else {
    const style = document.createElement('style')
    style.type = 'text/css'
    style.id = id
    style.innerHTML = css
    document.getElementsByTagName('head')[0].appendChild(style)
  }
}

export function getDynamicFormConfig (jsConfig) {
  const config = { type: [], display: [], user: {} }
  try {
    Object.keys(config).forEach(option => {
      const configKey = '_task_change_form_control_' + option + '_config'
      const startOption = jsConfig.indexOf(configKey)
      if (~startOption) {
        // why use eval: 已知截取的是一个不标准的json(
        // key 没有引号,value是单引号,甚至有注释等等,是一个js文件,可随意添加代码)
        // 当然 也可以动态拼接生成的string 添加一个script标签
        // 但是没必要 对于已知不标准的json数据来说 eval很合适 没必要嫌弃他 执行效率也不低

        const jsonString = returnSymbolMatchToContent({
          string: jsConfig.slice(startOption),
          symbol: JSON.stringify(config[option]).charAt(0)
        })
        config[option] = eval('(' + jsonString + ')')
      }
    })
  } catch (e) { }
  return config
}

export function dynamicRemoveScriptDom (id) {
  const script = document.getElementById(id)
  script && script.parentNode.removeChild(script)
}

export function dynamicRemoveStyleDom (id) {
  const style = document.querySelectorAll('style')
  const currentIdDom = [...style].find(item => item.id == id)
  currentIdDom && currentIdDom.remove()
}

export function getElementOffset ({ element, direction }) {
  const dir = direction.charAt(0).toUpperCase() + direction.slice(1)
  let offset = element['offset' + dir]
  let parent = element.offsetParent
  while (parent !== null) {
    offset += parent['offset' + dir]
    parent = parent.offsetParent
  }
  return offset
}

export function getCurrentStyle (node) {
  return window.getComputedStyle ?
    getComputedStyle(node, null) : node.currentStyle
}

export function returnSymbolMatchToContent ({
  string,
  symbol = '[',
  includeSymbol = true }) {

  const leftSymbol = ['(', '[', '{']
  const rightSymbol = [')', ']', '}']
  const symbolIndex = leftSymbol.indexOf(symbol)
  // 先完成左映射 右映射可将字符串颠倒 相同符号更简单

  if (~symbolIndex) {
    const currentRight = rightSymbol[symbolIndex]

    let symbolStack = []
    let resultString = symbol

    //剪切源字符  使第一个字符为左符号后第一位
    let srouceString = string.slice(string.indexOf(symbol) + 1)
    symbolStack.push(symbol)
    for (let i = 0, len = srouceString.length; i < len; i++) {
      if (symbolStack.length) {
        if (srouceString[i] == symbol) {
          symbolStack.push(srouceString[i])
        } else if (srouceString[i] == currentRight) {
          symbolStack.pop()
        }
        resultString += srouceString[i]
      } else {
        break
      }
    }
    return includeSymbol ? resultString : resultString.slice(1, -1)
  } else {
    return string
  }
}

export const mobileFilterAdd = url => {
  if (isH5Milieu) {
    let pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}:\d{0,4}/
    let newAdd = '183.224.8.165:5081'
    return url.replace(pattern, newAdd)
  } else {
    return url
  }
}
export const utilUploadImageMultipart = (data, options) => {
  const {
    formMetaId,
    processKey,
    code,
    id,
    nodeId,
  } = options
  console.log(options)
  if (!data.length) return ""
  let files = Array.prototype.slice.call(data)
  let formData = new FormData()
  for (let file of data) {
    formData.append("files", file.file);
  }
  formData.append("formMetaId", formMetaId);
  formData.append("processKey", processKey);
  formData.append("flowStage", code);
  formData.append("formInsId", id);
  formData.append("nodeId", nodeId);


  return axios.post(API.URL_ADD + "/flow/attachment/upload", formData, {
    timeout: 10 * 60 * 1000
  }).then(res => {
    console.log(res)
    return true
  }).catch(e => {
    console.log(e)
    return false
  })

}
export const appDataBackfill = url => {
  let filterUrl = ['http://10.174.240.17:8082']
  let appUrl = 'http://183.224.8.165:5081'
  let newUrl = url
  if (state.isH5Milieu && newUrl.includes(filterUrl)) {
    return newUrl.replace(filterUrl, appUrl)
  } else {
    return newUrl
  }
}




