package sgc.portal.cw.cw1403.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.cw1403.model.CW14030001U;
import sgc.portal.cw.cw1403.dto.CW14030001USearch;
import sgc.portal.cw.cw1403.persistence.CW14030001UMapper;

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

@Service
public class CW14030001UService {
    private final CW14030001UMapper mapper;

    public CW14030001UService(CW14030001UMapper mapper) {
        this.mapper = mapper;
    }

    public List<EasyHashMap<String, Object>> getList(CW14030001USearch search) {
    	if(search.getEmpNo().isEmpty()) {
            return mapper.getList(search);
    	} else {
    		String resiNo = mapper.selectResiNo(search);
    		search.setResiNo(resiNo);
            return mapper.getList(search);
    	}
    }

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

    private void insert(CW14030001U cW14030001U) {
		String resiNo = mapper.selectResiNo(cW14030001U);
		int seq = mapper.selectSeq(cW14030001U);
		cW14030001U.setResiNo(resiNo);
		cW14030001U.setSeq(seq);
        mapper.insert(cW14030001U);
    }

    private void update(CW14030001U cW14030001U) {
		String resiNo = mapper.selectResiNo(cW14030001U);
		cW14030001U.setResiNo(resiNo);
        mapper.update(cW14030001U);
    }

    private void delete(CW14030001U cW14030001U) {
        mapper.delete(cW14030001U);
    }
    
    @Transactional
    public Map<String, String> draw(CW14030001USearch search) {
    	
    	Map<String,String> result = new HashMap<>();

        mapper.draw(search);
        
        return result;
    }
}
