package ${basePackage}.action.ajax.system;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import ${basePackage}.frame.base.BaseResponse;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.base.FileUploadResponse;

import javax.swing.tree.TreeNode;
import java.io.IOException;
import java.net.URLEncoder;

public class FileAjax {

    public Object upload(MultipartFile file) {
        FileUploadResponse fileUploadResponse = new FileUploadResponse();
        String fileName = file.getOriginalFilename();

        //========
        // todo 处理文件
        //========
        fileUploadResponse.setId(1L);
        fileUploadResponse.setUrl("example.com\\img\\1.jpg");
        fileUploadResponse.setDownloadUrl("example.com\\img\\1.jpg");

        if (file != null) {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传成功,但未处理文件[" + fileName + "]!");
        } else {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传失败!");
        }

        return fileUploadResponse;
    }

    public Object download(TreeNode jsonParam) {
        try {
            //========
            // todo 下载示例
            //========
            byte[] bytes = "test".getBytes();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode("example.test", "utf-8"));
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "");
            return baseResponse;
        }
    }
}
