package com.madeu.crm.categoryManagement.service.impl;

import java.util.ArrayList;
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.common.dao.CommonDao;
import com.madeu.common.service.MenuAuthService;
import com.madeu.constants.Constants;
import com.madeu.crm.categoryManagement.service.CategoryManagementService;
import com.madeu.dao.web.webauthmenurelation.WebAuthMenuRelationSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CategoryManagementServiceImpl implements CategoryManagementService {
    
    @Autowired
    private CommonDao cmmnDAO;
    
    @Autowired
    private MenuAuthService menuAuthService;
    
    @Autowired
    private WebMemberSqlMapDAO webMemberSqlMapDAO;

    @Autowired
    private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
   

    /**
     * 카테고리 게시판으로 이동
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> moveCategoryManagementList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("moveCategoryManagementList START");

        HashMap<String, Object> map = menuAuthService.getMenuAuthority(paramMap);

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
        log.debug("menuClass           :"+paramMap.get("menuClass"));
        log.debug("moveCategoryManagementList END");
        return map;
    }
    
    /**
     * 홈페이지 카테고리 리스트 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getCategoryManagementList(HashMap<String, Object> paramMap) throws Exception {
    	log.debug("CategoryManagementServiceImpl getCategoryManagementList START");
    	System.out.println("paramMap : " + paramMap.toString());
        HashMap<String, Object> map = menuAuthService.getMenuAuthority(paramMap);

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
        
        int totalCount = cmmnDAO.selectCount("CategoryManagementSql.getCategoryManagementCnt", paramMap);

        if(0 < totalCount) {
            listMap = cmmnDAO.selectList("CategoryManagementSql.getCategoryManagementList", paramMap);
        }

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("totalCount", totalCount);
        map.put("rows",listMap);
		log.debug("CategoryManagementServiceImpl getCategoryManagementList END");
        return map;
    }
    /**
     * 홈페이지 카테고리정보 상세 조회 (one)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getCategoryManagement(
            HashMap<String, Object> paramMap) throws Exception {

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

        try{
            boolean check  = true;
            String postNo    = String.valueOf(paramMap.get("postNo"));

            // 정렬
            if(true != ValidationCheckUtil.emptyCheck(postNo)){
                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){
                
                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("detail", cmmnDAO.select("CategoryManagementSql.getCategoryManagement", paramMap));                
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("CategoryManagementServiceImpl selectCategoryManagement END");
        return map;
    }

    /**
     * 홈페이지 카테고리 콘텐츠 등록 화면으로 이동.
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> insertCategoryManagementIntro(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("CategoryManagementServiceImpl insertCategoryManagementIntro 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("CategoryManagementServiceImpl insertCategoryManagementIntro END");
        return map;
    }

    /**
     * 홈페이지 카테고리 정보 등록
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> putCategoryManagement(
            HashMap<String, Object> paramMap) throws Exception{
    	 log.debug("CategoryManagementServiceImpl putCategoryManagement START");
    	
	    HashMap<String, Object> map = new HashMap<>();

	    try {
	        boolean check = true;

	        String categoryDivCd = String.valueOf(paramMap.get("categoryDivCd"));
	        String categoryName = String.valueOf(paramMap.get("categoryNm"));

	        // Validation
	        if (!ValidationCheckUtil.emptyCheck(categoryDivCd)) {
	            check = false;
	            map.put("msgCode", Constants.FAIL);
	            map.put("msgDesc", "카테고리 구분 정보가 없습니다.");
	        }
	        if (!ValidationCheckUtil.emptyCheck(categoryName)) {
	            check = false;
	            map.put("msgCode", Constants.FAIL);
	            map.put("msgDesc", "카테고리명 정보가 없습니다.");
	        }

	        // 권한 및 사용자 확인
	        if (check) {
	            List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
	            if (userListMap.size() == 1) {
	                paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
	            } else {
	                check = false;
	                map.put("msgCode", Constants.FAIL);
	                map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
	            }
	        }

	        if (check) {
	            HashMap<String, Object> authCheckParamMap = new HashMap<>();
	            authCheckParamMap.put("menuClass", paramMap.get("menuClass"));
	            authCheckParamMap.put("muAuthId", paramMap.get("menuClassAuthId"));
	            List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

	            if (authMenuRelationlistMap.size() == 1 && "Y".equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
	                // 권한 있음
	            } else {
	                check = false;
	                map.put("msgCode", Constants.FAIL);
	                map.put("msgDesc", "등록 권한 정보가 없습니다.");
	            }
	        }

	        if (check) {
	            // 등록 처리
	            paramMap.put("muMemberId", paramMap.get("loginMemberId"));
	            cmmnDAO.insert("CategoryManagementSql.putCategoryManagement", paramMap);

	            map.put("msgCode", Constants.OK);
	            map.put("msgDesc", "등록되었습니다.");
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	        throw e;
	    }
	    log.debug("CategoryManagementServiceImpl putCategoryManagement END");
        return map;
    }

    /**
     * 홈페이지 카테고리 수정 화면으로 이동.
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> moveCategoryManagement(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("CategoryManagementServiceImpl updateCategoryManagementIntro 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("CategoryManagementServiceImpl updateCategoryManagementIntro END");
        return map;
    }

    /**
     * 홈페이지 카테고리 정보 수정
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> modCategoryManagement(
            HashMap<String, Object> paramMap) throws Exception{
    	log.debug("CategoryManagementServiceImpl modCategoryManagement START");
    	
    	HashMap<String, Object> map = new HashMap<>();

        try {
            boolean check = true;

            String categoryNo = String.valueOf(paramMap.get("categoryNo"));
            String categoryDivCd = String.valueOf(paramMap.get("categoryDivCd"));
            String categoryName = String.valueOf(paramMap.get("categoryNm"));

            // Validation
            if (!ValidationCheckUtil.emptyCheck(categoryNo)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "카테고리 번호 정보가 없습니다.");
            }
            if (!ValidationCheckUtil.emptyCheck(categoryName)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "카테고리명 정보가 없습니다.");
            }

            // 권한 및 사용자 확인
            if (check) {
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                if (userListMap.size() == 1) {
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                } else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if (check) {
                HashMap<String, Object> authCheckParamMap = new HashMap<>();
                authCheckParamMap.put("menuClass", paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId", paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

                if (authMenuRelationlistMap.size() == 1 && "Y".equals(authMenuRelationlistMap.get(0).get("updateUseYn"))) {
                    // 권한 있음
                } else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "수정 권한 정보가 없습니다.");
                }
            }

            if (check) {
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));
                //본문 UPDATE
                cmmnDAO.update("CategoryManagementSql.modCategoryManagement", paramMap);
                
                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "수정되었습니다.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("CategoryManagementServiceImpl modCategoryManagement END");
        return map;
    }

    /**
     * 홈페이지 카테고리 정보 삭제
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> delCategoryManagement(
            HashMap<String, Object> paramMap) throws Exception{

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

        try{
            boolean check  = true;

            // delList 처리 추가
            List<Map<String, Object>> delList = (List<Map<String, Object>>) paramMap.get("delList");
            int delCnt = 0;

            if (delList == null || delList.isEmpty()) {
                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) {
                // delList 반복 삭제
                for (Map<String, Object> delItem : delList) {
                    paramMap.put("categoryNo", delItem.get("categoryNo"));
                    paramMap.put("categoryDivCd", delItem.get("categoryDivCd")); // CATEGORY_DIV_CD 추가
                    int cnt = cmmnDAO.update("CategoryManagementSql.delCategoryManagement", paramMap);
                    delCnt += cnt;
                }
                map.put("msgCode", Constants.OK);
                map.put("msgDesc", delCnt + "건 삭제 되었습니다.");
            }

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

        log.debug("CategoryManagementServiceImpl deleteCategoryManagement END");
        return map;
    }
}