package com.madeu.service.api.doctalk.impl;

import com.madeu.constants.Constants;
import com.madeu.dao.api.doctalk.DocTalkSqlMapDAO;
import com.madeu.dao.web.webhospital.WebHospitalSqlMapDAO;
import com.madeu.service.api.doctalk.DocTalkService;
import com.madeu.util.SecurityUtil;
import com.madeu.util.ValidationCheckUtil;
import lombok.extern.slf4j.Slf4j;
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 javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("DocTalkService")
public class DocTalkServiceImpl implements DocTalkService{

	@Autowired
	private DocTalkSqlMapDAO docTalkSqlMapDAO;

	@Autowired
	private WebHospitalSqlMapDAO webHospitalSqlMapDAO;

	/**
	 * 사용자 등록
	 * 
	 * 
	 * @param paramMap
	 * @param authorization
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertReserveNaver(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("DocTalkServiceImpl insertReserveNaver START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("hospitalId       : "+paramMap.get("hospitalId"));
		log.debug("reservationKey   : "+paramMap.get("reservationKey"));
		log.debug("bookingKey       : "+paramMap.get("bookingKey"));
		log.debug("datetime         : "+paramMap.get("datetime"));
		log.debug("name             : "+paramMap.get("name"));
		log.debug("phone            : "+paramMap.get("phone"));
		log.debug("state            : "+paramMap.get("state"));
		log.debug("naverUserId      : "+paramMap.get("naverUserId"));
		log.debug("email            : "+paramMap.get("email"));
		log.debug("userRequest      : "+paramMap.get("userRequest"));
		log.debug("customFormData   : "+paramMap.get("customFormData"));
		log.debug("preBookingKey    : "+paramMap.get("preBookingKey"));
		log.debug("itemOptions      : "+paramMap.get("itemOptions"));
		log.debug("visitorName      : "+paramMap.get("visitorName"));
		log.debug("visitorPhone     : "+paramMap.get("visitorPhone"));

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

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String tDate = simpleDateFormat.format(Long.parseLong(tId));

			paramMap.put("tId", tId);
			paramMap.put("tDate", tDate);

			String hospitalId      = String.valueOf(paramMap.get("hospitalId"));
			String reservationKey  = String.valueOf(paramMap.get("reservationKey"));
			String bookingKey      = String.valueOf(paramMap.get("bookingKey"));
			String datetime        = String.valueOf(paramMap.get("datetime"));
			String name            = String.valueOf(paramMap.get("name"));
			String phone           = String.valueOf(paramMap.get("phone"));
			String state           = String.valueOf(paramMap.get("state"));
			String naverUserId     = String.valueOf(paramMap.get("naverUserId"));
			String reserveDate     = "";
			String reserveTime     = "";

			if(true != ValidationCheckUtil.emptyCheck(hospitalId)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","전자차트 병원별 유니크 ID 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(reservationKey)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약 상품 ID 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(bookingKey)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","차트 내부의 예약 ID 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(datetime)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약 일자 및 시간 (yyyy-MM-dd HH:mm:ss) 정보가 없습니다.");
			}else{
				reserveDate = datetime.substring(0, 10);
				reserveTime = datetime.substring(11, 16);
			}

			if(true != ValidationCheckUtil.emptyCheck(name)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약자 이름 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(phone)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약자 전화번호 정보가 없습니다.");
			}

			/*if(true != ValidationCheckUtil.emptyCheck(state)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약 상태값 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(naverUserId)){
				check = false;
				success = false;
				map.put("code", Constants.EBS_ID_NONE);
				map.put("message","예약자 유니크 ID 정보가 없습니다.");
			}*/

			if(true == check){
				// 휴일 확인
				HashMap<String, Object> selectHolidayMap = new HashMap<String, Object>();
				selectHolidayMap.put("searchDate", reserveDate);
				List<Map<String, Object>> hospitalListMap = webHospitalSqlMapDAO.selectHospitalWeek(selectHolidayMap);

				if(1 == hospitalListMap.size()) {
					String openYn = String.valueOf(hospitalListMap.get(0).get("openYn"));
					String holidayYn = String.valueOf(hospitalListMap.get(0).get("holidayYn"));

					if(("N").equals(openYn)||("Y").equals(holidayYn)){
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "운영시간이 아닙니다.");
					}
				}
			}

			if(true == check){
				// 고객 정보 조회 (등록 여부 확인, 고객명/전화번호로 확인)
				List<Map<String, Object>> userList = docTalkSqlMapDAO.selectUserId(paramMap);

				if(1==userList.size()) {
					// 기존 고객으로 예약경로리
					paramMap.put("muUserId", userList.get(0).get("muUserId"));
				}
				else {
					// 간편예약 고객 등록
					String muUserId = ("U").concat(String.valueOf(System.currentTimeMillis()));
					paramMap.put("muUserId", muUserId);
					docTalkSqlMapDAO.insertUserTemp(paramMap);
					paramMap.put("muUserId", paramMap.get("id"));
				}
			}

			if(true == check){
				paramMap.put("regId", paramMap.get("muUserId"));
				paramMap.put("modId", paramMap.get("muUserId"));

				// 앱 예약처럼 등록
				String muReserveId = ("R").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muReserveId",muReserveId);
				paramMap.put("reserveDate", reserveDate);
				paramMap.put("reserveTime", reserveTime);

				paramMap.put("status", "T");
				paramMap.put("status2", "N");
				docTalkSqlMapDAO.insertReserve(paramMap);
				paramMap.put("muReserveId",paramMap.get("id"));

				// 상담차트 등록
				List<Map<String, Object>> userConsultingChartNumberList = docTalkSqlMapDAO.selectConsultingChartNumber(paramMap);
				String chartNumber1 = String.valueOf(userConsultingChartNumberList.get(0).get("chartNumber"));

				String muUserConsultingChartId = ("UCC").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muUserConsultingChartId",muUserConsultingChartId);
				paramMap.put("chartNumber",chartNumber1);
				docTalkSqlMapDAO.insertConsultingChart(paramMap);

				// 시술차트 등록
				List<Map<String, Object>> userMedicalChartNumberList = docTalkSqlMapDAO.selectMedicalChartNumber(paramMap);
				String chartNumber2 = String.valueOf(userMedicalChartNumberList.get(0).get("chartNumber"));

				String muUserMedicalChartId = ("UMC").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muUserMedicalChartId",muUserMedicalChartId);
				paramMap.put("chartNumber",chartNumber2);
				docTalkSqlMapDAO.insertMedicalChart(paramMap);
			}

			map.put("success", success);
			map.put("bookingKey", bookingKey);

		}catch (Exception e) {
			e.printStackTrace();
            throw e;
		}
		log.debug("DocTalkServiceImpl insertReserveNaver END");
		return map;
	}
}
