import moment from 'moment'
import { getToken } from './request'
import { GlobalConstant } from '@/constant'
import DictCache from '@/utils/dict'
import {
  message
} from 'ant-design-vue'

const BaseTool = {}
BaseTool.Constant = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 } // 2的倍数
  },
  labelCol2: {
    xs: { span: 4 },
    sm: { span: 4 } // 2的倍数
  },
  labelCol3: {
    xs: { span: 6 },
    sm: { span: 6 } // 2的倍数
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 13 }
  },
  wrapperCol2: {
    xs: { span: 18 },
    sm: { span: 18 }
  },
  wrapperCol3: {
    xs: { span: 24 },
    sm: { span: 15 }
  },
  row: {
    gutter: 16
  },
  INVEST: 'INVEST',
  FINANCE: 'FINANCE',
  FINANCING: 'FINANCING',
  FILE_URL: '',
  HOST: window.location.protocol + '//' + window.location.host,
  scrollY: document.documentElement.clientHeight < 680 ? document.documentElement.clientHeight * 0.4 : document.documentElement.clientHeight * 0.5
}
// 时间对象
BaseTool.Moment = moment
BaseTool.Date = {
  PICKER_NORM_YEAR: 'YYYY',
  PICKER_NORM_MONTH: 'MM',
  PICKER_NORM_YEAR_MONTH: 'YYYY-MM',
  PICKER_NORM_DATE_PATTERN: 'YYYY-MM-DD',
  PICKER_NORM_TIME_PATTERN: 'HH:mm:ss',
  PICKER_NORM_DATETIME_PATTERN: 'YYYY-MM-DD HH:mm:ss',
  /**
   * 将字符串日期格式化
   * @param date
   * @param pattern
   * @returns {string}
   */
  formatter (date, pattern) {
    if (BaseTool.Object.isBlank(date)) {
      return ''
    } else {
      return BaseTool.Moment(date, BaseTool.Date.PICKER_NORM_DATETIME_PATTERN).format(pattern)
    }
  },
  getCountBetween (date1, date2, type = 1) {
    const startTime = new Date(date1) // 开始时间
    const endTime = new Date(date2) // 结束时间
    const usedTime = endTime - startTime // 相差的毫秒数
    const days = Math.floor(usedTime / (24 * 3600 * 1000)) // 计算出天数
    const leavel = usedTime % (24 * 3600 * 1000) // 计算天数后剩余的时间
    const hours = Math.floor(leavel / (3600 * 1000)) // 计算剩余的小时数
    const leavel2 = leavel % (3600 * 1000) // 计算剩余小时后剩余的毫秒数
    const minutes = Math.floor(leavel2 / (60 * 1000)) // 计算剩余的分钟数
    if (type === 1) {
      return days
    }
    if (type === 2) {
      return hours
    }
    if (type === 2) {
      return minutes
    }
  }
}
BaseTool.String = {
  isBlank (text) {
    return text === null || text === undefined || text === 'undefined' || text === ''
  },
  isNotBlank (text) {
    return !this.isBlank(text)
  },
  uuid () {
    const s = []
    const hexDigits = '0123456789abcdef'
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    // s[8] = s[13] = s[18] = s[23] = '-'
    s[8] = s[13] = s[18] = s[23] = ''

    const uuid = s.join('')
    return uuid
  }
}
BaseTool.Object = {
  isBlank (text) {
    if (typeof text === 'string') {
      return BaseTool.String.isBlank(text)
    }
    return text === null || text === undefined
  },
  isNotBlank (text) {
    return !this.isBlank(text)
  },
  /**
   * 获取对象属性
   * @param obj
   * @param field
   * @returns {*}
   */
  getField (obj, field) {
    if (BaseTool.String.isBlank(obj) || BaseTool.String.isBlank(field)) {
      return ''
    }
    return obj[field]
  },
  /**
   * 深克隆
   * @param data
   * @returns {{}|any}
   */
  copy: function (data) {
    if (BaseTool.Object.isBlank(data)) {
      return {}
    }
    return JSON.parse(JSON.stringify(data))
  }
}
BaseTool.Table = {
  defaultOptions (that) {
    return {
      alert: { show: true, clear: () => { that.selectedRowKeys = [] } },
      rowSelection: {
        selectedRowKeys: that.selectedRowKeys,
        onChange: that.onSelectChange
      }
    }
  },
  tableOption (that) {
    if (!that.optionAlertShow) {
      that.options = {
        alert: { show: true, clear: () => { that.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: that.selectedRowKeys,
          onChange: that.onSelectChange,
          getCheckboxProps: record => ({
            props: {
              disabled: false,
              name: record.id
            }
          })
        }
      }
      that.optionAlertShow = true
    } else {
      that.options = {
        alert: false,
        rowSelection: null
      }
      that.optionAlertShow = false
    }
  },
  getMapText (obj, field) {
    if (BaseTool.String.isBlank(obj) || BaseTool.String.isBlank(field)) {
      return ''
    }
    return obj[field]
  },
  getMapTextForMoneyType (obj, field) {
    if (BaseTool.String.isBlank(obj) || BaseTool.String.isBlank(field)) {
      return ''
    }
    return '(币种：' + obj[field] + ')'
  },
  colSpan (value, col) {
    return {
      children: value,
      attrs: {
        colSpan: col
      }
    }
  },
  rowSpan (value, row) {
    return {
      children: value,
      attrs: {
        rowSpan: row
      }
    }
  },
  rowSpanDiv (value, row) {
    return {
      children: BaseTool.Amount.formatter(BaseTool.Number.div(value, 10000, 4)),
      attrs: {
        rowSpan: row
      }
    }
  },
  allSpan (value, col, row) {
    return {
      children: value,
      attrs: {
        colSpan: col,
        rowSpan: row
      }
    }
  },
  statusCustomRender (vm, text, record, type) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    const label = DictCache.getLabelByValue(DictCache.TYPE[type], text)
    const status1 = DictCache.COLOR[type][text]
    const myProps = { status: status1, text: label }
    return vm.$createElement('Badge', { ...{ props: { ...myProps } } })
  },
  statusCustomRenderWhether (vm, text) {
    if (BaseTool.Object.isBlank(text)) {
      return vm.$createElement('Badge', { ...{ props: { status: 'error', text: '否' } } })
    }
    const label = text ? '是' : '否'
    const status1 = text ? 'success' : 'error'
    const myProps = { status: status1, text: label }
    return vm.$createElement('Badge', { ...{ props: { ...myProps } } })
  },
  statusCustomRenderDict (vm, text, record, colorMap, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    const label = dictMap[text]
    const status1 = colorMap[text]
    const myProps = { status: status1, text: label }
    return vm.$createElement('Badge', { ...{ props: { ...myProps } } })
  },
  statusCustomRenderTypeDict (vm, text, record, type, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    const label = dictMap[text]
    const status1 = DictCache.COLOR[type][text]
    const myProps = { status: status1, text: label }
    return vm.$createElement('Badge', { ...{ props: { ...myProps } } })
  },
  statusCustomRenderFun (vm, fun) {
    const myProps = fun()
    return vm.$createElement('Badge', { ...{ props: { ...myProps } } })
  },
  customRenderWidth: (vm, text, width) => {
    const content = {
      content: props => vm.$createElement('div', text)
    }
    const textDom = vm.$createElement('div', {
      style: {
        maxWidth: width + ' !important',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
        cursor: 'pointer'
      }
    }, text)
    return vm.$createElement('a-popover', { scopedSlots: content, attrs: { placement: 'top' } }, [textDom])
  },
  customRenderWidthDefault: (vm, text) => {
    return BaseTool.Table.customRenderWidth(vm, text, '150px')
  },
  customCellWidth: (text, width) => {
    return {
      attrs: {
        title: text
      },
      style: {
        maxWidth: width + ' !important',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
        cursor: 'pointer'
      }
    }
  },
  customCellDefault: (text) => {
    return BaseTool.Table.customCellWidth(text, '150px')
  },
  customRenderDictValue (vm, text, record, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    return dictMap[text]
  },
  customRenderMultiDictValue (vm, text, record, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    const values = text.split(',')
    const texts = new Array()
    values.forEach((item, index, array) => {
      texts.push(dictMap[item])
    })
    return texts.join(',')
  }
}
BaseTool.ListForm = {
  clearOneList: (vm) => {
    vm.$store.dispatch('setOneListAdd', [])
    vm.$store.dispatch('setOneListUpdate', [])
    vm.$store.dispatch('setOneListDelete', [])
  },
  setOneListValues: (vm, values) => {
    values.updateList = vm.$store.getters.oneListUpdate
    values.deleteList = vm.$store.getters.oneListDelete
    values.addList = vm.$store.getters.oneListAdd
    console.log(values.addList)
  },
  setTwoListValues: (vm, values, id) => {
    values.updateList = vm.$store.getters.twoListUpdate[id]
    values.deleteList = vm.$store.getters.twoListDelete[id]
    values.addList = vm.$store.getters.twoListAdd[id]
    // values.addList = addList
    // // 将删除表里面排除 删除后又添加进来的  适用于同一个明细的 比如采购申请 采购单 合同登
    // const addListMap = {}
    // if (addList) {
    //   addList.forEach((item) => {
    //     addListMap[item.id] = item
    //   })
    // }
    // const result = []
    // if (deleteList) {
    //   deleteList.forEach((item) => {
    //     const elem = addListMap[item.id]
    //     if (!elem) {
    //       result.push(item)
    //     }
    //   })
    // }
    // values.deleteList = result
  },
  pushOneListAdd: (vm, item) => {
    if (!item.exist) {
      const oneListAdd = vm.$store.getters.oneListAdd
      oneListAdd.push(item)
      vm.$store.dispatch('setOneListAdd', oneListAdd)
    }
  },
  pushOneListAddMore: (vm, items) => {
    const oneListAdd = vm.$store.getters.oneListAdd
    const addListMap = {}
    oneListAdd.forEach((item) => {
      addListMap[item.id] = item
    })
    items.forEach((item) => {
      if (!item.exist) {
        const elem = addListMap[item.id]
        if (!elem) {
          oneListAdd.push(item)
        }
      }
    })
    vm.$store.dispatch('setOneListAdd', oneListAdd)
  },
  pushOneListAddMoreForEdit: (vm, items, id) => {
    const oneListAdd = vm.$store.getters.oneListAdd
    const addListMap = {}
    oneListAdd.forEach((item) => {
      addListMap[item[id]] = item
    })
    items.forEach((item) => {
      if (!item.exist) {
        const elem = addListMap[item[id]]
        if (!elem) {
          oneListAdd.push(item)
        }
      }
    })
    console.log(oneListAdd)
    vm.$store.dispatch('setOneListAdd', oneListAdd)
  },
  pushTwoListAddMore: (vm, items, id) => {
    const twoListAddMap = vm.$store.getters.twoListAdd
    let twoListAdd = twoListAddMap[id]
    const addListMap = {}
    if (twoListAdd) {
      twoListAdd.forEach((item) => {
        addListMap[item.id] = item
      })
    } else {
      twoListAdd = []
    }
    items.forEach((item) => {
      if (!item.exist) {
        const elem = addListMap[item.id]
        if (!elem) {
          twoListAdd.push(item)
        }
      }
    })
    twoListAddMap[id] = twoListAdd
    vm.$store.dispatch('setTwoListAdd', twoListAddMap)
  },
  pushOneListUpdate: (vm, item) => {
    const oneListAdd = vm.$store.getters.oneListAdd
    let flag = true
    for (let i = 0; i < oneListAdd.length; i++) {
      const value = oneListAdd[i]
      if (item.id === value.id) {
        oneListAdd[i] = item
        flag = false
      }
    }
    if (!flag) {
      vm.$store.dispatch('setOneListAdd', oneListAdd)
    } else {
      const oneListUpdate = vm.$store.getters.oneListUpdate
      const updateListMap = {}
      oneListUpdate.forEach((item) => {
        updateListMap[item.id] = item
      })
      const elem = updateListMap[item.id]
      if (!elem) {
        oneListUpdate.push(item)
      } else {
        for (let i = 0; i < oneListUpdate.length; i++) {
          const one = oneListUpdate[i]
          if (one.id === item.id) {
            oneListUpdate[i] = item
            break
          }
        }
      }
      vm.$store.dispatch('setOneListUpdate', oneListUpdate)
    }
  },
  pushOneListDelete: (vm, items) => {
    const oneListDelete = vm.$store.getters.oneListDelete
    const oneListDeleteMap = {}
    items.forEach((item) => {
      oneListDelete.push(item)
      oneListDeleteMap[item.id] = item
    })
    vm.$store.dispatch('setOneListDelete', oneListDelete)
    const oneListAdd = vm.$store.getters.oneListAdd
    const result = []
    oneListAdd.forEach((item) => {
      const elem = oneListDeleteMap[item.id]
      if (!elem) {
        result.push(item)
      }
    })
    vm.$store.dispatch('setOneListAdd', result)
  },
  clearTwoList: (vm) => {
    vm.$store.dispatch('setTwoListAdd', {})
    vm.$store.dispatch('setTwoListUpdate', {})
    vm.$store.dispatch('setTwoListDelete', {})
  },
  initTwoList: (vm, id) => {
    console.log(id)
    const twoListAddMap = vm.$store.getters.twoListAdd
    const twoListAdd = twoListAddMap[id]
    if (!twoListAdd) {
      twoListAddMap[id] = []
    }
    vm.$store.dispatch('setTwoListAdd', twoListAddMap)
    const twoListUpdateMap = vm.$store.getters.twoListUpdate
    const twoListUpdate = twoListUpdateMap[id]
    if (!twoListUpdate) {
      twoListUpdateMap[id] = []
    }
    vm.$store.dispatch('setTwoListUpdate', twoListUpdateMap)
    const twoListDeleteMap = vm.$store.getters.twoListDelete
    const twoListDelete = twoListDeleteMap[id]
    if (!twoListDelete) {
      twoListDeleteMap[id] = []
    }
    vm.$store.dispatch('setTwoListDelete', twoListDeleteMap)
  },
  pushTwoListAdd: (vm, item, id) => {
    const twoListAddMap = vm.$store.getters.twoListAdd
    const twoListAdd = twoListAddMap[id]
    twoListAdd.push(item)
    twoListAddMap[id] = twoListAdd
    vm.$store.dispatch('setTwoListAdd', twoListAddMap)
  },
  pushTwoListUpdate: (vm, item, id) => {
    const twoListAddMap = vm.$store.getters.twoListAdd
    const twoListAdd = twoListAddMap[id]
    let flag = true
    for (let i = 0; i < twoListAdd.length; i++) {
      const value = twoListAdd[i]
      if (item.id === value.id) {
        twoListAdd[i] = item
        flag = false
      }
    }
    if (!flag) {
      twoListAddMap[id] = twoListAdd
      vm.$store.dispatch('setTwoListAdd', twoListAddMap)
    } else {
      const twoListUpdateMap = vm.$store.getters.twoListUpdate
      const twoListUpdate = twoListUpdateMap[id]
      const updateListMap = {}
      twoListUpdate.forEach((item) => {
        updateListMap[item.id] = item
      })
      const elem = updateListMap[item.id]
      if (!elem) {
        twoListUpdate.push(item)
        twoListUpdateMap[id] = twoListUpdate
        vm.$store.dispatch('setTwoListUpdate', twoListUpdateMap)
      }
    }
  },
  pushTwoListDelete: (vm, items, id) => {
    const twoListDeleteMap = vm.$store.getters.twoListDelete
    let twoListDelete = twoListDeleteMap[id]
    if (!twoListDelete) {
      twoListDelete = []
    }
    const listDeleteMap = {}
    items.forEach((item) => {
      twoListDelete.push(item)
      listDeleteMap[item.id] = item
    })
    twoListDeleteMap[id] = twoListDelete
    vm.$store.dispatch('setTwoListDelete', twoListDeleteMap)
    const twoListAddMap = vm.$store.getters.twoListAdd
    const twoListAdd = twoListAddMap[id]
    const result = []
    if (twoListAdd) {
      twoListAdd.forEach((item) => {
        const elem = listDeleteMap[item.id]
        if (!elem) {
          result.push(item)
        }
      })
    }
    twoListAddMap[id] = result
    vm.$store.dispatch('setTwoListAdd', twoListAddMap)
  },
  getOneListHandledRows: (vm, rows) => {
    const oneListAdd = vm.$store.getters.oneListAdd
    const oneListUpdate = vm.$store.getters.oneListUpdate
    const oneListUpdateMap = {}
    oneListUpdate.forEach((item) => {
      oneListUpdateMap[item.id] = item
    })
    const oneListDelete = vm.$store.getters.oneListDelete
    const oneListDeleteMap = {}
    oneListDelete.forEach((item) => {
      oneListDeleteMap[item.id] = item
    })
    const result = []
    rows.forEach((item) => {
      item.exist = 1
      const id = item.id
      let elem = oneListDeleteMap[id]
      if (!elem) {
        elem = oneListUpdateMap[id]
        if (elem) {
          result.push(elem)
        } else {
          result.push(item)
        }
      }
    })
    const resultMap = {}
    result.forEach((item) => {
      resultMap[item.id] = item
    })
    oneListAdd.forEach((item) => {
      const elem = resultMap[item.id]
      if (!elem) {
        result.splice(0, 0, item)
      }
    })
    return result
  },
  getOneListHandledRowsForEdit: (vm, rows, id) => {
    const oneListDelete = vm.$store.getters.oneListDelete
    const oneListDeleteMap = {}
    oneListDelete.forEach((item) => {
      oneListDeleteMap[item[id]] = item
    })
    const result = []
    const resultMap = {}
    rows.forEach((item) => {
      const i = item[id]
      const elem = oneListDeleteMap[i]
      if (!elem) {
        resultMap[i] = item
        result.push(item)
      }
    })
    const oneListAdd = vm.$store.getters.oneListAdd
    oneListAdd.forEach((item) => {
      const elem = resultMap[item[id]]
      if (!elem) {
        result.splice(0, 0, item)
        resultMap[item[id]] = item
      }
    })

    // rows.forEach((item) => {
    //   const elem = resultMap[item[id]]
    //   if (!elem) {
    //     result.push(item)
    //   }
    // })
    return result
  },
  getTwoListHandledRows: (vm, rows, id) => {
    const twoListAdd = vm.$store.getters.twoListAdd[id]
    const twoListUpdate = vm.$store.getters.twoListUpdate[id]
    const twoListUpdateMap = {}
    if (twoListUpdate) {
      twoListUpdate.forEach((item) => {
        twoListUpdateMap[item.id] = item
      })
    }

    const twoListDelete = vm.$store.getters.twoListDelete[id]
    const twoListDeleteMap = {}
    if (twoListDelete) {
      twoListDelete.forEach((item) => {
        twoListDeleteMap[item.id] = item
      })
    }
    const result = []
    rows.forEach((item) => {
      item.exist = 1
      const id = item.id
      let elem = twoListDeleteMap[id]
      if (!elem) {
        elem = twoListUpdateMap[id]
        if (elem) {
          result.push(elem)
        } else {
          result.push(item)
        }
      }
    })
    const resultMap = {}
    result.forEach((item) => {
      resultMap[item.id] = item
    })
    if (twoListAdd) {
      twoListAdd.forEach((item) => {
        const elem = resultMap[item.id]
        if (!elem) {
          result.splice(0, 0, item)
        }
      })
    }

    return result
  }
}
BaseTool.Amount = {
  /**
   * 元换算为万元
   * @param num ：
   * @returns {number} ：
   */
  divTenThousand (num) {
    if (num == null) {
      return 0
    }
    return BaseTool.Number.div(num, 10000, 3)
    // return num
  },
  /**
   * 元换算为万元，并格式化
   * @param num ：
   * @returns {string} ：
   */
  divTenThousandFormatter (num) {
    if (BaseTool.String.isBlank(num)) {
      return num
    }
    return this.formatter(this.divTenThousand(num))
  },
  /**
   * 格式化金额
   * @param value
   * @returns {string}
   */
  formatter: value => {
    if (BaseTool.String.isBlank(value)) {
      return value
    }
    return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  },
  /**
   * 格式化利率
   * @param value
   * @returns {string|*}
   */
  formatterRate: value => {
    if (BaseTool.String.isBlank(value)) {
      return value
    }
    return value + '%'
  },
  /**
   * 去掉格式化金额
   * @param value
   * @returns {*}
   */
  parser: value => value.replace(/\$\s?|(,*)/g, ''),
  /**
   * 万元换算为元
   * @param num
   * @returns {*}
   */
  mulTenThousand (num) {
    if (BaseTool.String.isBlank(num)) {
      return 0
    }
    return BaseTool.Number.mul(num, 10000, 6)
    // return num
  },
  /**
  * 元换算为万元，并格式化
* @param num ：
* @returns {string} ：
*/
  default (value) {
    if (BaseTool.String.isBlank(value) || value === 0) {
      return '0.00'
    }
    return value
  },
  /**
   * 元换算为万元，并格式化
   * @param num ：
   * @returns {string} ：
   */
  defaultDivTenThousandFormatter (num) {
    if (BaseTool.String.isBlank(num) || num === 0) {
      return '0.00'
    }
    return this.formatter(this.divTenThousand(num))
  }
}

