
package sgc.portal.com.sym.batch.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.core.env.Environment;

import sgc.portal.base.util.EasyHashMap;
import sgc.portal.com.sym.batch.model.Batch;
import sgc.portal.com.sym.batch.persistence.BatchMapper;
import sgc.portal.com.sym.mail.service.MailService;

import java.util.ArrayList;
import java.util.List;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import javax.annotation.Resource;

import sgc.portal.security.PasswordEncryptionService;
import sgc.portal.security.annotation.Secured;
import sgc.portal.security.annotation.SecurityPolicy;
/**
 * The type Authentication exception.
 *
 * @author YongSang
 * @version 1.0.0
 * @since 2020. 7. 28.
 */
@Component
public class BatchService {
    
	@Autowired
    private BatchMapper batchMapper;
	@Autowired
	private MailService mailService;
	@Autowired
    private Environment environment;

    /**
	 * 패스워드 암호화
	 */
    @Resource(name = "passwordEncryptionService")
    private PasswordEncryptionService passwordEncryptionService;
    
    Logger logger = LoggerFactory.getLogger(this.getClass());
    //logger.info("[MYTEST] test batch {}", recvAddress);
    
    
    @Scheduled(cron = "0 0 13 * * *")		//13시 실행
    public void schedule() throws Exception {
        
		List<EasyHashMap<String, Object>> empList = new ArrayList<EasyHashMap<String, Object>>();
		empList = batchMapper.getList();
    	
    	for (EasyHashMap<String, Object> empInfo : empList) {
    		
    		String cmpnCd = String.valueOf(empInfo.get("cmpnCd"));
    		String empNo = String.valueOf(empInfo.get("empNo"));
    		String empNm = String.valueOf(empInfo.get("empNm"));
    		String jobGradeNm = String.valueOf(empInfo.get("jobGradeNm"));
    		String deptNm = String.valueOf(empInfo.get("deptNm"));
    		String eMail = String.valueOf(empInfo.get("eMail"));
    		String staDate = String.valueOf(empInfo.get("staDate"));
    		String endDate = String.valueOf(empInfo.get("endDate"));
    		String dtmNm = String.valueOf(empInfo.get("dtmNm"));
    		String staDateResult = String.valueOf(empInfo.get("staDateResult"));
    		
    		String mobile = String.valueOf(empInfo.get("mobile"));
    		
    		//본인
    		doDtmMailSend(cmpnCd,empNo,empNm,jobGradeNm,deptNm,eMail,staDate,endDate,dtmNm,staDateResult);
            //부서장
    		doDtmMailMngSend(cmpnCd,empNo,empNm,jobGradeNm,deptNm,eMail,staDate,endDate,dtmNm,staDateResult);
            //SMS
            doSmsSend(dtmNm,mobile,staDate);
    	}
    	
    }

    
    @Scheduled(cron = "0 30 6 * * *")		//6시30분 실행
    public void schedule2() throws Exception {
        
		List<EasyHashMap<String, Object>> empList = new ArrayList<EasyHashMap<String, Object>>();
		empList = batchMapper.getList2();
    	
    	for (EasyHashMap<String, Object> empInfo : empList) {
    		
    		String cmpnCd = String.valueOf(empInfo.get("cmpnCd"));
    		String userId = String.valueOf(empInfo.get("userId"));
    		String logpass = String.valueOf(empInfo.get("logpass"));
    		
    		//패스워드 초기화
    		doUpdateLogpass(cmpnCd,userId,logpass);
    	}
    	
    }

    @Scheduled(cron = "0 55 16 * * 1-5")		//16시 55분 실행
    public void schedule3() throws Exception {
    	String frDate = LocalDate.now().format(DateTimeFormatter.ofPattern("YYYYMMDD"));
    	
		List<EasyHashMap<String, Object>> empList = new ArrayList<EasyHashMap<String, Object>>();
		empList = batchMapper.getList3(frDate);

		
    	for (EasyHashMap<String, Object> empInfo : empList) {

    		String cmpnCd = "S0001";
    		String empNo = String.valueOf(empInfo.get("empNo"));
    		String empNm = String.valueOf(empInfo.get("empNm"));
    		String deptNm = String.valueOf(empInfo.get("deptNm"));
    		String eMail = String.valueOf(empInfo.get("eMail"));

    		doMhGetList(cmpnCd,empNo,frDate, empNm, deptNm, eMail);
    	}
    	
		List<EasyHashMap<String, Object>> empList2 = new ArrayList<EasyHashMap<String, Object>>();
		empList2 = batchMapper.getList4(frDate);
        
		
    	for (EasyHashMap<String, Object> empInfo2 : empList2) {
        
    		String cmpnCd = "S0001";
    		String empNo = String.valueOf(empInfo2.get("empNo"));
    		String empNm = String.valueOf(empInfo2.get("empNm"));
    		String deptNm = String.valueOf(empInfo2.get("deptNm"));
    		String eMail = String.valueOf(empInfo2.get("eMail"));

    		doMhGetList2(cmpnCd,empNo,frDate, empNm, deptNm, eMail);
    	}
    	
    }

