import Vue from 'vue'
// import AppData from '../stores/AppData'

// 登录后获取的所有数据，需要自行获取
export var f

export function getAttendanceState(item, timeToWork, timeToGo) {
  item.f_state = ''
  if(!item.f_signin_time || !item.f_knockoff_time)
    item.f_state = '缺勤'
  else {
    let signin_time = item.f_signin_time.substring(11, 16)
    let knockoff_time = item.f_knockoff_time.substring(11, 16)
    if(signin_time > timeToWork)
      item.f_state = '迟到'
    if(knockoff_time < timeToGo)
      item.f_state = item.f_state + '早退'
  }
  if(!item.f_state)
    item.f_state = '正常'
}

// 字符串进行解密
export function uncompileStr (code) {
  code = unescape(code)
  let c = String.fromCharCode(code.charCodeAt(0) - code.length)
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1))
  }
  return c
}

// 通过地址栏的参数获取参数内容
export function getUrlParames (param) {
  var query = window.location.search
  var iLen = param.length
  var iStart = query.indexOf(param)
  if (iStart === -1) {
    return ''
  }
  iStart += iLen + 1
  var iEnd = query.indexOf('&', iStart)
  if (iEnd === -1) {
    return query.substring(iStart)
  }
  return query.substring(iStart, iEnd)
}

// 从地址栏获取加密的参数
export function getUrlCompileParames (param) {
  var query = uncompileStr(window.location.search.slice(1, window.location.search.length))
  var iLen = param.length
  var iStart = query.indexOf(param)
  if (iStart === -1) {
    return ''
  }
  iStart += iLen + 1
  var iEnd = query.indexOf('&', iStart)
  if (iEnd === -1) {
    return query.substring(iStart)
  }
  return query.substring(iStart, iEnd)
}

export function toStandardYearMonth() {
  let dt = new Date()
  let month = dt.getMonth()+1
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month)
}

export function toStandardDateString() {
  let dt = new Date()
  let month = dt.getMonth()+1
  let date = dt.getDate()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
}
//获取当前月第一天
export function toStartDateString () {
  let dt = new Date()
  let month = dt.getMonth() + 1
  let date = dt.getDate()
  return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + '01'
}
//获取当前月最后一天
export function toEndDateString () {
  let dt = new Date()
  let month = dt.getMonth() + 1
  // let date = dt.getDate()
  return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (new Date(dt.getFullYear(), month, 0).getDate())
  // return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
}

//获取当前年份1月1号
export function toStartDateYearString () {
  let dt = new Date()
  let date = dt.getDate()
  return dt.getFullYear() + '-' + '01' + '-' +  '01'
}
export function toStandardTimeString() {
  let dt = new Date()
  let month = dt.getMonth()+1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
    + ' ' + (hour<10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec<10? '0'+ sec : sec)
}

export function getPreMonth(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

export function to3339TimeString() {
  let dt = new Date()
  let month = dt.getMonth()+1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
    + 'T' + (hour<10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec<10? '0'+ sec : sec)
}

export function parse3339String(strDate) {
  return new Date(
    strDate.substr(0, 4), strDate.substr(5, 2)-1, strDate.substr(8, 2)
    ,strDate.substr(11, 2), strDate.substr(14, 2), strDate.substr(17, 2)
  )
}

/**
 * 判断前值是否为空，如果为龙返回后值，类似sqlserver 同名函数 isnull(v1,v2)
 * @param check_expression
 * @param replacement_value
 * @returns {string|Array|*}
 */
export function isnull(check_expression,replacement_value) {
  if (typeof check_expression == 'string') {
    if (check_expression) {
      return check_expression
    } else {
      return replacement_value
    }
  }else if (check_expression instanceof Array) {
    if (check_expression.length ===0) {
      return replacement_value
    } else {
      return check_expression
    }
  } else if (check_expression instanceof Object) {
    if (check_expression == null || !check_expression || JSON.stringify(check_expression) === "{}") {
      return replacement_value
    }else {
      return check_expression
    }
  } else {
    if (check_expression) {
      return check_expression
    } else {
      return replacement_value
    }
  }
}

/**
 * 将时间类型，转为指定的（YYYY-mm-dd HH:MM:SS）str类型
 * @param fmt
 * @param date
 * @returns {*}
 */
export function dateFormatToFmt(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    }
  }
  return fmt;
}

export function format3339TimeString(dt) {
  let month = dt.getMonth()+1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
      + 'T' + (hour<10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec<10? '0'+ sec : sec)
}

export function guid() {
  let buf = new Uint16Array(8)
  window.crypto.getRandomValues(buf)
  let S4 = function(num) {
      let ret = num.toString(16)
      while(ret.length < 4){
          ret = '0' + ret
      }
      return ret
  }
  return (S4(buf[0])+S4(buf[1])+S4(buf[2])+S4(buf[3])+S4(buf[4])+S4(buf[5])+S4(buf[6])+S4(buf[7]))
}

