/**
 * Created by Anndy Yang on 18/03/18.
 */

Date.prototype.format = function(fmt) {
  var o = {
    'M+': this.getMonth() + 1,                 // 月份
    'd+': this.getDate(),                    // 日
    'h+': this.getHours(),                   // 小时
    'm+': this.getMinutes(),                 // 分
    's+': this.getSeconds(),                 // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds()             // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}



export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  let des = ''

  if (diff < 30) {
    des = '刚刚'
  } else if (diff < 3600) { // less 1 hour
    des = Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    des = Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    des = '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    if (des) {
      return des + ' (' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + ')'
    } else {
      return d.getMonth() + 1 + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
    }
  }
}

// 将树形结构任意两个key修改成对应的特定key
// {id: '', name: ''} => {id: '', label: ''}
export function convertTreeData(originData, orgId = 'id', orgLabel = 'name', targetId = 'id', targetLabel = 'label') {
  const targetData = []
  let targetObj = {}
  for (let i = 0; i < originData.length; i++) {
    targetObj = {}
    targetObj[targetId] = originData[i][orgId]
    targetObj[targetLabel] = originData[i][orgLabel]
    targetData.push(targetObj)
    if (originData[i].children && originData[i].children.length > 0) {
      targetObj.children = convertTreeData(originData[i].children, orgId, orgLabel, targetId, targetLabel)
    }
  }
  return targetData
}

/**
 * JSON数组去重
 * @param: [array] json Array
 * @param: [string] 唯一的key名，根据此键名进行去重
 */
export function uniqueArray(array, key) {
  const result = [array[0]]
  for (let i = 1; i < array.length; i++) {
    const item = array[i]
    let repeat = false
    for (let j = 0; j < result.length; j++) {
      if (item[key] === result[j][key]) {
        repeat = true
        break
      }
    }
    if (!repeat) {
      result.push(item)
    }
  }
  return result
}

export function resizeHeight(cMinusHeight = 152, iMinuxHeight = 210, refHeightId = 'sidebarWrapperId', 
  containerHeightId = 'appContainerId', innerHeightId = 'elTableId'){
  if (!p_getElm(refHeightId) || !p_getElm(containerHeightId) || !p_getElm(innerHeightId)) {
    // window.onresize = null
    logger.warn('No certain dom id!!!');
  }
  let containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 50
  p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px'
  p_getElm(innerHeightId).style.height = containerHeight - iMinuxHeight + 'px'
  if(p_getElm('elTableIdInner')){
    p_getElm('elTableIdInner').style.height = containerHeight - iMinuxHeight + 'px' 
  }
  window.onresize = function() {
    containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 50
    p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px'
    p_getElm(innerHeightId).style.height = containerHeight - iMinuxHeight + 'px'
    if (p_getElm('elTableIdInner')) {
      p_getElm('elTableIdInner').style.height = containerHeight - iMinuxHeight + 'px'  
    }
  }
}

function p_getElm(elmId) {
  return document.getElementById(elmId)
}

export function getHostnameAndPort() {
  const NODE_ENV = process.env.NODE_ENV
  if (NODE_ENV === 'production') {
    return location.hostname + ':' + location.port
  } else {
    return '192.168.80.191:8080'
  }
}

function setRouterParm(paramList){
  let parm = {};
  if(paramList.length<=1){
    return '';
  }
  for(let i=1;i<paramList.length;i++){
    parm[paramList[i].key] = paramList[i].value;
  }
  return parm;
}

export function setEventByModuleCode(itemData){
  let modeCode = itemData.appModuleInfo.code || '';
  let paramList = itemData.appModuleInfo.paramList ? itemData.appModuleInfo.paramList : ''
  if( modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
      paramList = ''
  }else if( modeCode === 'M100' || modeCode === 'M300' ) {
     
    let urlPara = getUrlParmByCode(paramList);
    paramList[0] && (paramList[0].value += urlPara);

  }else if( modeCode === 'M400') {

      let path = paramList[0]['key'];
      let v = paramList[0]['value'];
      let query = setRouterParm(paramList);

      //console.log(Vue);
      // this.$router.push({
      //   path: v,
      //   query:query
      // })
  }
  if(typeof paramList === 'string' && !paramList){
      paramList = []
  }

  return paramList;
}

function getUrlParmByCode(paramList) {
    if ( paramList.length <= 1) {
        return ''
    }
    let dataStr = ''
    let list = [];
    for( let i = 1; i < paramList.length; i ++) {
        list.push(paramList[i].key + '=' + paramList[i].value)
    }
    dataStr = list.join('&')
    if (dataStr !== '') {
        return '?' + dataStr
    }
    return ''
}

export function pageJumpUrl(){
  let url = { 
    pageListUrl : 'https://test1-contents.yunqueyi.com/content_list',
    detailUrl : 'https://test1-contents.yunqueyi.com/content_detail'
  };

  return url;
}


// dev地址
// const baseUrl = 'https://dev-sc.yunqueyi.com/'
// const apiUrl = 'https://dev-api.yunqueyi.com/'

// test1地址
const baseUrl = 'https://test1-sc.yunqueyi.com/'
const apiUrl = 'https://test1-api.yunqueyi.com/'
//const devApiUri = 'https://test1-api.yunqueyi.com/'

// // uat地址
// const baseUrl = 'http://uat-sc.yunqueyi.com/'
// const apiUrl = 'http://uat-api.yunqueyi.com/'

// // pro地址
// const baseUrl = 'http://sc.yunqueyi.com/'
// const apiUrl = 'http://api.yunqueyi.com/'


// 为每个URL添加应用校验密钥
export function getBaseUrl(url,str) {
  
  return baseUrl + url
 
}

export function getApiUrl(url) {
 
  return apiUrl + url
  
}
