import { message } from 'antd'

export function getAntdFormVal (value, data, isEvent) {
  let val
  if (data && data.props) val = data.key // 下拉框
  else if (data) val = data // 日历插件
  else if (isEvent) val = value.target.type === 'checkbox' ? value.target.checked : value.target.value // 多选/普通文本框
  else val = value

  return val
}

export function onChange (property, isEvent = false) {
  return function (value, data) {
    let val = getAntdFormVal(value, data, isEvent)

    this.props &&
            this.props.transferMsg &&
            this.props.transferMsg(property, val)
  }
}

export function onComponentChange (mergeInfo, property, isEvent = false) {
  return function (value, data) {
    let val = getAntdFormVal(value, data, isEvent)

    let mInfo = this.props.info[mergeInfo]
    mInfo[property] = val

    this.props &&
            this.props.transferMsg &&
            this.props.transferMsg(mergeInfo, mInfo)
  }
}

export function showSuccess (text) {
  message.success(text)
}

export function showError (text) {
  message.error(text)
}

export function showWarning (text) {
  message.warning(text)
}

export function isFunction (arg) {
  return Object.prototype.toString.call(arg) === '[object Function]'
}

export function isRegExp (arg) {
  return Object.prototype.toString.call(arg) === '[object RegExp]'
}

export function getBase64(file, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(file);
}

//base64转blod
export function dataURItoBlob (base64Data) {
  var byteString
  if (base64Data.split(',')[0].indexOf('base64') >= 0) { byteString = atob(base64Data.split(',')[1]) } else byteString = unescape(base64Data.split(',')[1])
  var mimeString = base64Data
    .split(',')[0]
    .split(':')[1]
    .split(';')[0]
  var ia = new Uint8Array(byteString.length)
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i)
  }
  return new Blob([ia], {
    type: mimeString
  })
}

/**
 * 获取Url上指定参数
 * @param {String} name 参数名
 */
export function getUrlParam (name) {
  var reg = new RegExp('[?&]' + name + '=([^&#?]*)(&|#|$)')
  var r = window.location.href.match(reg)
  return r ? r[1] : null
}

export function getCookie (name) {
  var arr; var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  arr = document.cookie.match(reg)
  if (arr) { return unescape(arr[2]) } else { return null }
}
