import Vue from 'vue'
import { export_json_to_excel } from './exportExcel'
import store from '../store'
import _ from 'lodash'
import { filePath, get, post } from './axios'
import { get_options, upload_other_file, upload_img } from './api'

/**
 *
 * @param {array}  params vuex字段名
 * @param {Function} callback
 */
export function getOptionData(params, callback) {
  if (!Array.isArray(params)) {
    params = [params]
  }
  params.forEach((name) => {
    const list = store.state[name]
    if (list.length > 0) {
      return callback && callback(list, name)
    }
    get_options(name)
      .then((res) => {
        const data = res.data
        store.dispatch('setState', { [name]: data })
        callback && callback(data, name)
      })
      .catch((err) => {
        console.log(err)
      })
  })
}

/**
 * 获取表格展示项
 * @param {*} name
 * @param {*} cb
 * @returns
 */
export const getColumn = (name, cb) =>
  get('sysLogin/getColumn', { reqMenu: name })
    .then((res) => {
      if (res.code === 200) {
        cb && cb(res.data)
      } else {
        this.$alert(res.message, '错误提示', {
          dangerouslyUseHTMLString: true,
        })
      }
    })
    .catch((err) => console.log(err))
/**
 * 获取权限表格展示项
 * @param {*} type
 * @param {*} cb
 * @returns
 */
export function getSysColumns(type, cb) {
  return get('sysDataRole/findRoleColumns/' + type).then((res) => {
    if (res.code === 200) {
      if (res.data.length <= 0) {
        Vue.prototype.$message({ type: 'warning', message: '暂无数据权限' })
        return
      }
      let list = res.data.map(
        ({ name, value, width, sortable, custom, align, columnName }) => ({
          label: name,
          key: value,
          custom,
          width,
          columnName,
          sortable: sortable ? 'custom' : false,
          show: true,
          align,
        })
      )
      cb && cb(list)
    }
  })
}

/**
 * 辅助字典
 * @param {*} code
 * @param {*} cb
 */
export function getDictionaryByCode(code, cb) {
  get('baseDictData/findDictByCode/' + code)
    .then((res) => {
      if (res.code == 200) {
        cb && cb(res.data)
      }
    })
    .catch(() => {})
}
/**
 * 订单驳回
 * @param {*} type
 * @param {*} arr
 * @param {*} cb
 */
export function rejectOrder(type, arr, cb) {
  let status = ''
  switch (type) {
    case 0: //待派单
      status = 1
      break
    case 1: //已派单
      status = 2
      break
    case 2: // 待拣货
      status = 5
      break
    case 3: // 待打单
      status = 6
      break
    case 4: // 待验货
      status = 7
      break
    case 5: // 待称重
      status = 8
      break
    case 6: // 待发货
      status = 9
      break
  }
  let ids = arr.map((v) => {
    return v.id
  })
  ids = ids.join()
  Vue.prototype
    .$prompt('', '驳回', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '驳回原因',
      inputPattern: /.+/,
      customClass: 'reject',
      inputErrorMessage: '请输入驳回原因',
    })
    .then(({ value }) =>
      get('orderDetails/rejectTo', { ids, status, reasonStr: value }).then(
        (res) => {
          if (res.code === 200) {
            cb && cb()
          }
        }
      )
    )
}
/** 清空本地 */
export function clearlocal() {
  const arr = ['token', 'userinfo', 'menulist', 'tags', 'tagsIndex', 'home']
  arr.forEach((key) => localStorage.removeItem(key))
  sessionStorage.clear()
  console.log('clearlocal')
}
/**
 *
 * @param {*} url
 * @param {*} data
 */
export function serveExportExcel(url, data) {
  post(url, data).then((res) => {
    window.open(filePath + res.message)
  })
}
/**
 *
 * @param {*} obj
 */
export function setRootStyle(obj) {
  for (const key in obj) {
    if (key === '--background-image') {
      document.documentElement.style.setProperty(key, `url('${obj[key]}')`)
    } else {
      document.documentElement.style.setProperty(key, obj[key])
    }
  }
}
/**
 * 清除 children
 * @param {*} list
 * @param {*} callback
 * @param {*} name
 * @returns
 */
