package com.madeu.service.web.webcompany.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 java.util.StringTokenizer;

import com.madeu.dao.web.webstockhistory.WebStockHistorySqlMapDAO;
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.webcompany.WebCompanySqlMapDAO;
import com.madeu.dao.web.webcompanyproduct.WebCompanyProductSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.dao.web.webproduct.WebProductSqlMapDAO;
import com.madeu.service.web.webcompany.WebCompanyService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("WebCompanyService")
public class WebCompanyServiceImpl implements WebCompanyService {
	
	@Autowired
	private WebCompanySqlMapDAO webCompanySqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	@Autowired
	private WebCompanyProductSqlMapDAO webCompanyProductSqlMapDAO;

	@Autowired
	private WebProductSqlMapDAO webProductSqlMapDAO;
	
	/**
	 * 거래처 리스트 조회 (option)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListCompanyOption(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectListCompanyOption 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;
			
			if(true == check){
				List<Map<String, Object>> listMap = webCompanySqlMapDAO.selectListCompanyOption(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebCompanyServiceImpl selectListCompanyOption END");
		return map;
	}
	
	/**
	 * 거래처 리스트 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListCompanyIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectListCompanyIntro 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("WebCompanyServiceImpl selectListCompanyIntro END");
		return map;
	}
	
	/**
	 * 거래처 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListCompany(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectListCompany START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("companySearchKeywordParam  :"+paramMap.get("companySearchKeywordParam"));
		log.debug("companySort                :"+paramMap.get("companySort"));
		log.debug("companyStart               :"+paramMap.get("companyStart"));
		log.debug("companyLimit               :"+paramMap.get("companyLimit"));
		log.debug("companySort                :"+paramMap.get("companySort"));
		log.debug("companyDir                 :"+paramMap.get("companyDir"));
		log.debug("companyCurrentPage         :"+paramMap.get("companyCurrentPage"));
		
		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("companyDir")||("").equals(paramMap.get("companyDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("companyDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("companyDir", "ASC");
					}
					else {
						paramMap.put("companyDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> totalCountListMap = webCompanySqlMapDAO.selectTotalCompanyCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webCompanySqlMapDAO.selectListCompany(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("WebCompanyServiceImpl selectListCompany END");
		return map;
	}
	
	/**
	 * 거래처 상세 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectCompanyIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectCompanyIntro START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muCompanyId         :"+paramMap.get("muCompanyId"));
		
		try{
			boolean check  = true;
			
			String menuClass    = String.valueOf(paramMap.get("menuClass"));
			
			String muCompanyId  = String.valueOf(paramMap.get("muCompanyId"));
			
			if(true != ValidationCheckUtil.emptyCheck(menuClass)){
				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){
					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("WebCompanyServiceImpl selectCompanyIntro END");
		return map;
	}
	
	/**
	 * 거래처 정보 상세 조회 (one)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectCompany(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectCompany START");

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

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

		try{
			boolean check  = true;
			String muCompanyId    = String.valueOf(paramMap.get("muCompanyId"));
			
			// 정렬
			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);

				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){
				List<Map<String, Object>> listMap = webCompanySqlMapDAO.selectCompany(paramMap);
				
				if(1 == listMap.size()) {
					// 거래처 제품 조회
					List<Map<String, Object>> companyProductListMap = webCompanyProductSqlMapDAO.selectListCompanyProduct(paramMap);
					
					listMap.get(0).put("companyProductList", companyProductListMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebCompanyServiceImpl selectCompany END");
		return map;
	}
	
	/**
	 * 거래처 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertCompany(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebCompanyServiceImpl insertCompany START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("companyName         :"+paramMap.get("companyName"));
		log.debug("businessNumber      :"+paramMap.get("businessNumber"));
		log.debug("userName            :"+paramMap.get("userName"));
		log.debug("phoneNumber         :"+paramMap.get("phoneNumber"));
		log.debug("email               :"+paramMap.get("email"));
		log.debug("memo                :"+paramMap.get("memo"));
		
		log.debug("companyProductRows  :"+paramMap.get("companyProductRows"));


		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 companyName     = String.valueOf(paramMap.get("companyName"));
			String businessNumber  = String.valueOf(paramMap.get("businessNumber"));
			String userName        = String.valueOf(paramMap.get("userName"));
			String phoneNumber     = String.valueOf(paramMap.get("phoneNumber"));
			String email           = String.valueOf(paramMap.get("email"));
			
			if(true != ValidationCheckUtil.emptyCheck(companyName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(companyName,35)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","거래처명 정보는 35자를 넘을 수 없습니다.");
				}
			}
			if(true == ValidationCheckUtil.emptyCheck(businessNumber)&&true != ValidationCheckUtil.buzNoCheck(businessNumber)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","사업자번호 정보가 올바르지 않습니다.");
			}

			if(true == ValidationCheckUtil.emptyCheck(userName)&&true != ValidationCheckUtil.lengthCheck(userName,35)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","담당자명 정보는 35자를 넘을 수 없습니다.");
			}
			
			if(true == ValidationCheckUtil.emptyCheck(phoneNumber)&&true != ValidationCheckUtil.phoneNumberCheck(phoneNumber)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","전화번호 정보가 올바르지 않습니다.");
			}

			if(true == ValidationCheckUtil.emptyCheck(email)&&true != ValidationCheckUtil.emailCheck(email)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","이메일 정보가 올바르지 않습니다.");
			}

			if(true == check){
				// 거래처 제품 값 확인
				JSONParser jsonParser = new JSONParser();
				JSONObject jsonObject = (JSONObject) jsonParser.parse(String.valueOf(paramMap.get("companyProductRows")));
				if(jsonObject.isEmpty()==true) {
					
				}else {
					JSONArray detailArray = (JSONArray) jsonObject.get("data");
					
					for(int j=0; j<detailArray.size(); j++){
						JSONObject detailObject = (JSONObject) detailArray.get(j);
						
						String productName   = String.valueOf(detailObject.get("productName"));
						String categoryCode  = String.valueOf(detailObject.get("categoryCode"));
						String volume        = String.valueOf(detailObject.get("volume"));
						String unitCode      = String.valueOf(detailObject.get("unitCode"));
						String unitName      = String.valueOf(detailObject.get("unitName"));
						String usage_volume        = String.valueOf(detailObject.get("usage_volume"));
						String usage_unitCode      = String.valueOf(detailObject.get("usage_unitCode"));
						String usage_unitName      = String.valueOf(detailObject.get("usage_unitName"));

						if(true != ValidationCheckUtil.emptyCheck(productName)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 제품명 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(categoryCode)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 구분 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(volume)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 용량 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(unitCode)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(unitName)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(usage_volume)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 사용량 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(usage_unitCode)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 사용량 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(usage_unitName)){
							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){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				
				String muCompanyId = ("C").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muCompanyId",muCompanyId);
				webCompanySqlMapDAO.insertCompany(paramMap);
				log.debug("muCompanyId :"+paramMap.get("id"));
				paramMap.put("muCompanyId", paramMap.get("id"));
				map.put("muCompanyId", paramMap.get("muCompanyId"));

				// 제품 정보 삭제
//				webProductSqlMapDAO.deleteProduct(paramMap);

				// 거래처 제품 연결 정보 삭제
				webCompanyProductSqlMapDAO.deleteCompanyProduct(paramMap);
				
				// 거래처 제품 등록
				JSONParser jsonParser = new JSONParser();
				JSONObject jsonObject = (JSONObject) jsonParser.parse(String.valueOf(paramMap.get("companyProductRows")));
				if(jsonObject.isEmpty()==true) {
					
				}else {
					JSONArray detailArray = (JSONArray) jsonObject.get("data");
					
					for(int j=0; j<detailArray.size(); j++){
						JSONObject detailObject = (JSONObject) detailArray.get(j);
						
						String productName     = String.valueOf(detailObject.get("productName"));
						String categoryCode    = String.valueOf(detailObject.get("categoryCode"));
						String volume          = String.valueOf(detailObject.get("volume"));
						String unitCode        = String.valueOf(detailObject.get("unitCode"));
						String unitName        = String.valueOf(detailObject.get("unitName"));
						String usage_volume          = String.valueOf(detailObject.get("usage_volume"));
						String usage_unitCode        = String.valueOf(detailObject.get("usage_unitCode"));
						String usage_unitName        = String.valueOf(detailObject.get("usage_unitName"));


						// 제품코드 조회
						List<Map<String, Object>> productCodeListMap = webProductSqlMapDAO.selectProductCountSeq(paramMap);
						String productCode = String.valueOf(productCodeListMap.get(0).get("productCode"));
						
						// 제품 정보 등록
						HashMap<String, Object> productParamMap = new HashMap<String, Object>();
						String muProductId = ("P").concat(String.valueOf(System.currentTimeMillis()));
						productParamMap.put("muProductId",muProductId);
						productParamMap.put("productCode", productCode);
						productParamMap.put("productName", productName);
						productParamMap.put("categoryCode", categoryCode);
						productParamMap.put("volume", volume);
						productParamMap.put("unitCode", unitCode);
						productParamMap.put("unitName", unitName);
						productParamMap.put("regId", paramMap.get("regId"));
						productParamMap.put("modId", paramMap.get("modId"));
						productParamMap.put("tId", paramMap.get("tId"));
						productParamMap.put("tDate", paramMap.get("tDate"));
						productParamMap.put("usage_volume", usage_volume);
						productParamMap.put("usage_unitCode", usage_unitCode);
						productParamMap.put("usage_unitName", usage_unitName);
						webProductSqlMapDAO.insertProduct(productParamMap);
						Object result = productParamMap.get("id");
						if (result instanceof HashMap) {
							@SuppressWarnings("unchecked")
							HashMap<String, Object> idMap = (HashMap<String, Object>) result;
							Object productId = idMap.get("productId");
							paramMap.put("muProductId", productId);
						}
						
						// 거래처 제품 연결 정보 등록
						HashMap<String, Object> companyProductParamMap = new HashMap<String, Object>();
						String muCompanyProductId = ("CP").concat(String.valueOf(System.currentTimeMillis()));
						companyProductParamMap.put("muCompanyProductId",muCompanyProductId);
						companyProductParamMap.put("muCompanyId", paramMap.get("muCompanyId"));
						companyProductParamMap.put("muProductId", paramMap.get("muProductId"));
						companyProductParamMap.put("orderNumber", (j+1));
						companyProductParamMap.put("regId", paramMap.get("regId"));
						companyProductParamMap.put("modId", paramMap.get("modId"));
						companyProductParamMap.put("tId", paramMap.get("tId"));
						companyProductParamMap.put("tDate", paramMap.get("tDate"));
						webCompanyProductSqlMapDAO.insertCompanyProduct(companyProductParamMap);
					}
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "등록되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebCompanyServiceImpl insertCompany END");
		return map;
	}

	/**
	 * 거래처 정보 수정
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> updateCompany(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebCompanyServiceImpl updateCompany START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muCompanyId         :"+paramMap.get("muCompanyId"));
		
		log.debug("companyName         :"+paramMap.get("companyName"));
		log.debug("businessNumber      :"+paramMap.get("businessNumber"));
		log.debug("userName            :"+paramMap.get("userName"));
		log.debug("phoneNumber         :"+paramMap.get("phoneNumber"));
		log.debug("email               :"+paramMap.get("email"));
		log.debug("memo                :"+paramMap.get("memo"));
		
		log.debug("companyProductRows  :"+paramMap.get("companyProductRows"));

		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 muCompanyId     = String.valueOf(paramMap.get("muCompanyId"));
			String companyName     = String.valueOf(paramMap.get("companyName"));
			String businessNumber  = String.valueOf(paramMap.get("businessNumber"));
			String userName        = String.valueOf(paramMap.get("userName"));
			String phoneNumber     = String.valueOf(paramMap.get("phoneNumber"));
			String email           = String.valueOf(paramMap.get("email"));
			
			if(true != ValidationCheckUtil.emptyCheck(muCompanyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(companyName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","거래처명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(companyName,35)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","거래처명 정보는 35자를 넘을 수 없습니다.");
				}
			}

			if(true == ValidationCheckUtil.emptyCheck(businessNumber)&&true != ValidationCheckUtil.buzNoCheck(businessNumber)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","사업자번호 정보가 올바르지 않습니다.");
			}

			if(true == ValidationCheckUtil.emptyCheck(userName)&&true != ValidationCheckUtil.lengthCheck(userName,35)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","담당자명 정보는 35자를 넘을 수 없습니다.");
			}

			if(true == ValidationCheckUtil.emptyCheck(phoneNumber)&&true != ValidationCheckUtil.phoneNumberCheck(phoneNumber)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","전화번호 정보가 올바르지 않습니다.");
			}

			if(true == ValidationCheckUtil.emptyCheck(email)&&true != ValidationCheckUtil.emailCheck(email)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","이메일 정보가 올바르지 않습니다.");
			}

			if(true == check){
				// 거래처 제품 값 확인
				JSONParser jsonParser = new JSONParser();
				JSONObject jsonObject = (JSONObject) jsonParser.parse(String.valueOf(paramMap.get("companyProductRows")));
				if(jsonObject.isEmpty()==true) {
					
				}else {
					JSONArray detailArray = (JSONArray) jsonObject.get("data");
					
					String notDeleteIdArr = "";
					for(int j=0; j<detailArray.size(); j++){
						JSONObject detailObject = (JSONObject) detailArray.get(j);
						
						String muProductId   = String.valueOf(detailObject.get("muProductId"));
						String productName   = String.valueOf(detailObject.get("productName"));
						String muTreatmentId = String.valueOf(detailObject.get("muTreatmentId"));
						String volume        = String.valueOf(detailObject.get("volume"));
						String unitCode      = String.valueOf(detailObject.get("unitCode"));
						String unitName      = String.valueOf(detailObject.get("unitName"));
						String usage_volume        = String.valueOf(detailObject.get("usage_volume"));
						String usage_unitCode      = String.valueOf(detailObject.get("usage_unitCode"));
						String usage_unitName      = String.valueOf(detailObject.get("usage_unitName"));

						if(true != ValidationCheckUtil.emptyCheck(productName)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 제품명 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(muTreatmentId)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 구분 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(volume)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 용량 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(unitCode)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(unitName)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(usage_volume)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 사용량 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(usage_unitCode)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 사용량 단위 정보가 없습니다.");
						}
						if(true != ValidationCheckUtil.emptyCheck(usage_unitName)){
							check = false;
							map.put("msgCode", Constants.FAIL);
							map.put("msgDesc","거래처 제품 중 사용량 단위 정보가 없습니다.");
						}
						
						if(true != ValidationCheckUtil.emptyCheck(muProductId)){
							
						}
						else {
							// 기존 등록 제품 중 값 변동 안된 것 확인
							HashMap<String, Object> productCheckParamMap = new HashMap<String, Object>();
							productCheckParamMap.put("muProductId",muProductId);
							productCheckParamMap.put("muTreatmentId",muTreatmentId);
							productCheckParamMap.put("productName",productName);
							productCheckParamMap.put("volume",volume);
							productCheckParamMap.put("unitCode",unitCode);
							productCheckParamMap.put("unitName",unitName);
							productCheckParamMap.put("usage_volume",usage_volume);
							productCheckParamMap.put("usage_unitCode",usage_unitCode);
							productCheckParamMap.put("usage_unitName",usage_unitName);
							List<Map<String, Object>> productCheckListMap = webProductSqlMapDAO.checkProduct(productCheckParamMap);
							int totalCount = Integer.parseInt(String.valueOf(productCheckListMap.get(0).get("totalCount")));
							
							if(1==totalCount) {
								notDeleteIdArr = notDeleteIdArr+"'"+muProductId + "',";
							}
						}
					}
					
					// 마지막 콤마 제거
					if (notDeleteIdArr.endsWith(",")) {
						notDeleteIdArr = notDeleteIdArr.substring(0, notDeleteIdArr.length() - 1);
					}
					
					paramMap.put("notDeleteIdArr", notDeleteIdArr);
				}
			}
			
			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){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				
				webCompanySqlMapDAO.updateCompany(paramMap);
				map.put("muCompanyId", paramMap.get("muCompanyId"));
				
				// 제품 정보 삭제 (제품 값 변동 안된 건 미삭제)
				String notDeleteIdArr = String.valueOf(paramMap.get("notDeleteIdArr"));
				paramMap.put("selectId", notDeleteIdArr);
//				webProductSqlMapDAO.deleteProduct(paramMap);
				
				// 거래처 제품 연결 정보 삭제 (제품 값 변동 안된 건 미삭제)
				webCompanyProductSqlMapDAO.deleteCompanyProduct(paramMap);
				
				// 거래처 제품 등록
				JSONParser jsonParser = new JSONParser();
				JSONObject jsonObject = (JSONObject) jsonParser.parse(String.valueOf(paramMap.get("companyProductRows")));
				if(jsonObject.isEmpty()==true) {
					
				}else {
					JSONArray detailArray = (JSONArray) jsonObject.get("data");
					
					for(int j=0; j<detailArray.size(); j++){
						JSONObject detailObject = (JSONObject) detailArray.get(j);
						
						String muProductId     = String.valueOf(detailObject.get("muProductId"));
						String productName     = String.valueOf(detailObject.get("productName"));
						String muTreatmentId   = String.valueOf(detailObject.get("muTreatmentId"));
						String volume          = String.valueOf(detailObject.get("volume"));
						String unitCode        = String.valueOf(detailObject.get("unitCode"));
						String unitName        = String.valueOf(detailObject.get("unitName"));
						String usage_volume   = String.valueOf(detailObject.get("usage_volume"));
						String usage_unitCode = String.valueOf(detailObject.get("usage_unitCode"));
						String usage_unitName = String.valueOf(detailObject.get("usage_unitName"));
						log.debug("companyProductRows  :"+paramMap.get("companyProductRows"));
						log.debug("muTreatmentId  :"+muTreatmentId);
						// 신규 등록 제품이거나, 제품 값 변동된 제품일 경우 신규 등록
						if(true != ValidationCheckUtil.emptyCheck(muProductId) || !notDeleteIdArr.contains(muProductId)) {
							// 제품코드 조회
							List<Map<String, Object>> productCodeListMap = webProductSqlMapDAO.selectProductCountSeq(paramMap);
							String productCode = String.valueOf(productCodeListMap.get(0).get("productCode"));
							
							// 제품 정보 등록
							HashMap<String, Object> productParamMap = new HashMap<String, Object>();
							String ProductId = ("P").concat(String.valueOf(System.currentTimeMillis()));
							productParamMap.put("muProductId",ProductId);
							productParamMap.put("productCode", productCode);
							productParamMap.put("productName", productName);
							productParamMap.put("categoryCode", muTreatmentId);
							productParamMap.put("volume", volume);
							productParamMap.put("unitCode", unitCode);
							productParamMap.put("unitName", unitName);
							productParamMap.put("regId", paramMap.get("regId"));
							productParamMap.put("modId", paramMap.get("modId"));
							productParamMap.put("tId", paramMap.get("tId"));
							productParamMap.put("tDate", paramMap.get("tDate"));
							productParamMap.put("usage_volume", usage_volume);
							productParamMap.put("usage_unitCode", usage_unitCode);
							productParamMap.put("usage_unitName", usage_unitName);
							webProductSqlMapDAO.insertProduct(productParamMap);
							Object result = productParamMap.get("id");
							if (result instanceof HashMap) {
								@SuppressWarnings("unchecked")
								HashMap<String, Object> idMap = (HashMap<String, Object>) result;
								Object productId = idMap.get("productId");
								paramMap.put("muProductId", productId);
							}
							// 거래처 제품 연결 정보 등록
							HashMap<String, Object> companyProductParamMap = new HashMap<String, Object>();
							String muCompanyProductId = ("CP").concat(String.valueOf(System.currentTimeMillis()));
							companyProductParamMap.put("muCompanyProductId",muCompanyProductId);
							companyProductParamMap.put("muCompanyId", muCompanyId);
							companyProductParamMap.put("muProductId", paramMap.get("muProductId"));
							companyProductParamMap.put("orderNumber", (j+1));
							companyProductParamMap.put("regId", paramMap.get("regId"));
							companyProductParamMap.put("modId", paramMap.get("modId"));
							companyProductParamMap.put("tId", paramMap.get("tId"));
							companyProductParamMap.put("tDate", paramMap.get("tDate"));
							webCompanyProductSqlMapDAO.insertCompanyProduct(companyProductParamMap);
						}
					}
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "수정되었습니다.");
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebCompanyServiceImpl updateCompany END");
		return map;
	}

	/**
	 * 거래처 정보 삭제
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> deleteCompany(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebCompanyServiceImpl deleteCompany START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		// ,로 구분
		log.debug("selectId            :"+paramMap.get("selectId"));
		
		try{
			boolean check  = true;
			
			if(null== paramMap.get("selectId") || ("").equals(paramMap.get("selectId"))){
				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("deleteUseYn"))) {
						
					}
					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){
				String selectId = String.valueOf(paramMap.get("selectId"));
				StringTokenizer selectData = new StringTokenizer(selectId, ",");
				while(selectData.hasMoreTokens()){//토큰이 계속 있을때 까지
					String muCompanyId = selectData.nextToken();
					
					HashMap<String, Object> deleteParamMap = new HashMap<String, Object>();
					deleteParamMap.put("muCompanyId", muCompanyId);
					deleteParamMap.put("modId", paramMap.get("loginMemberId"));
					webCompanySqlMapDAO.deleteCompany(deleteParamMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "삭제 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebCompanyServiceImpl deleteCompany END");
		return map;
	}
	

	
	/**
	 * 거래처 정보 및 제품 정보 상세 조회 (one)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectCompanyProduct(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebCompanyServiceImpl selectCompanyProduct 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"));

		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){
				// 권한 조회
				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){
				List<Map<String, Object>> listMap = webCompanyProductSqlMapDAO.selectCompanyProduct(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebCompanyServiceImpl selectCompanyProduct END");
		return map;
	}
}
