package com.bonus.canteen.core.common.sysfile.controller;

import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.canteen.core.common.core.util.Base64DecodedMultipartFile;
import com.bonus.canteen.core.common.enums.FileNameSuffixEnum;
import com.bonus.canteen.core.common.enums.FileUploadSourceEnum;
import com.bonus.canteen.core.common.sysfile.dto.SysFileUploadDTO;
import com.bonus.canteen.core.common.sysfile.service.SysFileService;
import com.bonus.canteen.core.common.sysfile.vo.SysFileUploadVO;
import com.bonus.common.houqin.encrypt.RequiresGuest;
import com.bonus.common.houqin.utils.LeRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping({"/api/v1/sysfile"})
@Api(
   value = "sysfile",
   tags = {"文件管理"}
)
public class SysFileController{
   private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
   private final SysFileService sysFileService;


   @PostMapping({"/upload/base64"})
   @RequiresGuest
   @ApiOperation("base64文件上传")
   public AjaxResult upload(@RequestBody @Valid SysFileUploadDTO dto) {
      MultipartFile file = Base64DecodedMultipartFile.base64ToMultipart(dto.getBase64File());
      String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
      if (!FileNameSuffixEnum.getAllFileNameList().contains(suffix.toUpperCase())) {
         return AjaxResult.error("接收参数错误,请上传正确的文件格式");
      } else {
         String uploadKey = dto.getUploadKey();
         List<String> uploadKeyList = FileUploadSourceEnum.getAllEnumsKeyList();
         if (!uploadKeyList.contains(uploadKey)) {
            return AjaxResult.error("目前只支持指定文件路径的上传,请重试 ^_^");
         } else {
            SysFileUploadVO result = this.sysFileService.uploadFile(file, uploadKey);
            return AjaxResult.success("上传成功", result);
         }
      }
   }

   public SysFileController(final SysFileService sysFileService) {
      this.sysFileService = sysFileService;
   }
}