    @Scheduled(cron = "0 0 17 20 * *")		//매월 20일 17시 실행
    public void schedule4() throws Exception {
    	LocalDate now = LocalDate.now();
    	LocalDate now2 = now.minusMonths(1);

    	String year = Integer.toString(now2.getYear());
    	String monthValue = Integer.toString(now2.getMonthValue());
    	
    	String frDate = "";
    	
		frDate = year+monthValue+"21";
    	
		List<EasyHashMap<String, Object>> empList = new ArrayList<EasyHashMap<String, Object>>();
		empList = batchMapper.getList7(frDate);

		
    	for (EasyHashMap<String, Object> empInfo : empList) {

    		String cmpnCd = "S0001";
    		String empNo = String.valueOf(empInfo.get("empNo"));
    		String empNm = String.valueOf(empInfo.get("empNm"));
    		String deptNm = String.valueOf(empInfo.get("deptNm"));
    		String eMail = String.valueOf(empInfo.get("eMail"));

    		doMhGetList3(cmpnCd,empNo,frDate, empNm, deptNm, eMail);
    	}
    	
    }
    

    @Scheduled(cron = "0 5 17 20 * *")		//매월 20일 16시55분 실행(담당자)
    public void schedule5() throws Exception {
    	LocalDate now = LocalDate.now();
    	LocalDate now2 = now.minusMonths(1);

    	String year = Integer.toString(now.getYear());
    	String monthValue = Integer.toString(now.getMonthValue());
    	int dayOfMonth = now.getDayOfMonth();

    	String year2 = Integer.toString(now2.getYear());
    	String monthValue2 = Integer.toString(now2.getMonthValue());
    	
    	String frDate = "";
    	
    	if(dayOfMonth < 21) {
    		frDate = year2+monthValue2+"21";
    	} else {
    		frDate = year+monthValue+"21";
    	}

		String cmpnCd = "S0001";
		String empNm = "";
    	String mhStr = "";
    	String mhStr2 = "";
    	String mhDStr = "";
    	String dtCal = "";
    	String eMail = "";
    	
		List<EasyHashMap<String, Object>> empList = new ArrayList<EasyHashMap<String, Object>>();
		empList = batchMapper.getList5(frDate);

    	for (EasyHashMap<String, Object> empInfo : empList) {

    		empNm = String.valueOf(empInfo.get("empNm"));
    		dtCal = String.valueOf(empInfo.get("dtCal"));
    		
    		mhStr += "\t" + dtCal + "\t" + empNm + "\t" + "\t";
    		mhStr += "<br>";
        }

		List<EasyHashMap<String, Object>> empList2 = new ArrayList<EasyHashMap<String, Object>>();
		empList2 = batchMapper.getList6(frDate);

    	for (EasyHashMap<String, Object> empInfo2 : empList2) {

    		empNm = String.valueOf(empInfo2.get("empNm"));
    		dtCal = String.valueOf(empInfo2.get("dtCal"));

    		mhStr2 += "\t" + dtCal + "\t" + empNm + "\t" + "\t";
    		mhStr2 += "<br>";
        }
    	
    	mhDStr = "MH 미입력자 안내";
    	
    	List<EasyHashMap<String, Object>> mailList = new ArrayList<EasyHashMap<String, Object>>();
    	mailList = batchMapper.getMhEmail();
    	
    	for (EasyHashMap<String, Object> mailInfo : mailList) {
    		eMail = String.valueOf(mailInfo.get("eMail"));
    		mailService.mailSend7("Man Hour 등록안내","Man Hour 등록", mhDStr, cmpnCd, eMail, mhStr, mhStr2);
    	}
    }
    
