package sgc.portal.cw.cw0627.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.cw0627.dto.CW06270001USearch;
import sgc.portal.cw.cw0627.model.CW06270001U;
import sgc.portal.cw.cw0627.persistence.CW06270001UMapper;

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

@Service
public class CW06270001UService {
    private final CW06270001UMapper mapper;

    public CW06270001UService(CW06270001UMapper mapper) {
        this.mapper = mapper;
    }

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

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

    private void insert(CW06270001U cW06270001U) {
    	if(cW06270001U.getSeq() == null) {
    		int seq = mapper.selectSeq(cW06270001U);
    		cW06270001U.setSeq(seq);
    		cW06270001U.setSubSeq(1);
            mapper.insert(cW06270001U);
    	}else {
    		if(cW06270001U.getSubSeq() == null) {
        		int subSeq = mapper.selectSubSeq(cW06270001U);
        		cW06270001U.setSubSeq(subSeq);
                mapper.insert(cW06270001U);
    		}
    	}
    }

    private void update(CW06270001U cW06270001U) {
        mapper.update(cW06270001U);
    }

    private void delete(CW06270001U cW06270001U) {
        mapper.delete(cW06270001U);
    }
}
