package com.madeu.service.web.webstocksumadjustmentdetail.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.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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.webcompanyproduct.WebCompanyProductSqlMapDAO;
import com.madeu.dao.web.webhospitalholiday.WebHospitalHolidaySqlMapDAO;
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.webstocksumadjustmentdetail.WebStockSumAdjustmentDetailService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("WebStockSumAdjustmentDetailService")
public class WebStockSumAdjustmentDetailServiceImpl implements WebStockSumAdjustmentDetailService {
	
	@Autowired
	private WebStockSumSqlMapDAO webStockSumSqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	@Autowired
	private WebCompanyProductSqlMapDAO webCompanyProductSqlMapDAO;
	
	@Autowired
	private WebHospitalHolidaySqlMapDAO webHospitalHolidaySqlMapDAO;
	
	@Autowired
	private WebStockHistorySqlMapDAO webStockHistorySqlMapDAO;
	
	/**
	 * 제품별 실시간 재고 현황 상세 리스트 (재고조정 팝업 화면)
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListStockSumAdjustmentDetail(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebStockSumAdjustmentDetailServiceImpl selectListStockSumAdjustmentDetail 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("muCompanyId         :"+paramMap.get("muCompanyId"));
		log.debug("muProductId         :"+paramMap.get("muProductId"));
		
		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){
				
				List<Map<String, Object>> totalCountListMap = webStockSumSqlMapDAO.selectTotalStockSumAdjustmentDetailCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webStockSumSqlMapDAO.selectListStockSumAdjustmentDetail(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("WebStockSumAdjustmentDetailServiceImpl selectListStockSumAdjustmentDetail END");
		return map;
	}
	
	/**
	 * 제품별 실시간 재고 현황 (재고조정 팝업 화면) 저장
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertStockAdjustmentDetail(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebStockSumAdjustmentDetailServiceImpl insertStockAdjustmentDetail 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("detailRows          :"+paramMap.get("detailRows"));
		
		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"));
			
			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){
				// 권한 조회
				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("updateUseYn"))) {
						
					}
					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>> 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);
				
				JSONParser jsonParser = new JSONParser();
				JSONObject jsonObject = (JSONObject) jsonParser.parse(String.valueOf(paramMap.get("detailRows")));
				JSONArray detailArray = (JSONArray) jsonObject.get("data");
				
				for(int j=0; j<detailArray.size(); j++){
					JSONObject detailObject = (JSONObject) detailArray.get(j);
					
					String stockSumId         = String.valueOf(detailObject.get("muStockSumId"));
					String stockHistoryId     = String.valueOf(detailObject.get("muStockHistoryId"));
					String price              = String.valueOf(detailObject.get("price"));
					String quantity           = String.valueOf(detailObject.get("quantity"));
					String etc                = String.valueOf(detailObject.get("etc"));
					
					// 재고조정 등록
					if((null!=price&&!("").equals(price))
							&&(null!=quantity&&!("").equals(quantity))) {
						HashMap<String, Object> stockHistoryParamMap = new HashMap<String, Object>();
						
						String type = "";
						if(0<Integer.parseInt(quantity)) {
							type = "AA";
						}
						else {
							type = "AD";
							quantity = quantity.replace("-", "");
						}
						
						// 재고 이력 등록
						String muStockHistoryId = ("SH").concat(String.valueOf(System.currentTimeMillis()));
						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("companyName", paramMap.get("companyName"));
						stockHistoryParamMap.put("type", type);
						stockHistoryParamMap.put("price", price);
						stockHistoryParamMap.put("quantity",quantity);
						stockHistoryParamMap.put("etc",etc);
						stockHistoryParamMap.put("muStockHistoryId2", stockHistoryId);
						stockHistoryParamMap.put("regId", paramMap.get("regId"));
						stockHistoryParamMap.put("modId", paramMap.get("modId"));
						stockHistoryParamMap.put("tId", paramMap.get("tId"));
						stockHistoryParamMap.put("tDate", paramMap.get("tDate"));
						webStockHistorySqlMapDAO.insertStockHistory2(stockHistoryParamMap);
						paramMap.put("muStockHistoryId", stockHistoryParamMap.get("id"));
						
							// 2. 현 재고 수정
							HashMap<String, Object> stockSumParamMap = new HashMap<String, Object>();
							stockSumParamMap.put("muStockSumId", stockSumId);
							stockSumParamMap.put("quantity", quantity);
							stockSumParamMap.put("type", type);
							stockSumParamMap.put("modId", paramMap.get("modId"));
							webStockSumSqlMapDAO.updateStockSum2(stockSumParamMap);
					}
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "저장되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebStockSumAdjustmentDetailServiceImpl insertStockAdjustmentDetail END");
		return map;
	}
}
