package com.madeu.service.web.webstockhistory.impl;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.madeu.constants.Constants;
import com.madeu.dao.web.webauthmenurelation.WebAuthMenuRelationSqlMapDAO;
import com.madeu.dao.web.webcompanyproduct.WebCompanyProductSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.dao.web.webstockhistory.WebStockHistorySqlMapDAO;
import com.madeu.dao.web.webstocksum.WebStockSumSqlMapDAO;
import com.madeu.service.web.webstockhistory.WebStockHistoryService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service("WebStockHistoryService")
public class WebStockHIstoryServiceImpl implements WebStockHistoryService {
	
	@Autowired
	private WebStockHistorySqlMapDAO webStockHistorySqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	@Autowired
	private WebCompanyProductSqlMapDAO webCompanyProductSqlMapDAO;
	
	@Autowired
	private WebStockSumSqlMapDAO webStockSumSqlMapDAO;

	@Value("${file.upload-path}")
	private String uploadUrl;

	/**
	 * 입출고내역 리스트 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockHistoryIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockHistoryServiceImpl selectListStockHistoryIntro START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		try{
			boolean check  = true;
			
			String menuClass    = String.valueOf(paramMap.get("menuClass"));
			
			// 정렬
			if(true != ValidationCheckUtil.emptyCheck(menuClass)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","메뉴 정보가 없습니다.");
			}

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					map.put("msgCode", Constants.OK);
					map.put("success","true");
					
					map.put("selectUseYn", authMenuRelationlistMap.get(0).get("selectUseYn"));
					map.put("insertUseYn", authMenuRelationlistMap.get(0).get("insertUseYn"));
					map.put("updateUseYn", authMenuRelationlistMap.get(0).get("updateUseYn"));
					map.put("deleteUseYn", authMenuRelationlistMap.get(0).get("deleteUseYn"));
					map.put("downloadUseYn", authMenuRelationlistMap.get(0).get("downloadUseYn"));
				}
				else {
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebStockHistoryServiceImpl selectListStockHistoryIntro END");
		return map;
	}
	
	/**
	 * 입출고내역 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockHistory(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockHistoryServiceImpl selectListStockHistory START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("stockHistorySort                :"+paramMap.get("stockHistorySort"));
		log.debug("stockHistoryStart               :"+paramMap.get("stockHistoryStart"));
		log.debug("stockHistoryLimit               :"+paramMap.get("stockHistoryLimit"));
		log.debug("stockHistorySort                :"+paramMap.get("stockHistorySort"));
		log.debug("stockHistoryDir                 :"+paramMap.get("stockHistoryDir"));
		log.debug("stockHistoryCurrentPage         :"+paramMap.get("stockHistoryCurrentPage"));
		
		log.debug("stockHistorySearchStartDate     :"+paramMap.get("stockHistorySearchStartDate"));
		log.debug("stockHistorySearchEndDate       :"+paramMap.get("stockHistorySearchEndDate"));
		log.debug("stockHistorySearchDateType      :"+paramMap.get("stockHistorySearchDateType"));
		log.debug("stockHistorySearchType          :"+paramMap.get("stockHistorySearchType"));
		
		log.debug("muTreatmentId                   :"+paramMap.get("muTreatmentId"));
		log.debug("muProductId                     :"+paramMap.get("muProductId"));
		log.debug("muCompanyId                     :"+paramMap.get("muCompanyId"));
		
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

		try{
			boolean check  = true;
			
			String muTreatmentId     = String.valueOf(paramMap.get("muTreatmentId"));
			String muProductId       = String.valueOf(paramMap.get("muProductId"));
			String muCompanyId       = String.valueOf(paramMap.get("muCompanyId"));
			
			if(true != ValidationCheckUtil.emptyCheck(muTreatmentId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","구분 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muProductId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","제품 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muCompanyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 정렬 
				if(null==paramMap.get("stockHistoryDir")||("").equals(paramMap.get("stockHistoryDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("stockHistoryDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("stockHistoryDir", "ASC");
					}
					else {
						paramMap.put("stockHistoryDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> totalCountListMap = webStockHistorySqlMapDAO.selectTotalStockHistoryCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webStockHistorySqlMapDAO.selectListStockHistory(paramMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("totalCount", totalCount);
				map.put("rows",listMap);
			}

		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebStockHistoryServiceImpl selectListStockHistory END");
		return map;
	}
	
	/**
	 * 입출고내역 리스트 조회 (Excel)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockHistoryExcel(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockHistoryServiceImpl selectListStockHistoryExcel START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("stockHistorySort                :"+paramMap.get("stockHistorySort"));
		log.debug("stockHistoryStart               :"+paramMap.get("stockHistoryStart"));
		log.debug("stockHistoryLimit               :"+paramMap.get("stockHistoryLimit"));
		log.debug("stockHistorySort                :"+paramMap.get("stockHistorySort"));
		log.debug("stockHistoryDir                 :"+paramMap.get("stockHistoryDir"));
		log.debug("stockHistoryCurrentPage         :"+paramMap.get("stockHistoryCurrentPage"));
		
		log.debug("stockHistorySearchStartDate     :"+paramMap.get("stockHistorySearchStartDate"));
		log.debug("stockHistorySearchEndDate       :"+paramMap.get("stockHistorySearchEndDate"));
		log.debug("stockHistorySearchDateType      :"+paramMap.get("stockHistorySearchDateType"));
		log.debug("stockHistorySearchType          :"+paramMap.get("stockHistorySearchType"));
		
		log.debug("muTreatmentId                   :"+paramMap.get("muTreatmentId"));
		log.debug("muProductId                     :"+paramMap.get("muProductId"));
		log.debug("muCompanyId                     :"+paramMap.get("muCompanyId"));
		
		try{
			boolean check  = true;
			
			String muTreatmentId     = String.valueOf(paramMap.get("muTreatmentId"));
			String muProductId       = String.valueOf(paramMap.get("muProductId"));
			String muCompanyId       = String.valueOf(paramMap.get("muCompanyId"));
			
			if(true != ValidationCheckUtil.emptyCheck(muTreatmentId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","구분 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muProductId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","제품 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muCompanyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 정렬 
				if(null==paramMap.get("stockHistoryDir")||("").equals(paramMap.get("stockHistoryDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("stockHistoryDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("stockHistoryDir", "ASC");
					}
					else {
						paramMap.put("stockHistoryDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> listMap = webStockHistorySqlMapDAO.selectListStockHistoryExcel(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}

		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebStockHistoryServiceImpl selectListStockHistoryExcel END");
		return map;
	}
	
	/**
	 * 입출고내역 상단 거래처정보 및 각 타입별 수량/금액 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectStockHistory(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockHistoryServiceImpl selectStockHistory START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("stockHistorySearchStartDate     :"+paramMap.get("stockHistorySearchStartDate"));
		log.debug("stockHistorySearchEndDate       :"+paramMap.get("stockHistorySearchEndDate"));
		log.debug("stockHistorySearchDateType      :"+paramMap.get("stockHistorySearchDateType"));

		log.debug("muTreatmentId                   :"+paramMap.get("muTreatmentId"));
		log.debug("muProductId                     :"+paramMap.get("muProductId"));
		log.debug("muCompanyId                     :"+paramMap.get("muCompanyId"));
		
		try{
			boolean check  = true;
			
			String muTreatmentId     = String.valueOf(paramMap.get("muTreatmentId"));
			String muProductId       = String.valueOf(paramMap.get("muProductId"));
			String muCompanyId       = String.valueOf(paramMap.get("muCompanyId"));
			
			if(true != ValidationCheckUtil.emptyCheck(muTreatmentId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","구분 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muProductId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","제품 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muCompanyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 정렬 
				if(null==paramMap.get("stockHistoryDir")||("").equals(paramMap.get("stockHistoryDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("stockHistoryDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("stockHistoryDir", "ASC");
					}
					else {
						paramMap.put("stockHistoryDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				// 거래처 정보 조회
				List<Map<String, Object>> companyProductListMap = webCompanyProductSqlMapDAO.selectCompanyProduct(paramMap);
				
				// 입출고내역 상단 각 타입별 수량/금액 조회
				List<Map<String, Object>> listMap = webStockHistorySqlMapDAO.selectTotalStockHistoryType(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("companyRows", companyProductListMap);
				map.put("rows",listMap);
			}

		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebStockHistoryServiceImpl selectStockHistory END");
		return map;
	}
	
	/**
	 * 입출고 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertStockHistory(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebStockHistoryServiceImpl insertStockHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muTreatmentId       :"+paramMap.get("muTreatmentId"));
		log.debug("muProductId         :"+paramMap.get("muProductId"));
		log.debug("muCompanyId         :"+paramMap.get("muCompanyId"));
		log.debug("inOutDate           :"+paramMap.get("inOutDate"));
		log.debug("type                :"+paramMap.get("type"));
		log.debug("price               :"+paramMap.get("price"));
		log.debug("quantity            :"+paramMap.get("quantity"));
		log.debug("etc                 :"+paramMap.get("etc"));
		
		try{
			boolean check  = true;
			String tId = String.valueOf(System.currentTimeMillis());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar c1 = Calendar.getInstance();
			String tDate = sdf.format(c1.getTime());

			String muTreatmentId  = String.valueOf(paramMap.get("muTreatmentId"));
			String muProductId    = String.valueOf(paramMap.get("muProductId"));
			String muCompanyId    = String.valueOf(paramMap.get("muCompanyId"));
			String inOutDate      = String.valueOf(paramMap.get("inOutDate"));
			String type           = String.valueOf(paramMap.get("type"));
			String price          = String.valueOf(paramMap.get("price"));
			String quantity       = String.valueOf(paramMap.get("quantity"));
			String etc            = String.valueOf(paramMap.get("etc"));
			
			if(true != ValidationCheckUtil.emptyCheck(muTreatmentId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","구분 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muProductId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","제품 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(muCompanyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(inOutDate)){
				if(("I").equals(type)) {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","입고일자 정보가 없습니다.");
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","출고일자 정보가 없습니다.");
				}
			}
			
			if(true != ValidationCheckUtil.emptyCheck(type)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","타입 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(price)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","단가 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(quantity)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","수량 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					
					if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "등록 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
			
			if(true == check){
				if(("I").equals(type)) {
					// 입고의 경우 해당일자 입고 확인 (동일제품 입고 불가)
					paramMap.put("inDate", inOutDate);
					List<Map<String, Object>> stockSumListMap = webStockSumSqlMapDAO.checkStockSumIn(paramMap);
					int stockSumListMapSize = Integer.parseInt(String.valueOf(stockSumListMap.get(0).get("totalCount")));
					
					if(0==stockSumListMapSize){
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "해당 일자에 이미 입고된 내역이 있습니다.");
					}
				}
				else {
					// 입고가 아닐 경우 입고수량 확인
					List<Map<String, Object>> stockSumListMap = webStockSumSqlMapDAO.selectTotalStockSumQuantity(paramMap);
					
					if(1==stockSumListMap.size()){
						int totalQuantity = Integer.parseInt(String.valueOf(stockSumListMap.get(0).get("totalQuantity")));
						
						if(totalQuantity>=Integer.parseInt(quantity)) {
							
						}
						else {
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc", "남은 수량은 "+totalQuantity+"입니다. 수량을 다시 확인하십시오.");
						}
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "현재 입고된 재고가 없습니다.");
					}
				}
			}
			
			if(true == check){
				// 거래처 및 제품 정보 조회
				List<Map<String, Object>> companyProductListMap = webCompanyProductSqlMapDAO.selectCompanyProduct(paramMap);
				
				if(1==companyProductListMap.size()){
					paramMap.put("treatmentName", companyProductListMap.get(0).get("treatmentName"));
					paramMap.put("companyName", companyProductListMap.get(0).get("companyName"));
					paramMap.put("productCode", companyProductListMap.get(0).get("productCode"));
					paramMap.put("productName", companyProductListMap.get(0).get("productName"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "거래처 및 제품 정보가 없습니다.");
				}
			}
			
			if(true == check){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				if(null!=paramMap.get("file")&&!("").equals(paramMap.get("file"))) {
					MultipartFile fileData = (MultipartFile) paramMap.get("file");

					if (null != fileData && !fileData.isEmpty()) {
						byte[] bytes = fileData.getBytes();
						Date toDay = new Date();
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
						String nowDateTime = dateFormat.format(toDay);
						String originalFileName = fileData.getOriginalFilename();
						String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
						String fileName = "stockHistoryIn"+ nowDateTime + "." + fileExtension;
						Path path = Paths.get(uploadUrl + fileName);
						Files.createDirectories(path.getParent()); // 상위 디렉토R리가 없으면 생성
						Files.write(path, bytes); // 파일 쓰기
						paramMap.put("fileName", fileName);
						paramMap.put("filePath", String.valueOf(path));
						paramMap.put("originalFileName", originalFileName);
					}
				}
				if(("I").equals(type)) {
					// 1. 입고 처리
					String muStockHistoryId = ("SH").concat(String.valueOf(System.currentTimeMillis()));
					paramMap.put("muStockHistoryId",muStockHistoryId);
					webStockHistorySqlMapDAO.insertStockHistory(paramMap);
					log.debug("muStockHistoryId :"+paramMap.get("id"));
					paramMap.put("muStockHistoryId", paramMap.get("id"));
					map.put("muStockHistoryId", paramMap.get("muStockHistoryId"));
					
					// 2. 현 재고 등록
					String muStockSumId = ("SS").concat(String.valueOf(System.currentTimeMillis()));
					paramMap.put("muStockSumId",muStockSumId);
					paramMap.put("inDate", inOutDate);
					webStockSumSqlMapDAO.insertStockSum(paramMap);
					log.debug("muStockSumId :"+paramMap.get("id"));
				}
				else {
					// 입고가 아닐 경우 선입선출로 출고 처리
					List<Map<String, Object>> stockSumListMap = webStockSumSqlMapDAO.selectListStockSum(paramMap);
					int stockSumListMapSize = stockSumListMap.size();
					
					// 입력받은 값
					int intQuantity = Integer.parseInt(quantity);
					
					for (int i = 0; i < stockSumListMapSize; i++) {
						// 현재고
						String muStockSumId        = String.valueOf(stockSumListMap.get(i).get("muStockSumId"));
						String stockStockHistoryId = String.valueOf(stockSumListMap.get(i).get("muStockHistoryId"));
						int stockQuantity          = Integer.parseInt(String.valueOf(stockSumListMap.get(i).get("quantity")));
						
						// 등록할 값
						int insertQuantity = (stockQuantity>=intQuantity)?intQuantity:stockQuantity;
						
						// 1. 출고이력 등록
						String muStockHistoryId = ("SH").concat(String.valueOf(System.currentTimeMillis()));
						
						HashMap<String, Object> stockHistoryParamMap = new HashMap<String, Object>();
						stockHistoryParamMap.put("muStockHistoryId", muStockHistoryId);
						stockHistoryParamMap.put("muTreatmentId", paramMap.get("muTreatmentId"));
						stockHistoryParamMap.put("treatmentName", paramMap.get("treatmentName"));
						stockHistoryParamMap.put("muProductId", paramMap.get("muProductId"));
						stockHistoryParamMap.put("productCode", paramMap.get("productCode"));
						stockHistoryParamMap.put("productName", paramMap.get("productName"));
						stockHistoryParamMap.put("muCompanyId", paramMap.get("muCompanyId"));
						stockHistoryParamMap.put("fileName", paramMap.get("fileName"));
						stockHistoryParamMap.put("filePath", paramMap.get("filePath"));
						stockHistoryParamMap.put("originalFileName", paramMap.get("originalFileName"));
						stockHistoryParamMap.put("companyName", paramMap.get("companyName"));
						stockHistoryParamMap.put("inOutDate", paramMap.get("inOutDate"));
						stockHistoryParamMap.put("type", paramMap.get("type"));
						stockHistoryParamMap.put("price", paramMap.get("price"));
						stockHistoryParamMap.put("quantity", insertQuantity);
						stockHistoryParamMap.put("etc", paramMap.get("etc"));
						stockHistoryParamMap.put("muStockHistoryId2", stockStockHistoryId);
						stockHistoryParamMap.put("regId", paramMap.get("regId"));
						stockHistoryParamMap.put("modId", paramMap.get("modId"));
						webStockHistorySqlMapDAO.insertStockHistory(stockHistoryParamMap);
						log.debug("muStockHistoryId :"+stockHistoryParamMap.get("id"));
						paramMap.put("muStockHistoryId", stockHistoryParamMap.get("id"));
						map.put("muStockHistoryId", paramMap.get("muStockHistoryId"));
						
						// 2. 현 재고 수정
						// 현 재고 수량
						int remainingQuantity = stockQuantity-insertQuantity;
						HashMap<String, Object> stockSumParamMap = new HashMap<String, Object>();
						stockSumParamMap.put("muStockSumId", muStockSumId);
						stockSumParamMap.put("quantity", remainingQuantity);
						stockSumParamMap.put("modId", paramMap.get("modId"));
						webStockSumSqlMapDAO.updateStockSum(stockSumParamMap);
						
						// 등록한 수량 빼고 다음 값 확인
						intQuantity = intQuantity - insertQuantity;
						
						// 수량만큼 등록햇으면 종료
						if(intQuantity==0) {
							break;
						}
					}
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "저장되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebStockHistoryServiceImpl insertStockHistory END");
		return map;
	}
}
