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

import org.springframework.beans.factory.annotation.Autowired;
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.auth.Token;
import ${basePackage}.frame.base.BaseResponse;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.excel.WExcel;
import ${basePackage}.frame.excel.exception.ReadErrorException;
import ${basePackage}.frame.excel.exception.TemplateNotMatchException;
import ${basePackage}.frame.utils.LogUtil;
import ${basePackage}.frame.utils.MapperUtil;
import ${basePackage}.frame.utils.ResponseUtil;
import ${basePackage}.frame.utils.ValidationUtil;
import ${basePackage}.module.system.ent.File;
import ${basePackage}.module.system.mgr.FileManager;
import ${basePackage}.module.system.req.FileCreateRequest;
import ${basePackage}.module.system.req.FileDeleteRequest;
import ${basePackage}.module.system.req.FileFindRequest;
import ${basePackage}.module.system.req.FileGetRequest;
import ${basePackage}.module.system.rsp.FileCreateResponse;
import ${basePackage}.module.system.rsp.FileDeleteResponse;
import ${basePackage}.module.system.rsp.FileFindResponse;
import ${basePackage}.module.system.rsp.FileGetResponse;
import ${basePackage}.module.system.rsp.FileUploadResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class FileAjax {

    @Autowired
    private FileManager fileManager;

    public FileCreateResponse create(FileCreateRequest request, Token token) {
        return fileManager.create(request, token);
    }

    public FileDeleteResponse delete(FileDeleteRequest request, Token token) {
        return fileManager.delete(request, token);
    }

    public FileFindResponse find(FileFindRequest request, Token token) {
        return fileManager.find(request, token);
    }

    public FileGetResponse get(FileGetRequest request, Token token) {
        return fileManager.get(request, token);
    }

    public Object template() {
        return ResponseUtil.apply(new WExcel<>(File.class));
    }

    public Object exports(FileFindRequest request, Token token) {
        FileFindResponse response = fileManager.find(request, token);
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(File.class).loadData(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            WExcel sheet = new WExcel<>(File.class).loadData(file.getBytes(), new WExcel.Processor<File>() {
                @Override
                public List<String> exec(File o) {
                    FileCreateRequest request = MapperUtil.map(o, FileCreateRequest.class);
                    return ValidationUtil.validate(request);
                }
            });

            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException | ReadErrorException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }

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

        //========
        // todo 处理文件
        //========
        fileUploadResponse.setId(1L);
        fileUploadResponse.setUrl("example.com\\img\\1.jpg");
        fileUploadResponse.setUrlDownload("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() {
        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;
        }
    }
}
