package com.madeu.crm.kiosk.service;

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.constants.Constants;
import com.madeu.crm.kiosk.dto.ConsentFormDTO;
import com.madeu.crm.kiosk.map.KioskMAP;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class KioskService {
    
    @Autowired
    private KioskMAP kioskMAP; // 인터페이스 기반 Mapper 주입

    /**
	 * 진료 리스트 조회 (option)
	 */
	public HashMap<String, Object> getTreatmentOptionList(HashMap<String, Object> paramMap) throws Exception {
		log.debug("KioskServiceImpl getTreatmentOptionList START");
		HashMap<String, Object> map = new HashMap<String, Object>();

		try {
			List<Map<String, Object>> listMap = kioskMAP.getTreatmentOptionList(paramMap);
			map.put("msgCode", Constants.OK);
			map.put("success","true");
			map.put("rows",listMap);
		} catch(Exception e) {
			log.error("getTreatmentOptionList Error: ", e);
			throw e;
		}
		return map;
	}
	
	/**
     * 병원 기타설정 카테고리 조회 (Option)
     */
    public HashMap<String, Object> getCategoryList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> categoryListMap = kioskMAP.getCategoryList(paramMap);
        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",categoryListMap);
        return map;
    }
    
    /**
     * 카테고리 아이템 조회 (Option)
     */
    public HashMap<String, Object> getCategoryItem(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> categoryListMap = kioskMAP.getCategoryItem(paramMap);
        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",categoryListMap);
        return map;
    }
    
    /**
     * 병원 고객정보 리스트 조회
     */
    public HashMap<String, Object> getUserOptionList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();

        if(null != paramMap.get("userDir") && !("").equals(paramMap.get("userDir"))){
            String dir = String.valueOf(paramMap.get("userDir"));
            paramMap.put("userDir", ("B").equals(dir) ? "ASC" : "DESC");
        }

        paramMap.put("useYn", "Y");
        int totalCount = kioskMAP.getUserOptionListCnt(paramMap);
        if(0 < totalCount){
            listMap = kioskMAP.getUserOptionList(paramMap);
        }

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("totalCount", totalCount);
        map.put("rows",listMap);
        return map;
    }
    
    /**
     * 고객 등록
     */
    public HashMap<String, Object> putUser(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();

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

            // 유효성 검사 로직
            if(!ValidationCheckUtil.emptyCheck(String.valueOf(paramMap.get("nationality")))) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","국적 정보가 없습니다.");
            } else if(!ValidationCheckUtil.emptyCheck(String.valueOf(paramMap.get("userName")))) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","고객 성함 정보가 없습니다.");
            } else if(!ValidationCheckUtil.nickNameCheck(String.valueOf(paramMap.get("userName")))) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","유효하지 않은 이름 형식입니다.");
            } else if(!ValidationCheckUtil.phoneNumberCheck(String.valueOf(paramMap.get("phoneNumber")))) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","유효하지 않은 전화번호 형식입니다.");
            }

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

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "등록되었습니다.");
            }
        } catch (Exception e) {
            log.error("putUser Error: ", e);
            throw e;
        }
        return map;
    }
    
    /**
     * 고객정보 조회
     */
    public HashMap<String, Object> getUser(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> usermap = new HashMap<String, Object>();
        if (paramMap.containsKey("muUserId")) {
        	usermap = kioskMAP.getUser(paramMap);
        }
        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("rows",usermap);
        return map;
    }
    
    /**
     * 근무시간 조회
     */
    public HashMap<String, Object> getWorkTime(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> hospitalListMap = kioskMAP.getHospital(paramMap);

		if(hospitalListMap.size() == 1){
			paramMap.put("muHospitalId", hospitalListMap.get(0).get("muHospitalId"));
			List<Map<String, Object>> holidayList = kioskMAP.getHospitalHolidayList(paramMap);
			hospitalListMap.get(0).put("holidayRows", holidayList);

			map.put("msgCode", Constants.OK);
			map.put("success","true");
			map.put("rows",hospitalListMap);
		} else {
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc", "병원 정보가 없습니다.");
		}
        return map;
    }
    
    /**
     * 진료시술 조회
     */
    public HashMap<String, Object> getTreatmentProcedureOptionList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        
		if(null != paramMap.get("treatmentProcedureDir") && !("").equals(paramMap.get("treatmentProcedureDir"))){
			String dir = String.valueOf(paramMap.get("treatmentProcedureDir"));
			paramMap.put("treatmentProcedureDir", ("B").equals(dir) ? "ASC" : "DESC");
		}
		
		paramMap.put("useYn", "Y");
        int totalCount = kioskMAP.getTotalTreatmentProcedureOptionCount(paramMap);
        if(0 < totalCount){
            listMap = kioskMAP.getTreatmentProcedureOptionList(paramMap);
        }

        map.put("msgCode", Constants.OK);
        map.put("success","true");
        map.put("totalCount", totalCount);
        map.put("rows",listMap);
        return map;
    }
    
    /**
     * 상담 의사 리스트 조회
     */
    public HashMap<String, Object> getMemberDoctorConsultingOptionList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
		String muTreatmentProcedureId = String.valueOf(paramMap.get("muTreatmentProcedureId"));
		
		if(!ValidationCheckUtil.emptyCheck(muTreatmentProcedureId)){			
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc","시술 정보가 없습니다.");
		}else{
			String [] arr = muTreatmentProcedureId.split(",");
			StringBuilder sb = new StringBuilder();
			for(String id : arr){
				sb.append("'").append(id).append("',");
			}
			String list = sb.substring(0, sb.lastIndexOf(","));
			paramMap.put("muTreatmentProcedureIdList", list);

            List<Map<String, Object>> listMap = kioskMAP.getMemberDoctorConsultingOptionList(paramMap);
            map.put("msgCode", Constants.OK);
            map.put("success","true");
            map.put("rows",listMap);
		}
        return map;
    }
    
    /**
     * 직원 리스트 조회
     */
    public HashMap<String, Object> getMemberList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        
		if(null != paramMap.get("memberDir") && !("").equals(paramMap.get("memberDir"))){
			String dir = String.valueOf(paramMap.get("memberDir"));
			paramMap.put("memberDir", ("B").equals(dir) ? "ASC" : "DESC");
		}
		
		paramMap.put("useYn", "Y");
		List<Map<String, Object>> totalCountListMap = kioskMAP.getMemberListCnt(paramMap);
		int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalcount")));
		
		if(0 < totalCount) {
			listMap = kioskMAP.getMemberList(paramMap);
		}
		
		map.put("msgCode", Constants.OK);
		map.put("success","true");
		map.put("totalCount", totalCount);
		map.put("rows",listMap);
        return map;
    }
    
    /**
     * 예약 고객 옵션 리스트 조회
     */
    public HashMap<String, Object> getReserveUserOptionList(HashMap<String, Object> paramMap) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        
		List<Map<String, Object>> totalCountListMap = kioskMAP.getMemberListCnt(paramMap);
		int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalcount")));
		
		if(0 < totalCount) {
			listMap = kioskMAP.getReserveUserOptionList(paramMap);
		}
		
		map.put("msgCode", Constants.OK);
		map.put("success","true");
		map.put("totalCount", totalCount);
		map.put("rows",listMap);
        return map;
    }
    
    /**
     * 동의서 조회
     */
    public ConsentFormDTO getConsentForm(ConsentFormDTO dto) {
    	return kioskMAP.selectConsentForm(dto);
    }
}