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

import ${basePackage}.frame.auth.LocalData;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.utils.MapperUtil;
import ${basePackage}.frame.utils.Base64Util;
import ${basePackage}.module.system.mgr.FileManager;
import ${basePackage}.module.system.req.FileCreateRequest;
import ${basePackage}.module.system.req.FileGetRequest;
import ${basePackage}.module.system.req.FileUploadRequest;
import ${basePackage}.module.system.req.FileDownloadRequest;
import ${basePackage}.module.system.rsp.FileCreateResponse;
import ${basePackage}.module.system.rsp.FileGetResponse;
import ${basePackage}.module.system.rsp.FileUploadResponse;
import ${basePackage}.module.system.rsp.FileDownloadResponse;
import org.springframework.beans.factory.annotation.Autowired;

public class FileApi {

    @Autowired
    private FileManager fileManager;

    public FileCreateResponse create(FileCreateRequest request) {
        return fileManager.create(request, LocalData.getToken());
    }

    public FileGetResponse get(FileGetRequest request) {
        return fileManager.get(request, LocalData.getToken());
    }

    public FileUploadResponse upload(FileUploadRequest request) {
        FileUploadResponse fileUploadResponse = new FileUploadResponse();
        String fileName = request.getFileName();
        String dataBase64 = request.getDataBase64();

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

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

        return fileUploadResponse;
    }

    public FileDownloadResponse download(FileDownloadRequest request) {
        FileDownloadResponse response = new FileDownloadResponse();

        FileGetRequest fileGetRequest = MapperUtil.map(request, FileGetRequest.class);
        FileGetResponse fileGetResponse = fileManager.get(fileGetRequest, LocalData.getToken());
        if (fileGetResponse.hasError() || null == fileGetResponse.getFile()) {
            response.addErrors(fileGetResponse.getErrors());
            response.addError(ErrorType.BUSINESS_ERROR, "未找到文件");
            return response;
        }

        response.setFile(fileGetResponse.getFile());
        // todo 实例文件字节转Base64
        response.setBase64(Base64Util.encodeToString("".getBytes()));
        return response;
    }
}
