package com.madeu.crm.kiosk.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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 com.madeu.constants.Constants;
import com.madeu.crm.kiosk.dto.ConsentFormDTO;
import com.madeu.crm.kiosk.dto.UserDTO;
import com.madeu.crm.kiosk.map.KioskMAP;
import com.madeu.dao.web.webuser.WebUserSqlMapDAO;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class KioskService {
    
    @Autowired
    private KioskMAP kioskMAP; // 인터페이스 기반 Mapper 주입
    
    @Autowired
    private WebUserSqlMapDAO webUserSqlMapDAO;
    /**
	 * 진료 리스트 조회 (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(UserDTO dto) throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();

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

            // 1. DTO 필드를 이용한 유효성 검사 로직
            if(!ValidationCheckUtil.emptyCheck(dto.getNationality())) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","국적 정보가 없습니다.");
            } else if(!ValidationCheckUtil.emptyCheck(dto.getUserName())) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","고객 성함 정보가 없습니다.");
            } else if(!ValidationCheckUtil.nickNameCheck(dto.getUserName())) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","유효하지 않은 이름 형식입니다.");
            } else if(!ValidationCheckUtil.phoneNumberCheck(dto.getPhoneNumber())) {
                check = false; map.put("msgCode", Constants.FAIL); map.put("msgDesc","유효하지 않은 전화번호 형식입니다.");
            }

            if(check) {
            	String muUserId = ("U").concat(String.valueOf(System.currentTimeMillis()));
            	// 2. DTO에 필요한 추가 정보 세팅 (Setter 활용)
                // muUserId는 매퍼의 selectKey에서 생성되지만, 접두어 등이 필요하다면 세팅
                dto.setMuUserId(muUserId); 
                
                // tId 등 로그용 데이터가 DTO에 필드로 정의되어 있다면 세팅, 
                // 없다면 결과 map에만 담아서 리턴
                map.put("tId", tId);

                // 3. MyBatis 매퍼 호출 (DTO 객체 자체를 전달)
                kioskMAP.insertUser(dto);
                //A: 개인정보수집및이용안내
                //B: 메이드유시술동의서
                //C: 이용약관동의서
                //G: 사진촬영거부동의서
                String[] types = {"A","B","C","G"};
                HashMap<String, Object> consentFormMap = new HashMap<>();
                for (String type : types) {
                	String muUserAgreementId = ("UA").concat(String.valueOf(System.currentTimeMillis()));
                	
                	consentFormMap.put("muUserAgreementId", muUserAgreementId);
                	consentFormMap.put("muUserId", dto.getUserNumber().get("id"));
                	consentFormMap.put("userName", dto.getUserName());
                	consentFormMap.put("type", type);
                	consentFormMap.put("renewalCycle", 12);
                	
                	LocalDateTime oneYearLater = LocalDateTime.now().plusYears(1);

                	// MariaDB DATETIME 표준 형식 (YYYY-MM-DD HH:mm:ss)
                	String expirationDate = oneYearLater.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                	consentFormMap.put("expirationDate", expirationDate);
                	consentFormMap.put("cdnUrl", "-");
                	consentFormMap.put("filePath", "-");
                	consentFormMap.put("fileName", "-");
                	consentFormMap.put("originalFileName", "-");
                	consentFormMap.put("loginMemberId", "kiosk");
                	consentFormMap.put("signatureBase64", dto.getSignatureData());
                	webUserSqlMapDAO.insertUserAgreement(consentFormMap);
				}
                
                
                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);
    }
}