package sgc.portal.cw.cw1602.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.cw1602.model.CW16020001U;
import sgc.portal.cw.cw1602.dto.CW16020001USearch;
import sgc.portal.cw.cw1602.persistence.CW16020001UMapper;

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

@Service
public class CW16020001UService {
    private final CW16020001UMapper mapper;

    public CW16020001UService(CW16020001UMapper mapper) {
        this.mapper = mapper;
    }

    public List<EasyHashMap<String, Object>> getList(CW16020001USearch search) {
        return mapper.getList(search);
    }
    
    //상세항목 조회
    public List<EasyHashMap<String, Object>> selectCommonCode(CW16020001USearch search) {
        return mapper.selectCommonCode(search);
    }
    
    //코드마감 조회
    public List<EasyHashMap<String, Object>> selectCodeClose(CW16020001USearch search) {
        return mapper.selectCodeClose(search);
    }
    
    @Transactional
    public Map<String, String> save(List<CW16020001U> CW16020001U) {
    	
    	Map<String,String> result = new HashMap<>();
    	
    	for (CW16020001U cW16020001U : CW16020001U) {
            switch (cW16020001U.getRowStatus()) {
                case GridRowStatus.CREATED:
        	        insert(cW16020001U);
                    break;
                case GridRowStatus.UPDATED:
                    update(cW16020001U);
                    break;
                case GridRowStatus.DELETED:
                	int count1 = mapper.selectAtchfileIdCount(cW16020001U);
                	if(count1 != 0) {
                		mapper.deleteAtchfileId(cW16020001U);	
                	}
                    mapper.delete(cW16020001U);
                    break;
                default:
                    break;
            }
        }
    	return result;
    }

    private void insert(CW16020001U cW16020001U) {
        mapper.insert(cW16020001U);
    }

    private void update(CW16020001U cW16020001U) {
        mapper.update(cW16020001U);
    }
    
    @Transactional
    public Map<String, String> updateStatus(List<CW16020001U> CW16020001U) {
    	
    	Map<String,String> result = new HashMap<>();
    	
        for (CW16020001U cW16020001U : CW16020001U) {
        	updateStatus(cW16020001U);
        }
        return result;
    }
    
    private void updateStatus(CW16020001U cW16020001U) {
        mapper.updateStatus(cW16020001U);
    }
}
