package com.madeu.crm.kiosk.service.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 com.madeu.common.dao.CommonDao;
import com.madeu.constants.Constants;
import com.madeu.crm.kiosk.service.KioskService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class KioskServiceImpl implements KioskService {
    
    @Autowired
    private CommonDao cmmnDAO;    

    /**
	 * 진료 리스트 조회 (option)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> getTreatmentOptionList(HashMap<String, Object> paramMap) throws Exception {
		log.debug("KioskServiceImpl getTreatmentOptionList 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 = cmmnDAO.selectList("KioskSql.getTreatmentOptionList", paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("KioskServiceImpl getTreatmentOptionList END");
		return map;
	}
	
	/**
     * 병원 기타설정 카테고리 조회 (Option)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getCategoryList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getCategoryList START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        
        List<Map<String, Object>> categoryListMap = cmmnDAO.selectList("KioskSql.getCategoryList", paramMap);

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",categoryListMap);
        
        log.debug("KioskServiceImpl getCategoryList END");
        return map;
    }
    
    /**
     * 병원 기타설정 카테고리 조회 (Option)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getCategoryItem(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getCategoryItem START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        
        List<Map<String, Object>> categoryListMap = cmmnDAO.selectList("KioskSql.getCategoryItem", paramMap);

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",categoryListMap);
        
        log.debug("KioskServiceImpl getCategoryItem END");
        return map;
    }
    
    /**
     * 병원 고객정보 리스트 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getUserOptionList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getUserOptionList START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        // 정렬
        if(null==paramMap.get("userDir")||("").equals(paramMap.get("userDir"))){

        }
        else{
            String dir = String.valueOf(paramMap.get("userDir"));
            if(("A").equals(dir)){
                paramMap.put("userDir", "DESC");
            }
            else if(("B").equals(dir)){
                paramMap.put("userDir", "ASC");
            }
            else {
                paramMap.put("userDir", "DESC");
            }
        }

        paramMap.put("useYn", "Y");

        int totalCount = cmmnDAO.selectCount("KioskSql.getUserOptionListCnt", paramMap);
        if(0<totalCount){
            listMap = cmmnDAO.selectList("KioskSql.getUserOptionList", paramMap);
        }

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("totalCount", totalCount);
        map.put("rows",listMap);
        
        log.debug("KioskServiceImpl getUserOptionList END");
        return map;
    }
    
    /**
     * 고객 등록
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> putUser(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl putUser START");

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

        log.debug("nationality       : " + paramMap.get("nationality"));
        log.debug("nationalityCode   : " + paramMap.get("nationalityCode"));
        log.debug("localYn           : " + paramMap.get("localYn"));
        log.debug("userName          : " + paramMap.get("userName"));
        log.debug("userRrn1          : " + paramMap.get("userRrn1"));
        log.debug("userRrn2          : " + paramMap.get("userRrn2"));
        log.debug("userPno           : " + paramMap.get("userPno"));
        log.debug("userArc1          : " + paramMap.get("userArc1"));
        log.debug("userArc2          : " + paramMap.get("userArc2"));
        log.debug("phoneNumber       : " + paramMap.get("phoneNumber"));
        log.debug("phoneNumber2      : " + paramMap.get("phoneNumber2"));
        log.debug("gender            : " + paramMap.get("gender"));
        log.debug("channel           : " + paramMap.get("channel"));
        log.debug("channelCode       : " + paramMap.get("channelCode"));
        log.debug("muGroupId         : " + paramMap.get("muGroupId"));
        log.debug("memo              : " + paramMap.get("memo"));
        log.debug("etc               : " + paramMap.get("etc"));
        log.debug("birthday          : " + paramMap.get("birthday"));
        log.debug("userTypeCode      : " + paramMap.get("userTypeCode"));
        log.debug("userType          : " + paramMap.get("userType"));
        log.debug("refusePhotoYn     : " + paramMap.get("refusePhotoYn"));
        log.debug("smsYn             : " + paramMap.get("smsYn"));
        log.debug("identification    : " + paramMap.get("identification"));
        log.debug("introUserId       : " + paramMap.get("introUserId"));
        log.debug("muMemberId        : " + paramMap.get("muMemberId"));
        log.debug("modId             : " + paramMap.get("modId"));
        log.debug("regId             : " + paramMap.get("regId"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());


            String nationality = String.valueOf(paramMap.get("nationality"));
            String userName = String.valueOf(paramMap.get("userName"));
            String birthday = String.valueOf(paramMap.get("birthday"));
            String phoneNumber = String.valueOf(paramMap.get("phoneNumber"));
            String phoneNumber2 = String.valueOf(paramMap.get("phoneNumber2"));

            if(true != ValidationCheckUtil.emptyCheck(nationality)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","국적 정보가 없습니다.");
            }
            if(true != ValidationCheckUtil.emptyCheck(userName)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","고객 성함 정보가 없습니다.");
            }
            if(true != ValidationCheckUtil.emptyCheck(birthday)){
                paramMap.put("birthday", null);
            }
            if (!ValidationCheckUtil.emptyCheck(userName) || !ValidationCheckUtil.nickNameCheck(userName)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","유효하지 않은 이름 형식입니다.");
            }

            // 전화번호 형식 검증
            if (!ValidationCheckUtil.emptyCheck(phoneNumber) || !ValidationCheckUtil.phoneNumberCheck(phoneNumber)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","유효하지 않은 전화번호 형식입니다.");
            }

            // 보조 전화번호 형식 검증 (있을 경우만 검증)
            if (ValidationCheckUtil.emptyCheck(phoneNumber2) && !ValidationCheckUtil.phoneNumberCheck(phoneNumber2)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","유효하지 않은 보조 전화번호 형식입니다.");
            }


            if(check == true){
                String muUserId = ("U").concat(String.valueOf(System.currentTimeMillis()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar c1 = Calendar.getInstance();
                String tDate = sdf.format(c1.getTime());
                paramMap.put("muUserId", muUserId);
                paramMap.put("tId", tId);
                paramMap.put("tDate", tDate);
                cmmnDAO.insert("KioskSql.putUser", paramMap);

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "등록되었습니다.");
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        
        log.debug("KioskServiceImpl putUser END");
        return map;
    }
    
    /**
     * 고객정보 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getUser(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getUser START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> usermap = new HashMap<String, Object>();
        if (paramMap.containsKey("muUserId")) {
        	usermap = cmmnDAO.select("KioskSql.getUser", paramMap);
        }
        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",usermap);
        
        log.debug("KioskServiceImpl getUser END");
        return map;
    }
    
    /**
     * 근무시간 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getWorkTime(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getWorkTime START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> hospitalListMap = cmmnDAO.selectList("KioskSql.getHospital", paramMap);
		int hospitalListMapSize = hospitalListMap.size();

		if(1 == hospitalListMapSize){
			// 병원 휴일 정보 조회
			paramMap.put("muHospitalId", hospitalListMap.get(0).get("muHospitalId"));
			List<Map<String, Object>> hospitalHolidayListMap = cmmnDAO.selectList("KioskSql.getHospitalHolidayList", paramMap);

			hospitalListMap.get(0).put("holidayRows", hospitalHolidayListMap);

			map.put("msgCode", Constants.OK);
			map.put("success","true");
			map.put("rows",hospitalListMap);
		}
		else {
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc", "병원 정보가 없습니다.");
		}
        
        log.debug("KioskServiceImpl getWorkTime END");
        return map;
    }
    
    /**
     * 진료시술 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getTreatmentProcedureOptionList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getTreatmentProcedureOptionList START");
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        
     // 정렬 
		if(null==paramMap.get("treatmentProcedureDir")||("").equals(paramMap.get("treatmentProcedureDir"))){
			
		}
		else{
			String dir = String.valueOf(paramMap.get("treatmentProcedureDir"));
			if(("A").equals(dir)){
				paramMap.put("treatmentProcedureDir", "DESC");
			}
			else if(("B").equals(dir)){
				paramMap.put("treatmentProcedureDir", "ASC");
			}
			else {
				paramMap.put("treatmentProcedureDir", "DESC");
			}
		}
		
		paramMap.put("useYn", "Y");
        System.out.println(paramMap);
        int totalCount = cmmnDAO.selectCount("KioskSql.getTotalTreatmentProcedureOptionCount", paramMap);
        if(0 < totalCount){
            listMap = cmmnDAO.selectList("KioskSql.getTreatmentProcedureOptionList", paramMap);
        }

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("totalCount", totalCount);
        map.put("rows",listMap);
        log.debug("KioskServiceImpl getTreatmentProcedureOptionList END");
        return map;
    }
    
    
    /**
     * 진료시술 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getMemberDoctorConsultingOptionList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getMemberDoctorConsultingOptionList START");
        
    	// 	선택
 		log.debug("searchDate             :"+paramMap.get("searchDate"));
 		log.debug("searchTime             :"+paramMap.get("searchTime"));

 		// 필수
 		log.debug("muTreatmentProcedureId :"+paramMap.get("muTreatmentProcedureId"));
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        

		String muTreatmentProcedureId = String.valueOf(paramMap.get("muTreatmentProcedureId"));
		String muTreatmentProcedureIdList = "";
		
		if(true != ValidationCheckUtil.emptyCheck(muTreatmentProcedureId)){			
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc","시술 정보가 없습니다.");
		}else{
			String [] muTreatmentProcedureIdArr = muTreatmentProcedureId.split(",");
			for(int i=0; i<muTreatmentProcedureIdArr.length; i++){
				muTreatmentProcedureIdList = muTreatmentProcedureIdList.concat("'").concat(muTreatmentProcedureIdArr[i]).concat("',");
			}

			muTreatmentProcedureIdList = muTreatmentProcedureIdList.substring(0, muTreatmentProcedureIdList.lastIndexOf(","));
			paramMap.put("muTreatmentProcedureIdList", muTreatmentProcedureIdList);
		}
		
		listMap = cmmnDAO.selectList("KioskSql.getMemberDoctorConsultingOptionList", paramMap);
		
		map.put("msgCode", Constants.OK);
		map.put("success","true");
		map.put("rows",listMap);
			
        log.debug("KioskServiceImpl getMemberDoctorConsultingOptionList END");
        return map;
    }
    
    /**
     * 직원 리스트 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getMemberList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getMemberList START");
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
        
			
		// 정렬 
		if(null==paramMap.get("memberDir")||("").equals(paramMap.get("memberDir"))){
			
		}
		else{
			String dir = String.valueOf(paramMap.get("memberDir"));
			if(("A").equals(dir)){
				paramMap.put("memberDir", "DESC");
			}
			else if(("B").equals(dir)){
				paramMap.put("memberDir", "ASC");
			}
			else {
				paramMap.put("memberDir", "DESC");
			}
		}
		
		paramMap.put("useYn", "Y");
		
		// 총 갯수 조회
		List<Map<String, Object>> totalCountListMap = cmmnDAO.selectList("KioskSql.getMemberListCnt", paramMap);
		int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalcount")));
		
		if(0 < totalCount) {
			// 리스트 조회
			listMap = cmmnDAO.selectList("KioskSql.getMemberList", paramMap);
		}
		
		map.put("msgCode", Constants.OK);
		map.put("success","true");
		map.put("totalCount", totalCount);
		map.put("rows",listMap);
		
			
        log.debug("KioskServiceImpl getMemberList END");
        return map;
    }
    
    /**
     * 고객 - 1년간 진료내역 조회 (수납완료건) (List, option)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> getReserveUserOptionList(HashMap<String, Object> paramMap) throws Exception {
        log.debug("KioskServiceImpl getReserveUserOptionList START");
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
        
		
		// 총 갯수 조회
		List<Map<String, Object>> totalCountListMap = cmmnDAO.selectList("KioskSql.getMemberListCnt", paramMap);
		int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalcount")));
		
		if(0 < totalCount) {
			// 리스트 조회
			listMap = cmmnDAO.selectList("KioskSql.getReserveUserOptionList", paramMap);
		}
		
		map.put("msgCode", Constants.OK);
		map.put("success","true");
		map.put("totalCount", totalCount);
		map.put("rows",listMap);
		
			
        log.debug("KioskServiceImpl getReserveUserOptionList END");
        return map;
    }
}