BaseTool.Number = {
  /**
   * 校验费率最大值是否大于100 与  小于0
   * 由于校验框架对值校验需要用a-input-number组件，否则是按照字符串校验
   * @param rule
   * @param value
   * @param callback
   * @param max
   * @param min
   */
  rateValidatorMax: (rule, value, callback) => {
    if (BaseTool.Object.isBlank(rule.min)) {
      rule.min = 0
    }
    if (BaseTool.Object.isBlank(rule.max)) {
      rule.max = 100
    }
    const myValue = parseFloat(value)
    if (myValue > rule.max) {
      callback(new Error(rule.messageBefore + '不能大于' + rule.max))
    } else if (myValue < rule.min) {
      callback(new Error(rule.messageBefore + '不能小于' + rule.min))
    } else {
      callback()
    }
  },
  numberValidatorMax: (rule, value, callback) => {
    const myValue = parseFloat(value)
    if (!BaseTool.Object.isBlank(rule.max) && myValue > rule.max) {
      callback(new Error(rule.messageBefore + '不能大于' + rule.max))
    } else if (!BaseTool.Object.isBlank(rule.min) && myValue < rule.min) {
      callback(new Error(rule.messageBefore + '不能小于' + rule.min))
    } else {
      callback()
    }
  },
  add (arg1, arg2) {
    if (BaseTool.String.isBlank(arg1)) {
      arg1 = 0
    }
    if (BaseTool.String.isBlank(arg2)) {
      arg2 = 0
    }
    let r1, r2
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    const m = Math.pow(10, Math.max(r1, r2))
    const n = (r1 >= r2) ? r1 : r2
    return ((arg1 * m + arg2 * m) / m).toFixed(n)
  },
  sub (arg1, arg2) {
    if (BaseTool.String.isBlank(arg1)) {
      arg1 = 0
    }
    if (BaseTool.String.isBlank(arg2)) {
      arg2 = 0
    }
    let re1, re2
    try {
      re1 = arg1.toString().split('.')[1].length
    } catch (e) {
      re1 = 0
    }
    try {
      re2 = arg2.toString().split('.')[1].length
    } catch (e) {
      re2 = 0
    }
    const m = Math.pow(10, Math.max(re1, re2))
    const n = (re1 >= re2) ? re1 : re2
    return ((arg1 * m - arg2 * m) / m).toFixed(n)
  },
  mul (arg1, arg2) {
    if (BaseTool.String.isBlank(arg1)) {
      arg1 = 0
    }
    if (BaseTool.String.isBlank(arg2)) {
      arg2 = 0
    }
    let m = 0
    const s1 = arg1.toString()
    const s2 = arg2.toString()
    try {
      m += s1.split('.')[1].length
    } catch (e) {}
    try {
      m += s2.split('.')[1].length
    } catch (e) {}

    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
  },
  /**
   * 除法 注意如果整除了 小数点将无效
   * @param arg1 ： 被除数
   * @param arg2 ： 除数
   * @param digit ：精确位数
   * @returns {number}
   */
  div (arg1, arg2, digit) {
    if (BaseTool.String.isBlank(arg1)) {
      arg1 = 0
    }
    if (BaseTool.String.isBlank(arg2)) {
      arg2 = 1
    }
    let t1 = 0
    let t2 = 0
    try { t1 = arg1.toString().split('.')[1].length } catch (e) {}
    try { t2 = arg2.toString().split('.')[1].length } catch (e) {}
    const r1 = Number(arg1.toString().replace('.', ''))
    const r2 = Number(arg2.toString().replace('.', ''))
    // 获取小数点后的计算值
    const result = ((r1 / r2) * Math.pow(10, t2 - t1)).toString()
    let result2 = result.split('.')[1]
    if (result2 !== undefined) {
      result2 = result2.substring(0, digit > result2.length ? result2.length : digit)
    } else {
      result2 = ''
    }
    while (result2.length < digit) {
      result2 = result2 + '0'
    }
    if (digit === 0) {
      return Number(result.split('.')[0])
    }
    return Number(result.split('.')[0] + '.' + result2)
  },
  /**
   * 除法 注意如果整除了 小数点将无效
   * @param arg1 ： 被除数
   * @param arg2 ： 除数
   * @param digit ：精确位数
   * @returns {number}
   */
  divForDollar (arg1, arg2, digit) {
    return '(' + BaseTool.Amount.formatter(BaseTool.Number.div(arg1, arg2, digit)) + '美元)'
  }

}

