import { isString } from 'lodash'
import axios from './axios'
/**
 * 允许上传文件时，中途删除文件
 * @param file file
 * @returns
 */
/* eslint-disable no-param-reassign */
export const onBeforeRemove = (file: any) => {
  return new Promise<boolean>((RES) => {
    file.status = 'uploading'
    file.percent = 0.0
    const timer = setInterval(() => {
      file.percent += 0.1
      if (file.percent >= 0.9) {
        clearInterval(timer)
      }
    }, 40)
    let filename
    if (file.response && file.response.filename) {
      filename = file.response.filename
    }
    if (isString(filename)) {
      axios
        .post(`/sys/file/del/${filename}`)
        .then(() => {
          file.percent = 1
          setTimeout(() => {
            clearInterval(timer)
            RES(true)
          }, 100)
        })
        .catch(() => {
          file.status = 'done'
          file.percent = 0.0
          clearInterval(timer)
          RES(false)
        })
      return
    }
    RES(true)
  })
}
