package com.railway.system.service.impl;

import com.railway.common.constant.Constants;
import com.railway.common.core.domain.AjaxResult;
import com.railway.common.utils.StringUtils;
import com.railway.common.utils.file.FileUploadUtils;
import com.railway.common.utils.file.FileUtils;
import com.railway.system.service.ISysFileService;
import java.io.File;

/**
 * @author zhaomn
 */
public abstract class AbstractFileService implements ISysFileService {

  /**
   * 本地文件上传到文件服务器
   *
   * @param localFilePath 本地文件路径
   * @return 上传结果
   */
  @Override
  public AjaxResult uploadFile(String localFilePath) {
    if(StringUtils.isEmpty(localFilePath)){
      return AjaxResult.error("文件保存到文件服务器失败");
    }
    File localFile = new File(localFilePath);
    String fileName = localFile.getName();
    if(fileName.indexOf(Constants.UNDERLINE) > 0){
      fileName = fileName.substring(fileName.lastIndexOf(Constants.UNDERLINE) + 1);
    }
    try {
      String url = uploadFile(FileUploadUtils.upload(localFile));
      AjaxResult ajax = AjaxResult.uploadFile(url, fileName);
      FileUtils.deleteFile(localFilePath);
      return ajax;
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    }
  }
}