BaseTool.UPLOAD = {
  /**
   * 上传文件校验是否为文件
   * @param file
   * @param successBack
   * @param errorFun
   * @returns {Promise<boolean>|boolean}
   */
  isFileUpload (file, successBack, errorFun) {
    const reg = /\.(doc|docx|pdf|zip|xls|xlsx)(\?.*)?$/
    if (reg.test(file.name)) {
      if (!BaseTool.Object.isBlank(successBack)) {
        successBack(file)
      }
      return true
    } else {
      if (!BaseTool.Object.isBlank(errorFun)) {
        errorFun()
      } else {
        message.error(`请上传正确的word、pdf、docx、zip、xls、xlsx文件`)
      }
      // reject(new Error('请上传正确的word文件或pdf文件'))
      return new Promise((resolve, reject) => {
        reject(new Error('请上传正确的word、pdf、docx、zip、xls、xlsx文件'))
        return false
      })
    }
  },
  /**
   * 上传文件校验是否为图片
   * @param file
   * @param successBack
   * @param errorFun
   * @returns {Promise<boolean>|boolean}
   */
  isImageUpload (file, successBack, errorFun) {
    const reg = /\.(jpeg|jpg|png|gif)(\?.*)?$/
    if (reg.test(file.name)) {
      if (!BaseTool.Object.isBlank(successBack)) {
        successBack(file)
      }
      return true
    } else {
      if (!BaseTool.Object.isBlank(errorFun)) {
        errorFun()
      } else {
        message.error(`请上传正确的图片`)
      }
      // reject(new Error('请上传正确的word文件或pdf文件'))
      return new Promise((resolve, reject) => {
        reject(new Error('请上传正确的图片'))
        return false
      })
    }
  },
  downLoadExportExcel (data) {
    const contentDistribution = data.headers['content-disposition']
    // attachment;filename=%E6%8A%95%E8%B5%84%E9%A1%B9%E7%9B%AE%E4%BF%A1%E6%81%AF20200202162009965.xls
    const fileName = decodeURI(contentDistribution.replace('attachment;filename=', ''))
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(data, fileName)
    }
    const blob = new Blob([data.data])
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)// 释放 URL 对象
    document.body.removeChild(elink)
  },
  transImg (imgArr = []) {
    const temp = []
    if (BaseTool.Object.isBlank(imgArr)) {
      return temp
    }
    imgArr.forEach((item) => {
      if (BaseTool.String.isNotBlank(item.url)) {
        temp.push({
          url: GlobalConstant.BaseImageUrl + item.url,
          uid: item.id,
          name: item.name,
          value: item
        })
      }
    })
    return temp
  },
  filePreview (file) {
    if (file.url == null) {
      return
    }
    window.open(process.env.VUE_APP_PREVIEW_URL + BaseTool.Constant.HOST + BaseTool.Constant.FILE_URL + file.url)
  },
  getUploadFileDTO (fileList = [], type = Number) {
    // 添加图片
    const length = fileList.length
    const temp = []
    if (length >= 1) {
      for (let i = 0; i < length; i++) {
        let data = {}
        if (fileList[i].response) {
          data = fileList[i].response.data
        } else {
          data = fileList[i].value
        }
        const fileDTO = {}
        fileDTO.type = type
        fileDTO.name = data.name
        fileDTO.fileName = data.fileName
        fileDTO.fileFormat = data.fileFormat
        fileDTO.url = data.url
        temp.push(fileDTO)
      }
    }
    return temp
  },
  getUploadOneFileDTO (file, type = Number) {
    // 添加图片
    const temp = []
    if (file != null) {
      let data = {}
      if (file.response) {
        data = file.response.data
      } else {
        data = file
      }
      const fileDTO = {}
      fileDTO.type = type
      fileDTO.name = data.name
      fileDTO.fileName = data.fileName
      fileDTO.fileFormat = data.fileFormat
      fileDTO.url = data.url
      temp.push(fileDTO)
    }
    return temp
  },
  handleFileChange ({ file, fileList }) {
    const result = {}
    result.defaultFileList = fileList
    result.success = false
    if (file.status === 'done') {
      result.fileList = BaseTool.UPLOAD.getUploadFileDTO(fileList, GlobalConstant.FileTypeFile)
      result.success = true
    } else if (file.status === 'removed') {
      result.fileList = BaseTool.UPLOAD.getUploadFileDTO(fileList, GlobalConstant.FileTypeFile)
      result.success = true
    } else if (file.status === 'error') {
      message.error('上传失败')
    }
    return result
  },
  handleImageChange ({ file, fileList }) {
    const result = {}
    result.defaultImageList = fileList
    result.success = false
    if (file.status === 'done') {
      result.imageList = BaseTool.UPLOAD.getUploadFileDTO(fileList, GlobalConstant.FileTypeImg)
      result.success = true
    } else if (file.status === 'removed') {
      result.imageList = BaseTool.UPLOAD.getUploadFileDTO(fileList, GlobalConstant.FileTypeImg)
      result.success = true
    } else if (file.status === 'error') {
      message.error('上传失败')
    } else {
    }
    return result
  }
}

