import axios from 'axios'
import router from '@/router'
import store from '@/store'

/*
  获取文件后缀
*/
export function getfilesuffix (file) {
  //获取文件的后缀名的位置
  var index = file.name.lastIndexOf(".");
  if (index == -1) {
    return false;
  }
  //截取后缀名
  var type = file.name.substring(index + 1);
  return type
}

/*
  文件上传
*/
export function uploadformData (url, formData, progress) {
  return new Promise((resolve, reject) => {
    axios({
      method: "post",
      url: url,
      headers: { 'X-Token': store.getters.token },
      data: formData,
      onUploadProgress: (evt) => {
        if (evt.lengthComputable) {
          var percent = Math.round(evt.loaded * 100 / evt.total);
          if (progress != null) {
            progress(percent)
          }

        }
        else {
          if (progress != null) {
            progress(100)
          }
        }
      }
    }).then(response => {
      const status = response.status
      const res = response.data
      console.log('response:%o', response)
      if (status === 200) {
        if (res.code != 0) {
          if (res.code === 101) {
            router.replace('/login')
            return
          }
          return reject(new Error("exception code:" + res.code))
        } else {
          return resolve(res)
        }
      } else {
        return reject(new Error("exception status:" + status))
      }
    }).catch(err => {
      reject(err)
    })
  })
}

///校验文件格式
export function validateFileType (files, types) {
  if (files == null || types == null) {
    return false
  }
  for (var i = 0; i < files.length; i++) {
    var file = files[i]
    if (file.name == "" || file.name == null) {
      return false;
    }
    //获取文件的后缀名的位置
    var index = file.name.lastIndexOf(".");
    if (index == -1) {
      return false;
    }
    //截取后缀名
    var type = file.name.substring(index + 1);
    for (var i = 0; i < types.length; i++) {
      if (type == types[i]) {
        return true
      }
    }
    return false
  }
}
