package com.seeyon.ctp.rest.resources;

import com.seeyon.apps.src_saomaoyi.invoice.InvoiceImgSaveService;
import com.seeyon.ctp.common.AppContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.Iterator;

@Path("/saomiaoyi")
@Produces({"application/json", "application/xml"})
public class HandleSaoMiaoYiImgResource extends BaseResource {

    private InvoiceImgSaveService invoiceImgSaveService = (InvoiceImgSaveService) AppContext.getBean("invoiceImgSaveServiceImpl");

    @Context
    HttpServletRequest req;

    @POST
    @Path("/fileSave")
    @Produces({"application/json"})
    @Consumes({"multipart/form-data"})
    public Response fileSave() {
        try {
            CommonsMultipartResolver resolver = new CommonsMultipartResolver();
            resolver.setDefaultEncoding("utf-8");
            if (resolver.isMultipart(req)) {
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(req);

                // 获取所有文件名
                Iterator<String> fileNames = multipartRequest.getFileNames();

                while (fileNames.hasNext()) {
                    String name = fileNames.next();
                    MultipartFile file = multipartRequest.getFile(name);
                    if (file != null && !file.isEmpty()) {
                        InputStream inputStream = file.getInputStream();
                        invoiceImgSaveService.saveInvoiceImg(inputStream);
                        inputStream.close();
                    }
                }
            }
            return success("");
        }catch (Exception e) {
            return fail(e.getMessage());
        }
    }
}
