import Vue from 'vue'
import { uploadOtherFile, uploadImg } from './api'
function getStaticPath() {
  if (
    !/(http|https):\/\/([^/]+)/i.test(window.apiHostSetting.VUE_APP_BASE_URL)
  ) {
    return location.origin + window.apiHostSetting.VUE_APP_BASE_URL
  }
  return window.apiHostSetting.VUE_APP_BASE_URL
}
export const isMobile = () => window.innerWidth <= 1100
// zimg图片服务器地址
export const zImgPath = window.apiHostSetting.VUE_APP_ZIMG_URL
// 文件存储路径地址
export const filePath = getStaticPath() + 'upload/erp'

export function delChildren(list, callback, name) {
  const 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
}
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 () {
      const width = img.width
      const height = img.height
      if (width < params.minWidth || height < params.minHeight) {
        Vue.prototype.$message.warning(
          `请上传宽大于${params.minWidth}高大于${params.minHeight}的图片`
        )
        resolve(false)
      } else {
        resolve(true)
      }
    }
  })
}
export function inputFile(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) {
        // 添加类型后缀校验
        if (params.limit) {
          let etc = file.name.split('.')[file.name.split('.').length - 1]
          etc = etc.toLowerCase()
          if (!params.limit.includes(etc)) {
            return Vue.prototype.$message.error(
              `请上传${params.limit.join(',')}文件`
            )
          }
        }
        // 大小校验
        if (params.isSize) {
          const size = file.size
          if (!params.sizeLimit) params.sizeLimit = 10
          if (size / (1024 * 1024) >= params.sizeLimit) {
            return Vue.prototype.$message.error(
              `文件大小不能大于等于${params.sizeLimit}M`
            )
          }
        }
        // 文件类型校验
        if (!params.noType) {
          const type = params.type || 'img'
          let 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 (params.minWidth && params.minHeight) {
          const 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(
              uploadOtherFile({
                url: params.url,
                name: params.name || 'importExcel',
                file: file,
                ...other
              })
            )
          } else {
            uploadOtherFile({
              url: params.url,
              name: params.name || 'importExcel',
              file: file,
              ...other
            })
              .then(resolve)
              .catch(reject)
          }
        } else {
          const other = params.other || {}
          if (params.multiple) {
            requset.push(
              uploadImg(file, {
                filePath: params.filePath,
                isSize: params.isSize,
                multiple: params.multiple,
                url: params.url,
                businessType: params.businessType
              })
            )
          } else {
            uploadImg(file, {
              filePath: params.filePath,
              url: params.url,
              isSize: params.isSize,
              businessType: params.businessType,
              ...other
            })
              .then(resolve)
              .catch(reject)
          }
        }
      }
      if (requset.length > 0) {
        Promise.all(requset).then(resolve).catch(reject)
      }
    }
  })
}