    private void doDtmMailSend(String cmpnCd, String empNo, String empNm, String jobGradeNm, String deptNm, String eMail, String staDate, String endDate, String dtmNm, String staDateResult) throws Exception {
    	
    	String dtmStr = "";
    	String dtmhStr = "";
    	
    	if(staDateResult.equals("V_1")){
    		dtmhStr = "본인 연차유급휴가 사전 안내(1일전)";
    	}else if(staDateResult.equals("V_3")){
    		dtmhStr = "본인 연차유급휴가 사전 안내(3일전)";
    	}else if(staDateResult.equals("V_5")){
    		dtmhStr = "본인 연차유급휴가 사전 안내(5일전)";
    	}
    	
		dtmStr = "<br>기업문화팀에서 안내드립니다.<br>"+empNm+" "+jobGradeNm+" 님은 상기와 같이 휴가일정이 계획되어 있습니다.<br><br>만약 상기 휴가사용이 불가한 경우 반드시 휴가 당일까지 계획을 변경하시기 바랍니다.<br>(ERP - 휴가신청 - 휴가계획변경)<br><br>휴가당일까지 변경이 없는 경우 휴가는 확정됨을 알려드립니다.";
		mailService.mailSend2(dtmhStr,"연차유급휴가",cmpnCd, empNo, empNm, jobGradeNm, deptNm, eMail, staDate, endDate, dtmNm, staDateResult, dtmStr);
    }
    
    private void doDtmMailMngSend(String cmpnCd, String empNo, String empNm, String jobGradeNm, String deptNm, String eMail, String staDate, String endDate, String dtmNm, String staDateResult) throws Exception {
    	
    	String dtmStr = "";
    	String dtmhStr = "";
    	
    	if(staDateResult.equals("V_1")){
    		dtmhStr = "부서원("+empNm+" "+jobGradeNm+") 연차유급휴가 사전 안내(1일전)";
    	}else if(staDateResult.equals("V_3")){
    		dtmhStr = "부서원("+empNm+" "+jobGradeNm+") 연차유급휴가 사전 안내(3일전)";
    	}else if(staDateResult.equals("V_5")){
    		dtmhStr = "부서원("+empNm+" "+jobGradeNm+") 연차유급휴가 사전 안내(5일전)";
    	}
    	
    	List<EasyHashMap<String, Object>> mailList = new ArrayList<EasyHashMap<String, Object>>();
    	mailList = batchMapper.getMngEmail(empNo);
    	
    	for (EasyHashMap<String, Object> mailInfo : mailList) {
    		dtmStr = "<br>기업문화팀에서 안내드립니다.<br>"+empNm+" "+jobGradeNm+" 님의 휴가일정이 상기와 같이 계획되어 있습니다.<br><br>부서장님께서는 부서원이 계획한 휴가일정대로 휴가를 사용할 수 있도록 해주시기 바랍니다.<br><br>만약 상기 휴가사용이 불가한 경우 반드시 휴가 당일까지 휴가계획을 변경할 것을 안내하여 주시기 바랍니다.<br>(ERP - 휴가신청 - 휴가계획변경)<br><br>휴가당일까지 변경이 없는 경우 휴가는 확정됨을 알려드립니다.";
    		mailService.mailSend2(dtmhStr,"연차유급휴가", cmpnCd, empNo, empNm, jobGradeNm, deptNm, String.valueOf(mailInfo.get("eMail")), staDate, endDate, dtmNm, staDateResult, dtmStr);
    	}
    }
    
    private void doSmsSend(String dtmNm, String mobile, String staDate) throws Exception {
    	
    	Batch batch = new Batch();
    	String[] activeProfiles = environment.getActiveProfiles();
    	String sContents = "";
    	
        sContents = "[SGC이앤씨 본인휴가안내] "+staDate+" / "+dtmNm+"입니다.(세부내용 메일 참조)";
        //운영에서만 SMS전송 테이블에 데이터 INSERT
  		if(activeProfiles[0].equals("local")) {			//local
  			/*mobile = "";
  			batch.setMobile(mobile);
  			batch.setSContents(sContents);
  			batchMapper.insertSms(batch);*/
  		} else if(activeProfiles[0].equals("dev")) {	//개발
  			/*mobile = "";
  			batch.setMobile(mobile);
  			batch.setSContents(sContents);
  			batchMapper.insertSms(batch);*/
  		} else {										//운영
  			batch.setMobile(mobile);
  			batch.setSContents(sContents);
  			batchMapper.insertSms(batch);
  		}
        
    }
    
