package com.inkasso.factoring.code.controller;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.inkasso.adapter.response.ResponseData;
import com.inkasso.factoring.code.config.GoldConstant;
import com.inkasso.factoring.code.model.CodeDTO;
import com.inkasso.factoring.code.service.CodeGeneratorService;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value="/codegenerator")
public class CodeGeneratorController{

	@Resource
	private CodeGeneratorService codeGeneratorService;

	@Resource
	GoldConstant goldConstant;

	@RequestMapping(value = "", method = { RequestMethod.POST })
	public ResponseData save(@RequestBody @Valid CodeDTO codeDTO) {
		String str =  codeGeneratorService.createFile(codeDTO);
		return ResponseData.success(str);
	}
	
	@RequestMapping(value = "/export/{id}", method = { RequestMethod.POST,RequestMethod.GET})
	public void export(HttpServletResponse response, @PathVariable("id")String id) throws IOException {
		//ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
		String filePath = goldConstant.getFilePath()+ File.separator + id +".zip";
		File zipFile = new File(filePath);
		response
	          .setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=".concat(
	              URLEncoder.encode("代码.zip", StandardCharsets.UTF_8.displayName())));
		byte[] b = new byte[1000];
		InputStream inputStream = new FileInputStream(zipFile);
		int size = inputStream.read(b);
		while (size>0){
			response.getOutputStream().write(b,0,b.length);
			size=inputStream.read(b);
		}

	}
}