BaseTool.Util = {
  _isMobile () {
    const flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag
  },
  getToken (url) {
    return getToken(url)
  },
  /**
   * 页面合并单元格
   * @param mergeMap ：合并信息对象
   * @param keys ：获取的key
   * @returns {{}|number} :
   */
  getSpan (mergeMap = {}, ...keys) {
    if (mergeMap == null) {
      return 1
    }
    let map = mergeMap
    for (let i = 0; i < keys.length; i++) {
      if (map[keys[i]] == null) {
        return 1
      }
      map = map[keys[i]]
    }
    return map
  },
  /**
   * 根据不同类型获取行数据
   * @param record ：
   * @param key ：
   * @returns {string|*}
   */
  getRecordText (record, key) {
    let result = ''
    if (record.data == null) {
      return ''
    }
    if (record.type === 1) {
      result = record.data[key]
    } else {
      if (record.data[key] == null) {
        return ''
      }
      result = record.data[key]['data']
    }
    return result
  },
  /**
   * 获取携带合并单元格的行数据
   * @param record ：
   * @param key ：
   * @returns {{children: null, attrs: {rowSpan: ({}|number), colSpan: ({}|number)}}}
   */
  getCustomRender (record, key) {
    const obj = {
      children: null,
      attrs: {
        rowSpan: this.getSpan(record['mergeMap'], key, 'rowSpan'),
        colSpan: this.getSpan(record['mergeMap'], key, 'cellSpan')
      }
    }

    obj.children = this.getRecordText(record, key)
    return obj
  },
  /**
   * 获取携带合并单元格的行数据 ,并对类型进行格式化
   * @param record ：
   * @param key ：
   * @param type: 1表示string 2表示格式化金额   3表示万元之后格式金额
   * @returns {{children: null, attrs: {rowSpan: ({}|number), colSpan: ({}|number)}}}
   */
  getCustomRenderFormat (record, key, type) {
    const obj = {
      children: null,
      attrs: {
        rowSpan: this.getSpan(record['mergeMap'], key, 'rowSpan'),
        colSpan: this.getSpan(record['mergeMap'], key, 'cellSpan')
      }
    }
    let result = this.getRecordText(record, key)
    if (type === 2) {
      result = BaseTool.Amount.formatter(result)
    }
    if (type === 3) {
      result = BaseTool.Amount.divTenThousandFormatter(result)
    }
    obj.children = result
    return obj
  },
  getCustomRenderMultiDictValue (text, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    const values = text.split(',')
    const texts = new Array()
    values.forEach((item, index, array) => {
      texts.push(dictMap[item])
    })
    return texts.join(',')
  },
  getCustomRenderDictValue (text, dictMap) {
    if (BaseTool.Object.isBlank(text)) {
      return ''
    }
    return dictMap[text]
  }
}

BaseTool.TREE = {
  treeFilter (list = [], f = (item) => { return item }) {
    const r = []
    list.forEach(item => {
      if (item.children && item.children.length > 0) {
        item.children = this.treeFilter(item.children, f)
      }
      const i = f(item)
      if (i) {
        if (!i.delete) {
          r.push(i)
        }
      } else {
        r.push(item)
      }
    })
    return r
  }
}

BaseTool.ANTD = {
  selectFilterOption (input, option) {
    return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }
}

export default BaseTool
