package sgc.portal.cw.cw0604.service;

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.cw.cw0604.dto.CW06040001USearch;
import sgc.portal.cw.cw0604.model.CW06040001U;
import sgc.portal.cw.cw0604.persistence.CW06040001UMapper;
import sgc.portal.com.sym.mail.service.MailService;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CW06040001UService {
    private final CW06040001UMapper mapper;
    private final MailService mailService;

    public CW06040001UService(CW06040001UMapper mapper, MailService mailService) {
        this.mapper = mapper;
        this.mailService = mailService;
    }

    public List<EasyHashMap<String, Object>> getList(CW06040001USearch search) {
        return mapper.getList(search);
    }

    @Transactional
    public Map<String, String> save(List<CW06040001U> CW06040001U) {
    	
    	Map<String,String> result = new HashMap<>();
    	
    	for (CW06040001U cW06040001U : CW06040001U) {
            switch (cW06040001U.getRowStatus()) {
                case GridRowStatus.CREATED:
                    insert(cW06040001U);
                    break;
                case GridRowStatus.UPDATED:
                    update(cW06040001U);
                    break;
                case GridRowStatus.DELETED:
                    delete(cW06040001U);
                    break;
                default:
                    break;
            }
        }
    	return result;
    }

    private void insert(CW06040001U cW06040001U) {
        mapper.insert(cW06040001U);
    }

    private void update(CW06040001U cW06040001U) {
        mapper.update(cW06040001U);
    }

    private void delete(CW06040001U cW06040001U) {
        mapper.delete(cW06040001U);
    }
    
    @Transactional
    public Map<String, String> sendMail(List<CW06040001U> CW06040001U) {
    	
    	Map<String,String> result = new HashMap<>();

        for (CW06040001U cW06040001U : CW06040001U) {
    		
        	StringBuffer sContent = new StringBuffer();
    		
        	String srecvAddress 	= mapper.selectUserEmail(cW06040001U);
        	System.out.println("===================srecvAddress: " + srecvAddress);
    		String cmpnCd = cW06040001U.getCmpnCd();
        	String sSubject 	= mapper.selectEmailTitle(cW06040001U);
    		String ssubSubject = sSubject;
    		String sSender = cW06040001U.getEmpNo();	
    		sContent.append(mapper.selectEmailConts(cW06040001U));

			mailService.mailSend4(cmpnCd, sSubject, ssubSubject, sContent, sSender, srecvAddress);
			
        }
        
        return result;
    }
}
