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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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.webmember.WebMemberSqlMapDAO;
import com.madeu.dao.web.webstockclose.WebStockCloseSqlMapDAO;
import com.madeu.dao.web.webstockclosedetail.WebStockCloseDetailSqlMapDAO;
import com.madeu.dao.web.webstockhistory.WebStockHistorySqlMapDAO;
import com.madeu.service.web.webstockclose.WebStockCloseService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("WebStockCloseService")
public class WebStockCloseServiceImpl implements WebStockCloseService {
	
	@Autowired
	private WebStockCloseSqlMapDAO webStockCloseSqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	@Autowired
	private WebStockHistorySqlMapDAO webStockHistorySqlMapDAO;
	
	@Autowired
	private WebStockCloseDetailSqlMapDAO webStockCloseDetailSqlMapDAO;
	
	/**
	 * 재고마감 리스트 조회 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockCloseIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockCloseServiceImpl selectListStockCloseIntro 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("WebStockCloseServiceImpl selectListStockCloseIntro END");
		return map;
	}
	
	/**
	 * 재고마감 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockClose(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockCloseServiceImpl selectListStockClose START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("stockCloseSearchKeywordParam  :"+paramMap.get("stockCloseSearchKeywordParam"));
		log.debug("stockCloseSort                :"+paramMap.get("stockCloseSort"));
		log.debug("stockCloseStart               :"+paramMap.get("stockCloseStart"));
		log.debug("stockCloseLimit               :"+paramMap.get("stockCloseLimit"));
		log.debug("stockCloseSort                :"+paramMap.get("stockCloseSort"));
		log.debug("stockCloseDir                 :"+paramMap.get("stockCloseDir"));
		log.debug("stockCloseCurrentPage         :"+paramMap.get("stockCloseCurrentPage"));
		
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

		try{
			boolean check  = true;
			
			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);

				if(1==authMenuRelationlistMap.size()){

					if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

					}
					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(null==paramMap.get("stockCloseDir")||("").equals(paramMap.get("stockCloseDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("stockCloseDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("stockCloseDir", "ASC");
					}
					else {
						paramMap.put("stockCloseDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> totalCountListMap = webStockCloseSqlMapDAO.selectTotalStockCloseCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webStockCloseSqlMapDAO.selectListStockClose(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("WebStockCloseServiceImpl selectListStockClose END");
		return map;
	}
	
	/**
	 * 재고마감 리스트 조회 (Excel)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockCloseExcel(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockCloseServiceImpl selectListStockCloseExcel START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("stockCloseSearchKeywordParam  :"+paramMap.get("stockCloseSearchKeywordParam"));
		log.debug("stockCloseSort                :"+paramMap.get("stockCloseSort"));
		log.debug("stockCloseStart               :"+paramMap.get("stockCloseStart"));
		log.debug("stockCloseLimit               :"+paramMap.get("stockCloseLimit"));
		log.debug("stockCloseSort                :"+paramMap.get("stockCloseSort"));
		log.debug("stockCloseDir                 :"+paramMap.get("stockCloseDir"));
		log.debug("stockCloseCurrentPage         :"+paramMap.get("stockCloseCurrentPage"));
		
		try{
			boolean check  = true;
			
			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);

				if(1==authMenuRelationlistMap.size()){

					if(("Y").equals(authMenuRelationlistMap.get(0).get("downloadUseYn"))) {

					}
					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(null==paramMap.get("stockCloseDir")||("").equals(paramMap.get("stockCloseDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("stockCloseDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("stockCloseDir", "ASC");
					}
					else {
						paramMap.put("stockCloseDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> listMap = webStockCloseSqlMapDAO.selectListStockCloseExcel(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}

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

		log.debug("WebStockCloseServiceImpl selectListStockCloseExcel END");
		return map;
	}
	
	/**
	 * 재고마감생성 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertStockClose(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebStockCloseServiceImpl insertStockClose START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("startDate           :"+paramMap.get("startDate"));
		log.debug("endDate             :"+paramMap.get("endDate"));

		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 endDate         = String.valueOf(paramMap.get("endDate"));

			
			if(true != ValidationCheckUtil.emptyCheck(endDate)){
				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){
				List<Map<String,Object>> selectIdBeforeUpdateList = webStockCloseSqlMapDAO.selectIdBeforeUpdate(paramMap);
				//해당 월에 이미 마감 데이터 존재하는지 확인 후 삭제
				if(0<selectIdBeforeUpdateList.size()){
					webStockCloseSqlMapDAO.updateStockClose(paramMap);
					paramMap.put("selectIdBeforeUpdateList",selectIdBeforeUpdateList);
					for (Map<String, Object> item : selectIdBeforeUpdateList) {
						Object muStockCloseId = item.get("muStockCloseId");
						paramMap.put("muStockCloseId", muStockCloseId);
						webStockCloseSqlMapDAO.updateStockCloseDetail(paramMap);
					}
				}

				// 현재 거래처수, 품목수, 재고총액 조회
				List<Map<String, Object>> stockHistoryListMap = webStockHistorySqlMapDAO.selectTotalStockHistoryAmount(paramMap);
				
				if(1==stockHistoryListMap.size()){
					paramMap.put("companyCount", stockHistoryListMap.get(0).get("companyCount"));
					paramMap.put("productCount", stockHistoryListMap.get(0).get("productCount"));
					paramMap.put("totalAmount", stockHistoryListMap.get(0).get("totalAmount"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "재고 정보가 없습니다.");
				}
			}
			
			if(true == check){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				
				String muStockCloseId = ("SC").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muStockCloseId",muStockCloseId);
				paramMap.put("muMemberId", paramMap.get("loginMemberId"));
				webStockCloseSqlMapDAO.insertStockClose(paramMap);
				log.debug("muStockCloseId :"+paramMap.get("id"));
				paramMap.put("muStockCloseId", paramMap.get("id"));
				map.put("muStockCloseId", paramMap.get("muStockCloseId"));
				
				// 재고마감 상세 등록
				List<Map<String, Object>> stockHistoryDetailListMap = webStockHistorySqlMapDAO.selectListStockHistoryDetail(paramMap);
				int stockHistoryDetailListMapSize = stockHistoryDetailListMap.size();
				
				if(0<stockHistoryDetailListMapSize) {
					for (int i = 0; i < stockHistoryDetailListMapSize; i++) {
						String muStockHistoryId = String.valueOf(stockHistoryDetailListMap.get(i).get("muStockHistoryId"));
						String muTreatmentId    = String.valueOf(stockHistoryDetailListMap.get(i).get("muTreatmentId"));
						String treatmentName    = String.valueOf(stockHistoryDetailListMap.get(i).get("treatmentName"));
						String muProductId      = String.valueOf(stockHistoryDetailListMap.get(i).get("muProductId"));
						String productCode      = String.valueOf(stockHistoryDetailListMap.get(i).get("productCode"));
						String productName      = String.valueOf(stockHistoryDetailListMap.get(i).get("productName"));
						String muCompanyId      = String.valueOf(stockHistoryDetailListMap.get(i).get("muCompanyId"));
						String companyName      = String.valueOf(stockHistoryDetailListMap.get(i).get("companyName"));
						String inDate           = String.valueOf(stockHistoryDetailListMap.get(i).get("inDate"));
						String price            = String.valueOf(stockHistoryDetailListMap.get(i).get("price"));
						String quantity         = String.valueOf(stockHistoryDetailListMap.get(i).get("quantity"));
						String totalAmount      = String.valueOf(stockHistoryDetailListMap.get(i).get("totalAmount"));
						
						String muStockCloseDetailId = ("SCD").concat(String.valueOf(System.currentTimeMillis()));
						
						HashMap<String, Object> stockCloseDetailParamMap = new HashMap<String, Object>();
						stockCloseDetailParamMap.put("muStockCloseDetailId", muStockCloseDetailId);
						stockCloseDetailParamMap.put("muStockCloseId", paramMap.get("muStockCloseId"));
						stockCloseDetailParamMap.put("muTreatmentId", muTreatmentId);
						stockCloseDetailParamMap.put("treatmentName", treatmentName);
						stockCloseDetailParamMap.put("muProductId", muProductId);
						stockCloseDetailParamMap.put("productCode", productCode);
						stockCloseDetailParamMap.put("productName", productName);
						stockCloseDetailParamMap.put("muCompanyId", muCompanyId);
						stockCloseDetailParamMap.put("companyName", companyName);
						stockCloseDetailParamMap.put("muStockHistoryId", muStockHistoryId);
						stockCloseDetailParamMap.put("inDate", inDate);
						stockCloseDetailParamMap.put("price", price);
						stockCloseDetailParamMap.put("quantity", quantity);
						stockCloseDetailParamMap.put("totalAmount", totalAmount);
						stockCloseDetailParamMap.put("tId", tId);
						stockCloseDetailParamMap.put("tDate", tDate);
						stockCloseDetailParamMap.put("regId", paramMap.get("regId"));
						stockCloseDetailParamMap.put("modId", paramMap.get("modId"));
						webStockCloseDetailSqlMapDAO.insertStockCloseDetail(stockCloseDetailParamMap);
						
					}
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "등록되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebStockCloseServiceImpl insertStockClose END");
		return map;
	}
}