export function delChildren(list, callback, name) {
  let key = name || 'children'
  function recursive(list, callback, index) {
    for (const iterator of list) {
      callback && callback(iterator, index)
      if (iterator.children.length > 0) {
        recursive(iterator.children, callback, index + 1)
      } else {
        delete iterator[key]
      }
    }
  }

  recursive(list, callback, 0)
  return list
}
/**
 * 数组为空校验
 * @param {*} arr
 */
export function emptyArray(arr, message) {
  if (arr.length === 0) {
    Vue.prototype.$message.warning(message || '请至少选择一条记录')
    return true
  } else {
    return false
  }
}
/**
 * 获取id
 * @param {Array} arr
 * @param {Boolean} isStr
 */
export function getIds(arr, isStr) {
  let idList = arr.map((v) => v.id)
  isStr && (idList = idList.join())
  return idList
}
/**
 *
 * @param {*} filterVal
 * @param {*} jsonData
 */
function formatJson(filterVal, jsonData) {
  return jsonData.map((v) =>
    filterVal.map((j) => {
      if (typeof v[j] === 'object' && v[j]) {
        console.log(j, v[j])

        return v[j].desc
      } else {
        return v[j]
      }
    })
  )
}
/**
 * 获取打印内容并打印
 * @param {*} res
 */
export function getExcel(head, columns, res) {
  console.log(head, columns, res)
  require.ensure([], () => {
    const data = formatJson(columns, res)
    export_json_to_excel(
      head,
      data,
      'EXPORT' + Vue.prototype.$moment().format('YYYY_MM_DD_HH_mm_ss')
    )
  })
}
/**
 * 根据权限过滤导出参数
 * @param {} arr
 * @param {*} permissions
 */
export function exportOptions(arr, permissions) {
  let headOption = []
  let columnsOption = []
  if (permissions) {
    for (const iterator of arr) {
      if (iterator.show) {
        columnsOption.push(iterator.key)
        headOption.push(iterator.label)
      }
    }
  } else {
    for (const iterator of arr) {
      console.log(iterator.type, Boolean(iterator.type))
      if (iterator.type) {
        continue
      }
      columnsOption.push(iterator.key)
      headOption.push(iterator.label)
    }
  }

  console.log(headOption, columnsOption)

  return {
    headOption,
    columnsOption,
  }
}
const fileTypes = {
  img: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
  excel: ['.xls', '.xlsx'],
  json: ['json'],
  txt: ['txt'],
}
function imgSizeCheck(file, params) {
  return new Promise((resolve) => {
    const img = new Image()
    img.src = URL.createObjectURL(file)
    img.onload = function () {
      let width = img.width
      let height = img.height
      if (width < params.minWidth || height < params.minHeight) {
        Vue.prototype.$message.warning(
          `请上传宽大于${params.minWidth}高大于${params.minHeight}的图片`
        )
        resolve(false)
      } else {
        resolve(true)
      }
    }
  })
}
/**
 * 上传文件
 * @param {Object} params 参数
 * @param {String} params.url - 导入excel使用 图片不用
 * @param {String} params.name - 导入excel使用 图片不用
 * @param {String} params.filePath - 文件路径
 * @param {Boolean} params.multiple - 多选
 * @param { 'img' | 'excel' | 'json' | Array} params.type - 文件类型
 * @param {String} params.message - 提示信息
 * @param {Number} params.minWidth - 最小宽度
 * @param {Number} params.minHeight - 最小高度
 * @param {Number} params.other - 其他参数
 * @returns  Promise
 */
