package cokr.xit.fims.wpm.web;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.fims.sndb.SndbQuery;
import cokr.xit.fims.sndb.service.SndngDtlService;
import cokr.xit.fims.wpm.WoopyonMoaRequest;
import cokr.xit.fims.wpm.service.WoopyonMoaService;
import cokr.xit.foundation.Downloadable;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.foundation.web.AbstractController;

@Controller
@RequestMapping("/woopyonmoa")
public class WoopyonMoaController extends AbstractController {
    /**발송 상세 서비스*/
    @Resource(name="sndngDtlService")
    private SndngDtlService sndngDtlService;
	@Resource(name = "woopyonMoaService")
	private WoopyonMoaService woopyonMoaService;

	@PostMapping(name="발송정보 다운로드", value="/download.do")
	public ModelAndView downloadRequest(WoopyonMoaRequest req) {
		List<DataObject> list = sndngDtlService.getSndngDtlList(
			new SndbQuery().setSndngId(req.getSndngId()).setFetchAll(true)
		);

		Downloadable downloadable = woopyonMoaService.downloadRequest(
			req.setStandardYN("규격")
				.setWeight(25)
				.setPieceCount(1)
				.setSndngDtlList(list)
		);

		return new ModelAndView("downloadView")
    		.addObject("download", downloadable.setFilename("우편등록_" + now() + ".xls"));
	}

    private String now() {
        return dateFormats.format("yyyyMMdd_HHmmss", System.currentTimeMillis());
    }

	@PostMapping(name="발송정보 업데이트", value="/update.do")
	public ModelAndView updateStatus(MultipartFile upload) {
		try {
			int affected = woopyonMoaService.updateStatus(upload.getInputStream());
			return new ModelAndView("jsonView")
				.addObject("affected", affected)
				.addObject("saved", affected > 0);
		} catch (Exception e) {
			throw runtimeException(e);
		}
	}
}