    private void doUpdateLogpass(String cmpnCd, String userId, String logpass) throws Exception {
    	
    	Batch batch = new Batch();

		batch.setCmpnCd(cmpnCd);
		batch.setUserId(userId);
		batch.setLogpass(logpass);
		
        String encryptedPwd = passwordEncryptionService.encryptPasswordWithSalt(batch.getLogpass());
        batch.setScrtNo(encryptedPwd);
        
		batchMapper.updatePass(batch);
        
    }

    private void doMhGetList(String cmpnCd, String empNo, String frDate, String empNm, String deptNm, String eMail) throws Exception {
    	
    	String mhStr = "";
    	String mhHStr = "";
    	String mhDStr = "";

    	List<EasyHashMap<String, Object>> mhList = new ArrayList<EasyHashMap<String, Object>>();
    	mhList = batchMapper.getMhList3(empNo, frDate);
		
    	mhHStr = "<br>기술기획팀에서 안내드립니다.<br>"+empNm+" 님은 당일 MH를 입력하지 않으셨습니다.<br>작성 후 승인 요청하시기 바랍니다.<br>(ERP - M/H관리 - Man Hour 등록)";
    	mhDStr = "MH 입력 요청";
		
		for (EasyHashMap<String, Object> mhInfo : mhList) {
			mhStr += String.valueOf(mhInfo.get("dtCal"));
			mhStr += "<br>";
    	}
		mailService.mailSend6("MH 미입력 안내","당일 MH 입력", mhDStr, cmpnCd, empNo, empNm, deptNm, eMail, mhStr, mhHStr);
    }

    private void doMhGetList2(String cmpnCd, String empNo, String frDate, String empNm, String deptNm, String eMail) throws Exception {
    	
    	String mhStr = "";
    	String mhHStr = "";
    	String mhDStr = "";

    	List<EasyHashMap<String, Object>> mhList = new ArrayList<EasyHashMap<String, Object>>();
    	mhList = batchMapper.getMhList4(empNo, frDate);

    	mhHStr = "<br>기술기획팀에서 안내드립니다.<br>"+empNm+" 님은 당일 MH 입력 후 승인요청 하지 않은 상태입니다.<br>승인 요청하시기 바랍니다.<br>(ERP - M/H관리 - Man Hour 등록)";
    	mhDStr = "MH 승인 요청 안내";
		
		for (EasyHashMap<String, Object> mhInfo : mhList) {
			mhStr += String.valueOf(mhInfo.get("dtCal"));
			mhStr += "<br>";
    	}
		mailService.mailSend6("MH 승인 요청 안내","당일 입력하신 MH 승인 요청", mhDStr, cmpnCd, empNo, empNm, deptNm, eMail, mhStr, mhHStr);
    }

    private void doMhGetList3(String cmpnCd, String empNo, String frDate, String empNm, String deptNm, String eMail) throws Exception {
    	
    	String mhStr = "";
    	String mhHStr = "";
    	String mhDStr = "";

    	List<EasyHashMap<String, Object>> mhList = new ArrayList<EasyHashMap<String, Object>>();
    	mhList = batchMapper.getMhList7(empNo, frDate);

    	mhHStr = "<br>기술기획팀에서 안내드립니다.<br>"+empNm+" 님은 아래의 해당일에 MH를 입력하지 않으셨습니다.<br>작성 후 승인 요청하시기 바랍니다.<br>(ERP - M/H관리 - Man Hour 등록)<br> ※ 파견복귀자 혹은 신규 입사자는 복귀일/입사일 부터 작성 바랍니다.";
    	mhDStr = "당월 MH 입력 요청";
		
		for (EasyHashMap<String, Object> mhInfo : mhList) {
			mhStr += String.valueOf(mhInfo.get("dtCal"));
			mhStr += "<br>";
    	}
		mailService.mailSend6("당월 MH 입력 안내","당월 미입력 MH에 대해 입력 및 승인요청", mhDStr, cmpnCd, empNo, empNm, deptNm, eMail, mhStr, mhHStr);
    }
}