export function choices (role, param, hasBlank = false, blankHint = '请选择') {
  if (role === 'view') {
    Vue.$appdata.getParam(param, [null])
  } else {
    let result = []
    if(hasBlank)
      result.push({label: blankHint, value: null})
    if(!Vue.param || !Vue.param[param])
      result.push({label: '请在系统设置里更新参数', value: '请在系统设置里更新参数'})
    else {
      //console.log(param)
      //console.log(JSON.stringify(Vue.param))
      let p = Vue.param[param]
      p.forEach(function(item) {
        result.push({label: item.name, value: item.name})
      })
    }
    return result
  }
}

export function required(param) {
  if(typeof param === 'number' && param === 0)
    return false
  if(!param)
    return true
  param = param + ''
  param = param.trim()
  if(!param)
    return true
  // if(param === '')
  //   return true
  // if(param == null)
  //   return true
  // if(typeof param == 'undefined')
  //   return true
  return false
}

export function isInt(n){
  console.log('判断整数' + n)
  return !window.isNaN(n) && n % 1 === 0
}

export function isFloat(n){
  console.log('判断小数' + n)
  return !window.isNaN(n)
}

// this will convert all true/false to boolean
export function booleanFilter(paper) {
    for(let key in paper) {
      if(!paper.hasOwnProperty(key))
        continue
      if(typeof paper[key] == "object" && paper[key] != null) {
        booleanFilter(paper[key]);
      } else {
        if(paper[key] === "true" || paper[key] == "false")
          paper[key] = (paper[key] === "true")
      }
    }
}
// recursively traverse through each path
export function ratifyPics(paper) {
    for (let key in paper) {
      if (key.endsWith('_path') && !(JSON.stringify(paper[key]).startsWith('"rs'))) {
        if (!paper[key]) {
          paper[key] = ''
        } else {
          paper[key] = 'rs/image/file/' + paper[key]
        }
      } else if (paper[key] !== null && typeof(paper[key]) == "object") {
        ratifyPics(paper[key])
      }
    }
}
export function androidRatifyPics(paper,url) {
  console.log('androidRatifyPics-paper'+JSON.stringify(paper))
    for (let key in paper) {
      if (key.endsWith('_path') && !(JSON.stringify(paper[key]).startsWith(`"${url}`))) {
        console.log('开头是rs')
        if (!paper[key]) {
          paper[key] = ''
        } else {
          paper[key] = `${url}/rs/image/file/` + paper[key]
        }
      } else if (paper[key] !== null && typeof(paper[key]) == "object") {
        androidRatifyPics(paper[key],url)
      }
    }
}

// load script and other stuff
export function loadscript(type, fileName) {
  return new Promise((resolve, reject)=> {
    let element
    if(type == 'css') {
      element = document.createElement('link')
      element.setAttribute("rel", "stylesheet")
      element.setAttribute("type", "text/css")
      element.setAttribute("href", fileName)
    } else if(type == 'js') {
      element = document.createElement('script')
      element.setAttribute("type","text/javascript")
      element.setAttribute("src", fileName)
    }
    if(element) {
      element.setAttribute('async', '')
      element.setAttribute('defer', '')
      element.addEventListener('load', function() {
                resolve(element)
                console.log('load script resolved')
            }, false)
      element.addEventListener('error', function() {
                reject(element)
                console.log('load script rejected')
            }, false)
      document.body.appendChild(element)
    }
  })
}

export function getFileName(fileName) {
  let pos = fileName.indexOf('?')
  if(pos == -1) {
    let pos2 = fileName.lastIndexOf('/')
    if(pos2 == -1) {
      return fileName
    } else {
      return fileName.substring(pos2 + 1)
    }
  } else {
    if(pos2 == -1) {
      return fileName
    } else {
      return fileName.substring(pos2 + 1, pos)
    }
  }
}

export function replaceFalse(paper) {
  for (let key in paper) {
    if (paper[key]) {
      if (paper[key] == "false" ) {
        paper[key] = null
      } else if (paper[key] !== null && typeof(paper[key]) == "object") {
        replaceFalse(paper[key])
      }
    }
  }
}

export function getNowDate (name) {
  let year = ''
  let month = ''
  let day = ''
  let hour = ''
  let minutes = ''
  let seconds = ''
  let mydate = new Date()
  let mymonth = mydate.getMonth() + 1
  let myday = mydate.getDate()
  let myyear = mydate.getYear()
  let myhour = mydate.getHours()
  let myminutes = mydate.getMinutes()
  let myseconds = mydate.getSeconds()
  year = (myyear > 200) ? myyear : 1900 + myyear
  month = (mymonth > 9) ? mymonth : '0' + mymonth
  day = (myday > 9) ? myday : '0' + myday
  hour = (myhour > 9) ? myhour : '0' + myhour
  minutes = (myminutes > 9) ? myminutes : '0' + myminutes
  seconds = (myseconds > 9) ? myseconds : '0' + myseconds
  // document.write("<font color=#ffffff>今天是 "+year+"年"+mymonth+"月"+myday+"日 "+weekday+"</font>");
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
}