export function input_file(params = {}) {
  return new Promise((resolve, reject) => {
    const input = document.createElement('input')
    input.style.display = 'none'
    input.type = 'file'
    input.multiple = params.multiple || false
    input.click()
    input.onchange = async () => {
      console.log(input.files)
      const files = input.files
      const requset = []
      for (const file of files) {
        console.log(file)
        //文件类型校验
        let type = params.type || 'img',
          fileType = []
        if (typeof type === 'string') {
          fileType = fileTypes[type]
        } else {
          fileType = type
        }

        const typeExp = fileType.map((item) =>
          typeof item === 'object' ? item : new RegExp(item)
        )
        const bool = typeExp.some(
          (item) => item.test(file.name) || item.test(file.type)
        )
        if (!bool) {
          Vue.prototype.$message({
            type: 'warning',
            message: params.message || `请上传${fileType.join('、')}格式文件`,
          })
          return
        }
        // 文件大小校验
        // if (file.size / 1024 / 1024 > 3) {
        //   setTimeout(() => {
        //     Vue.prototype.$message.warning(`${file.name}文件大于3M`)
        //   }, 0);
        //   continue
        // }
        // 宽高校验
        if (params.minWidth && params.minHeight) {
          let res = await imgSizeCheck(file, params)
          if (!res) return
        }
        if (
          params.type === 'excel' ||
          params.type === 'json' ||
          params.type === 'txt'
        ) {
          const other = params.other || {}
          if (params.multiple) {
            requset.push(
              upload_other_file({
                url: params.url,
                name: params.name || 'importExcel',
                file: file,
                ...other,
              })
            )
          } else {
            upload_other_file({
              url: params.url,
              name: params.name || 'importExcel',
              file: file,
              ...other,
            })
              .then(resolve)
              .catch(reject)
          }
        } else {
          if (params.multiple) {
            requset.push(
              upload_img(file, {
                filePath: params.filePath,
                multiple: params.multiple,
              })
            )
          } else {
            upload_img(file, {
              filePath: params.filePath,
              multiple: params.multiple,
            })
              .then(resolve)
              .catch(reject)
          }
        }
      }
      if (requset.length > 0) {
        Promise.all(requset).then(resolve).catch(reject)
      }
    }
  })
}

function csvToArray(text) {
  let p = '',
    row = [''],
    ret = [row],
    i = 0,
    r = 0,
    s = !0,
    l
  for (l of text) {
    if ('"' === l) {
      if (s && l === p) row[i] += l
      s = !s
    } else if (',' === l && s) l = row[++i] = ''
    else if ('\n' === l && s) {
      if ('\r' === p) row[i] = row[i].slice(0, -1)
      row = ret[++r] = [(l = '')]
      i = 0
    } else row[i] += l
    p = l
  }
  return ret
}
export function import_csv(callback, head) {
  let input = document.createElement('input')
  input.style.display = 'none'
  input.type = 'file'
  input.onchange = function () {
    const files = this.files[0]
    if (files.name.indexOf('.csv') === -1) {
      Vue.prototype.$message.warning('请上传.CSV格式的文件')
      return
    }
    const datas = []
    const fileReader = new FileReader()
    fileReader.onload = function (ev) {
      try {
        const result = ev.target.result
        const csvarry = csvToArray(result)
        const headers = csvarry[0]
        if (head) {
          for (const iterator of head) {
            if (!headers.includes(iterator)) {
              Vue.prototype.$message.warning(`'${iterator}' 列不存在`)
              return
            }
          }
        }

        for (var i = 1; i < csvarry.length; i++) {
          const data = {}
          const temp = csvarry[i]
          let isNull = false
          for (var j = 0; j < temp.length; j++) {
            if (temp[j]) isNull = true
            data[headers[j]] = temp[j].trim()
          }
          isNull && datas.push(data)
        }
      } catch (e) {
        console.log(e)
        console.log('文件类型不正确')
        Vue.prototype.$message.warning('文件类型不正确')
        return
      }
      console.log(datas)
      callback && callback(datas)
    }
    fileReader.readAsText(files)
  }
  input.click()
}
const imgTools = {
  show: false,
  mouseoverImg(ev, url) {
    window.event ? (window.event.cancelBubble = true) : ev.stopPropagation()
    ev.preventDefault()
    if (this.show === true) return
    let imgView = document.querySelector('#imgView')
    let img = document.querySelector('#imgView img')
    img.src = url
    let cW = document.body.clientWidth
    let cH = document.body.clientHeight
    let cX = ev.clientX
    let cY = ev.clientY
    let x, y
    if (cY + 380 >= cH) y = cY - 440
    else y = cY - 30
    if (cX + 440 >= cW) x = cX - 440
    else x = cX + 30
    img.onload = () => {
      imgView.style.left = x + 'px'
      imgView.style.top = y + 'px'
      imgView.style.display = 'block'
      this.show = true
    }
  },
  mouseleaveImg() {
    if (this.show === false) return
    let imgView = document.querySelector('#imgView')
    if (imgView) {
      imgView.style.display = 'none'
      this.show = false
    }
  },
}
export default imgTools

