package ${domain}.action.api.wsys;

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

public class FileApi {

    @Autowired
    private FileManager fileManager;

    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;
    }
}
