package sgc.portal.ei.ei0107.service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sgc.portal.base.util.EasyHashMap;
import sgc.portal.base.websquare.GridRowStatus;
import sgc.portal.ei.ei0107.dto.EI01070001USearch;
import sgc.portal.ei.ei0107.model.EI01070001U;
import sgc.portal.ei.ei0107.model.EI01070002U;
import sgc.portal.ei.ei0107.model.EI01070003U;
import sgc.portal.ei.ei0107.persistence.EI01070001UMapper;

@Service
public class EI01070001UService {
	private final EI01070001UMapper mapper;

	public EI01070001UService(EI01070001UMapper mapper) {
		this.mapper = mapper;
	}

	//(경영정보 - 보증) JOIN PIVOT(경영정보 - 보증 분기잔액) 조회
	public List<EasyHashMap<String, Object>> getList1(EI01070001USearch search) {
		String maxExpirDt = mapper.getMaxExpirDt(search);
		if (maxExpirDt == null) {
			return new ArrayList<>();
		}

		String dateStr1 = search.getPyear() + search.getPmonth();
		String dateStr2 = maxExpirDt;
		search.setYyyymm(calculateYyyymm(dateStr1, dateStr2));

		return mapper.getList1(search);
	}

	//경영정보 - 보증 주요기재사항 조회
	public List<EasyHashMap<String, Object>> getList2(EI01070001USearch search) {
		return mapper.getList2(search);
	}

	//(경영정보 - 보증),(경영정보 - 보증 분기잔액) 저장
	@Transactional
	public Map<String, String> save(EI01070001U eI01070001U) {
		Map<String, String> result = new HashMap<>();

		EI01070002U dcMap = eI01070001U.getList2().get(0);
		List<Map<String, String>> dcList = eI01070001U.getList1();

		mapper.insertOrUpdate1(dcMap);

		for (Map<String, String> map : dcList) {
			map.put("wrtePr", eI01070001U.getWrtePr());
			String dateStr1 = map.get("pyear") + map.get("pmonth");
			String dateStr2 = map.get("expirDt").substring(0, 6);
			List<String> dateList = calculateYyyymm(dateStr1, dateStr2);
			EI01070003U eI01070003U = new EI01070003U();
			switch (map.get("rowStatus")) {
			case GridRowStatus.CREATED:
				mapper.insert1(map);
				for (String str : dateList) {
					eI01070003U.setGuarBamt("0");
					eI01070003U.setGuarNo(map.get("guarNo"));
					eI01070003U.setPmonth(map.get("pmonth"));
					eI01070003U.setPyear(map.get("pyear"));
					eI01070003U.setGuarYyyymm(str);
					mapper.insertOrUpdate2(eI01070003U);
				}				
				break;
			case GridRowStatus.UPDATED:
				mapper.update(map);
				for (String str : dateList) {
					eI01070003U.setGuarBamt(map.get("ym" + str));
					eI01070003U.setGuarNo(map.get("guarNo"));
					eI01070003U.setPmonth(map.get("pmonth"));
					eI01070003U.setPyear(map.get("pyear"));
					eI01070003U.setGuarYyyymm(str);
					mapper.insertOrUpdate2(eI01070003U);
				}
				eI01070003U.setYyyymm(dateList);
				mapper.delete3(eI01070003U);
				break;
			case GridRowStatus.DELETED:
				mapper.delete2(map);
				mapper.delete1(map);
				break;
			default:
				break;
			}
		}
		return result;
	}

	//(경영정보 - 보증),(경영정보 - 보증 분기잔액),(경영정보 - 보증 주요기재사항) 전월 기록 복사
	@Transactional
	public Map<String, String> copy(EI01070001USearch search) {
		Map<String, String> result = new HashMap<>();
		if (mapper.getList3(search) == 0) {
			result.put("result", "전월 보증정보 내역이 없습니다.");
			return result;
		}
		
		String maxExpirDt = mapper.getMaxExpirDtBefore(search);
		if(maxExpirDt == null) {
			result.put("result", "전월기록의 만기일이 현 기준년월 보다 작습니다.");
			return result;
		}
		
		mapper.delete4(search);
		mapper.delete5(search);
		mapper.delete6(search);
		
		
		
		String dateStr1 = search.getPyear() + search.getPmonth();
		String dateStr2 = maxExpirDt;
		search.setYyyymm(calculateYyyymm(dateStr1, dateStr2));
		
		mapper.insert2(search);
		mapper.insert3(search);
		mapper.insert4(search);

		return result;
	}
	
	/**
	 * 기준년월 과 만기일 사이의 월을 계산
	 * @param dateStr1		기준년월
	 * @param dateStr2		만기일
	 * @return List<String>	["202301","202302", ...]
	 */
	public List<String> calculateYyyymm(String dateStr1, String dateStr2) {

		dateStr1 = dateStr1 + "01";
		dateStr2 = dateStr2 + "02";

		List<String> yyyymm = new ArrayList<>();

		LocalDate localDate = LocalDate.parse(dateStr1, DateTimeFormatter.BASIC_ISO_DATE);
		dateStr1 = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

		localDate = LocalDate.parse(dateStr2, DateTimeFormatter.BASIC_ISO_DATE);
		dateStr2 = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

		LocalDate startDate = LocalDate.parse(dateStr1, DateTimeFormatter.ISO_DATE);
		LocalDate endDate = LocalDate.parse(dateStr2, DateTimeFormatter.ISO_DATE);
		
		while (startDate.isBefore(endDate)) {
			int year = startDate.getYear();
			int month = startDate.getMonthValue();
			
			String quarterString = month > 9 ? year + "" + month : year + "0" + month  ;
			yyyymm.add(quarterString);

			startDate = startDate.plusMonths(1);
		}

		return yyyymm;
	}
}