function itemIsArray(obj) {
  for (const key in obj) {
    if (Array.isArray(obj[key])) {
      return true
    }
  }
  return false
}
function isChange(arr, arr1) {
  if (!arr1) return true
  if (arr.length !== arr1.length) return true
  for (const iterator of arr) {
    const item = arr1.find((item) => item.id === iterator.id)
    if (!item) return true
  }
  return false
}
/**
 * 更新参数处理 只提交更新的
 * @param {*} newParams 新的数据
 * @param {*} oldParams 旧的数据
 * @param {*} id 数组唯一值
 */
export function checkUpdateParams(newParams, oldParams, id = 'id', other = {}) {
  console.log(newParams, oldParams)
  oldParams = JSON.parse(JSON.stringify(oldParams))
  if (!oldParams) return newParams
  if (newParams?.id !== oldParams?.id) return newParams
  const params = {
    id: newParams.id,
  }
  for (const key in newParams) {
    if (typeof newParams[key] === 'object') {
      if (Array.isArray(newParams[key])) {
        const arr = newParams[key]
        const arr1 = oldParams[key] || []
        const addList = []
        const updateList = []
        let removeList = []
        let list = []

        const keyname = other[key] || id
        for (const iterator of arr) {
          const obj = {}

          const index = arr1.findIndex(
            (item) => item[keyname] === iterator[keyname]
          )
          let isArray = itemIsArray(iterator)
          if (index !== -1) {
            const item = arr1[index]
            arr1.splice(index, 1)

            for (const key1 in iterator) {
              if (key1 === keyname) continue
              if (Array.isArray(iterator[key1])) {
                if (isChange(iterator[key1], item[key1])) {
                  obj[key1] = iterator[key1]
                }
              } else if (iterator[key1] !== item[key1]) {
                obj[key1] = iterator[key1]
              }
            }
            if (Object.keys(obj).length > 0) {
              if (isArray) {
                list.push({
                  [keyname]: iterator[keyname],
                  ...obj,
                  id: item.id,
                })
              } else {
                updateList.push({
                  [keyname]: iterator[keyname],
                  ...obj,
                  id: item.id,
                })
              }
            }
          } else {
            if (isArray) {
              list.push(iterator)
            } else {
              addList.push(iterator)
            }
          }
        }
        if (arr1.length > 0) {
          removeList = arr1.map((item) => item['id'])
        }

        let key_name = key.replace('List', 'Change')

        params[key_name] = {}
        if (addList.length > 0) {
          params[key_name].addList = addList
        }
        if (updateList.length > 0) {
          params[key_name].updateList = updateList
        }
        if (removeList.length > 0) {
          params[key_name].removeList = removeList
        }
        if (list.length > 0) {
          params[key_name] = list
        }
        if (Object.keys(params[key_name]).length === 0) {
          delete params[key_name]
        }
      }
    } else {
      if (newParams[key] !== oldParams[key]) {
        params[key] = newParams[key]
      }
    }
  }
  if (Object.keys(params).length === 1) {
    return null
  }
  return params
}

export function saveTag(tags, tagsIndex) {
  store.dispatch('setState', {
    tags,
    tagsIndex,
  })
  sessionStorage.setItem('tagsIndex', tagsIndex)
  sessionStorage.setItem('tags', JSON.stringify(tags))
}
export function getmenuName(path) {
  const menulist = JSON.parse(localStorage.getItem('menulist'))

  function getName(list, path) {
    for (const iterator of list) {
      if (iterator.path === path) {
        return iterator.name
      }
      if (iterator.children && iterator.children.length > 0) {
        const name = getName(iterator.children, path)
        if (name) {
          return name
        }
      }
    }
  }
  if (menulist) {
    return getName(menulist, path)
  } else {
    return ''
  }
}
/**
 * tag 添加
 * @param {*} tag
 * @returns
 */
