package com.madeu.controller.web.webstockhistory;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.madeu.constants.Constants;
import com.madeu.init.ManagerDraftAction;
import com.madeu.service.web.webloghistory.WebLogHistoryService;
import com.madeu.service.web.webstockhistory.WebStockHistoryService;
import com.madeu.util.HttpUtil;
import com.madeu.util.RequestLogUtil;
import com.madeu.view.web.WebStockHistoryView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Controller
public class WebStockHistoryController extends ManagerDraftAction{

	@Autowired
	private WebStockHistoryService webStockHistoryService;
	
	@Autowired
	private WebLogHistoryService webLogHistoryService;
	@Autowired
	ResourceLoader resourceLoader;
	@Value("${file.upload-path}")
	private String uploadUrl;
	
	/**
	 * 입출고 내역 정보 리스트 화면으로 이동.
	 * 
	 * @param request
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/selectListStockHistoryIntro.do")
	public String  selectListStockHistoryIntro(HttpSession session,HttpServletRequest request, HttpServletResponse response, Model model) {
		log.debug("WebStockHistoryController  selectListStockHistoryIntro START");

		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		try{
			if(!webCheckLogin(session)){
				return "/web/login/logout";
			}
			else {
				paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
				map = webStockHistoryService.selectListStockHistoryIntro(paramMap);
				
				model.addAttribute("selectUseYn", map.get("selectUseYn"));
				model.addAttribute("insertUseYn", map.get("insertUseYn"));
				model.addAttribute("updateUseYn", map.get("updateUseYn"));
				model.addAttribute("deleteUseYn", map.get("deleteUseYn"));
				model.addAttribute("downloadUseYn", map.get("downloadUseYn"));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			return "/web/login/logout";
		}
		log.debug("WebStockHistoryController  selectListStockHistoryIntro END");
		return "/web/stockhistory/stockHistorySelectList";
	}
	
	/**
	 * 입출고 내역 정보 리스트 조회
	 * 
	 * @param request
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/selectListStockHistory.do")
	public ModelAndView selectListStockHistory(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
			
		log.debug("WebStockHistoryController selectListStockHistory START");
		
		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		try{
			if(!webCheckLogin(session)){
				return null;
			}
			else{
				paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
				map = webStockHistoryService.selectListStockHistory(paramMap);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if(Constants.OK == map.get("msgCode")) {

			}
			else{
				map.put("msgCode", Constants.FAIL);
				map.put("success", false);
				if(null == map.get("msgDesc") || ("").equals(map.get("msgDesc"))) {
					map.put("msgDesc","정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
				}
			}
		}
		log.debug("WebStockHistoryController selectListStockHistory END");
		return HttpUtil.makeHashToJsonModelAndView(map);
	}

	/**
	 * 입출고 첨부 파일 다운로드
	 *
	 * response : msgCode, msgDesc
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/downloadFile.do")
	public void downloadFile(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		log.debug("WebStockHistoryController downloadFile START");

		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();

		try{
			if(!webCheckLogin(session)){

			}else{
				String fileName = String.valueOf(paramMap.get("fileName"));
                File file = new File(uploadUrl+fileName);

                if (!file.exists()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
                    return;
                }
				byte[] fileByte = FileUtils.readFileToByteArray(file);

				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment; fileName=\"" + URLEncoder.encode(file.getName(), "UTF-8")+"\";");
				response.setHeader("Content-Transfer-Encoding", "binary");

				response.getOutputStream().write(fileByte);
				response.getOutputStream().flush();
				response.getOutputStream().close();
			}
		}catch (Exception e) {
			e.printStackTrace();
		    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
		log.debug("WebStockHistoryController downloadFile END");
	}
	
	/**
	 * <b> 입출고 내역 정보 리스트 엑셀 다운로드 </b>
	 * 페이지 처리 없음 
	 * request: 
	 * response : msgCode, msgDesc
	 * 
	 * @param request
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/downloadStockHistoryExcel.do")
	public ModelAndView downloadStockHistoryExcel(HttpSession session, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file, Model model) {
		log.debug("WebStockHistoryController downloadStockHistoryExcel START");
		
		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		Map<String, Object> selectListReport = new HashMap<String,Object>();
		Map<String, Object> map = new HashMap<String,Object>();
		
		try{
			if(!webCheckLogin(session)){
				return null;
			}
			else{
				paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
				selectListReport = webStockHistoryService.selectListStockHistoryExcel(paramMap);
				map.put("selectListStockHistory", selectListReport);
				map.put("name", "stockhistory");
			}
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
		log.debug("WebStockHistoryController downloadStockHistoryExcel END");
		return new ModelAndView(new WebStockHistoryView(),"map",map);
	}
	
	/**
	 * 입출고내역 상단 거래처정보 및 각 타입별 수량/금액 조회
	 * 
	 * @param request
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/selectStockHistory.do")
	public ModelAndView selectStockHistory(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
		log.debug("WebStockHistoryController selectStockHistory START");
		
		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		try{
			if(!webCheckLogin(session)){
				return null;
			}
			else{
				paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
				map = webStockHistoryService.selectStockHistory(paramMap);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if(Constants.OK == map.get("msgCode")) {

			}
			else{
				map.put("msgCode", Constants.FAIL);
				map.put("success", false);
				if(null == map.get("msgDesc") || ("").equals(map.get("msgDesc"))) {
					map.put("msgDesc","정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
				}
			}
		}
		log.debug("WebStockHistoryController selectStockHistory END");
		return HttpUtil.makeHashToJsonModelAndView(map);
	}
	
	/**	
	 * 입출고 내역 정보 등록
	 * 
	 * @param request
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/webstockhistory/insertStockHistory.do")
	public ModelAndView insertStockHistory(HttpSession session,HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file", required = false) MultipartFile file) {
				
		log.debug("WebStockHistoryController insertStockHistory START");
		
		HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
		HashMap<String, Object> map = new HashMap<String, Object>();

		StringBuffer errorMsg = new StringBuffer();

		try{
			if(!webCheckLogin(session)){
				return null;
			}
			else{
				paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
				paramMap.put("regId", String.valueOf(session.getAttribute("loginMemberId")));
				paramMap.put("modId", String.valueOf(session.getAttribute("loginMemberId")));
				paramMap.put("file",file);
				map = webStockHistoryService.insertStockHistory(paramMap);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			errorMsg.append(e);
		}
		finally {
			if(Constants.OK == map.get("msgCode")) {

			}
			else{
				map.put("msgCode", Constants.FAIL);
				map.put("success", false);
				if(null == map.get("msgDesc") || ("").equals(map.get("msgDesc"))) {
					map.put("msgDesc","정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
				}
			}

			try {
				HashMap<String, Object> visitLogParamMap = RequestLogUtil.getVisitLogParameterMap(request);
				HashMap<String, Object> insertMap = new HashMap<String, Object>();
	
				insertMap.put("url", "/webstockhistory/insertStockHistory.do");
				insertMap.put("func", "insertStockHistory");
				insertMap.put("funcName", "입출고 내역 등록");
				insertMap.put("service", "webStockHistoryService");
				insertMap.put("serviceName", "입출고 내역 등록");
				insertMap.put("requestValue", String.valueOf(paramMap));
				insertMap.put("responseValue", String.valueOf(map));
				insertMap.put("tId", map.get("tId"));
				if((String.valueOf(errorMsg)).equals("") || (String.valueOf(errorMsg) == null) || String.valueOf(errorMsg).length() == 0){
					insertMap.put("resultCode", "SUCCESS");
				}
				else{
					insertMap.put("resultCode", "ERROR");
				}
				insertMap.put("resultMsg", String.valueOf(errorMsg));
				insertMap.put("muMemberId", paramMap.get("loginMemberId"));
	
				webLogHistoryService.insertLogHistory(insertMap, visitLogParamMap);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.debug("WebStockHistoryController insertStockHistory END");
		return HttpUtil.makeHashToJsonModelAndView(map);
	}
}
