package com.railway.web.controller.common;

import com.railway.common.core.domain.AjaxResult;
import com.railway.common.utils.StringUtils;
import com.railway.common.utils.file.FileUtils;
import com.railway.system.service.ISysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用请求处理
 *
 * @author railway
 */
@Api(tags = "通用请求接口")
@Slf4j
@RestController
public class CommonController {

  private final ISysFileService sysFileService;

  private static final String FILE_DELIMETER = ",";

  public CommonController(ISysFileService sysFileService) {
    this.sysFileService = sysFileService;
  }

  /**
   * 通用上传请求（单个）
   */
  @ApiOperation(value = "通用上传请求（单个）")
  @PostMapping("/common/upload")
  @ResponseBody
  public AjaxResult uploadFile(MultipartFile file) {
    try {
      // 上传并返回访问地址
      String url = sysFileService.uploadFile(file);
      return AjaxResult.uploadFile(url, file.getOriginalFilename());
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    }
  }

  /**
   * 通用上传请求（多个）
   */
  @ApiOperation(value = "通用上传请求（多个）")
  @PostMapping("/common/uploads")
  @ResponseBody
  public AjaxResult uploadFiles(List<MultipartFile> files) {
    try {
      List<String> fileNames = new ArrayList<>();
      List<String> urls = new ArrayList<>();
      for (MultipartFile file : files) {
        // 上传并返回访问地址
        String url = sysFileService.uploadFile(file);
        // 新文件名称
        String fileName = FileUtils.getName(url);
        fileNames.add(fileName);
        urls.add(url);
      }
      AjaxResult ajax = AjaxResult.success();
      ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
      ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
      return ajax;
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    }
  }

}