export function addTag(tag) {
  let { tags, tagsIndex } = store.state
  const obj = tag
  if (!obj) return
  if (!obj.title) {
    obj.title = getmenuName(obj.name)
  }
  if (!obj.title || !obj.name) return
  const index = tags.findIndex(
    (item) => item.name === obj.name || item.title === obj.title
  )
  if (index !== -1) {
    store.dispatch('setState', {
      tagsIndex: index,
    })
    return
  }

  if (tags.length === 10) {
    tags.splice(1, 1)
    tags.push(obj)
  } else {
    tags.push(obj)
    tagsIndex = tags.length - 1
  }
  saveTag(tags, tagsIndex)
}
export function addnumber(num1, num2, operator) {
  let num = 0
  num1 = Number(num1)
  num2 = Number(num2)
  if (isNaN(num1) || isNaN(num1)) {
    return 'NaN'
  }
  if (operator === '*') {
    num = _.multiply(num1, num2)
  } else if (operator === '/') {
    num = _.divide(num1, num2)
  } else if (operator === '+') {
    num = _.add(num1, num2)
  } else if (operator === '-') {
    num = _.subtract(num1, num2)
  }
  return num.toFixed(2)
}

export function isMobile() {
  if (
    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 true
  } else {
    return false
  }
}
/**
 * 根据id获取多维数组的某一项
 */

/**
 *
 * @param {*} id
 * @param {*} arr
 * @param {*} name 子集key
 * @param {*} key 对比的key
 * @returns
 */
export function getArraysItem(id, arr, name, key) {
  if (!name) name = 'children'
  if (!key) key = 'id'
  for (const iterator of arr) {
    if (iterator[key] === id) {
      return iterator
    }
    if (iterator[name] && iterator[name].length > 0) {
      const item = getArraysItem(id, iterator[name], name, key)
      if (item) {
        return item
      }
    }
  }
}
//多维数组变一维数组
export function dimensionConversion(clist) {
  let arr = []
  const func = (list) => {
    list.forEach((item) => {
      if (typeof item === 'object') {
        func(item)
      } else {
        if (!arr.includes(item)) {
          arr.push(item)
        }
      }
    })
  }
  if (clist) {
    func(clist)
  }
  return arr
}

// 一维转多维
export function dimensionalRotation(ids, vlist, name) {
  let newarr = []
  let key = name || 'id'
  function func(list, arr, index) {
    for (let i = 0, l = list.length; i < l; i++) {
      let currentArr = [...arr]

      const iterator = list[i]
      if (ids.includes(iterator[key])) {
        currentArr.push(iterator[key])
        // let length = currentArr.length
        if (iterator.children) {
          func(iterator.children, currentArr, index + 1)
        } else {
          currentArr.length > 0 && newarr.push(currentArr)
        }
      }
    }
  }
  if (ids) {
    let clist = vlist

    // let currentIndex = 0
    // let arr =[]

    func(clist, [], 0)
    console.log(newarr)
    return newarr
  } else {
    return newarr
  }
}

/**
 * 获取父级
 * @param {*} list
 * @param {*} value
 * @param {*} options
 * @returns  object
 */
export function getAncestorItem(list, value, options = {}) {
  const key = options.key || 'id'
  const level = options.level || 0
  const children = options.children || 'children'

  for (const iterator of list) {
    let arr = []
    arr[0] = iterator
    if (iterator[key] === value) {
      return arr[level][key]
    }
    if (iterator[children] && iterator[children].length > 0) {
      for (const iterat of iterator[children]) {
        arr[1] = iterat
        if (iterat[key] === value) {
          return arr[level][key]
        }
        if (iterat[children] && iterat[children].length > 0) {
          for (const itera of iterat[children]) {
            arr[2] = itera
            if (itera[key] === value) {
              return arr[level][key]
            }
          }
        }
      }
    }
  }
}
// 表格字段转换
export function sysColumnsTransform(columns) {
  return columns.map(({ name, value, width, sortable, custom, align }) => ({
    label: name,
    key: value,
    custom,
    width,
    sortable,
    show: true,
    align,
  }))
}
/**
 * 重置参数
 * @param {*} params
 */
export function resetParams(params) {
  for (const key in params) {
    if (Array.isArray(params[key])) {
      params[key] = []
    } else if (typeof params[key] === 'string') {
      params[key] = ''
    } else if (typeof params[key] === 'number') {
      params[key] = 0
    } else if (typeof params[key] === 'boolean') {
      params[key] = false
    } else if (typeof params[key] === 'object') {
      params[key] = {}
    } else {
      params[key] = ''
    }
  }
}
