package sgc.portal.cd.cd0302.service;

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.util.SessionUtil;
import sgc.portal.cd.cd0301.model.CD03010001P;
import sgc.portal.cd.cd0302.dto.CD03020001PSearch;
import sgc.portal.cd.cd0302.persistence.CD03020001PMapper;
import sgc.portal.com.sym.mail.service.MailService;
import sgc.portal.com.sym.user.model.UserDetails;

@Service
public class CD03020001PService {

	private final CD03020001PMapper mapper;
	private final MailService mailService;
	
    public CD03020001PService(CD03020001PMapper mapper, MailService mailService) {
        this.mapper = mapper;
        this.mailService = mailService;
    }
    
    /**
     * 메일전송 작업지시서 조회
     * @param search
     * @return
     */
	public List<EasyHashMap<String, Object>> selectConWkiOdrList(CD03020001PSearch search) {
		return mapper.selectConWkiOdrList(search);
	}

	/**
	 * 작업지시서 메일전송
	 */
	@Transactional
	public Map<String, String> sendMailConWkiOdr(CD03010001P cD03010001P) {
		Map<String, String> result = new HashMap<>();
		UserDetails userDetails = SessionUtil.getUserDetails();
		StringBuffer sContent = new StringBuffer();
		String cmpnCd = userDetails.getCmpnCd();
		String srecvAddress = cD03010001P.getCovendChrgrEmail();
		String sSender = userDetails.getEmpNo();	
		String sSubject = "[SGC이앤씨] 작업지시 요청";
		String ssubSubject = "작업지시 요청";
		
		sContent.append(cD03010001P.getMailCn().toString());
		
		//메일전송
		result = mailService.mailSendWorkOrder(cmpnCd, sSubject, ssubSubject, sContent, sSender, srecvAddress);
		
		cD03010001P.setSndLginId(userDetails.getLginId());
		cD03010001P.setSndEmpNo(userDetails.getEmpNo());
		cD03010001P.setSndEmpNm(userDetails.getUserNm());
		cD03010001P.setSndEmail(result.get("fromEmail"));
		cD03010001P.setRcvName(cD03010001P.getCovendChrgrNm());
		cD03010001P.setRcvEmail(cD03010001P.getCovendChrgrEmail());
		cD03010001P.setMailTtl(sSubject);
		cD03010001P.setContentBase(result.get("contentBase"));
		
		mapper.insertConWkiOdrMailhis(cD03010001P);
		
		//메일전송횟수 UPDATE
		mapper.updateMailsendCnt(cD03010001P);
		
		return result;
	}
	
}
