package sgc.portal.cw.cw1503.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.cw1503.model.CW15030001U;
import sgc.portal.cw.cw1503.dto.CW15030001USearch;
import sgc.portal.cw.cw1503.persistence.CW15030001UMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CW15030001UService {
    private final CW15030001UMapper mapper;

    public CW15030001UService(CW15030001UMapper mapper) {
        this.mapper = mapper;
    }

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

    @Transactional
    public Map<String, String> save(List<CW15030001U> CW15030001U) {
    	
    	Map<String,String> result = new HashMap<>();
    	
    	for (CW15030001U cW15030001U : CW15030001U) {
            switch (cW15030001U.getRowStatus()) {
                case GridRowStatus.CREATED:
                	if(cW15030001U.getEmpNo() != "" && cW15030001U.getDeptCd() == "") {
                		String deptCd = mapper.selectEmpInfo(cW15030001U);
                		cW15030001U.setDeptCd(deptCd);
                		
                    	if(deptCd == null) {
                    		result.put("errCode", "1");
                    		result.put("errMsg", "사번이 존재하지 않습니다.");
                    	} else {
                            insert(cW15030001U);
                            break;
                    	}
                	} else {
                        insert(cW15030001U);
                        break;
                	}
                case GridRowStatus.UPDATED:
                    update(cW15030001U);
                    break;
                case GridRowStatus.DELETED:
                	
                	int count1 = mapper.selectAtchfileIdCount(cW15030001U);
                	if(count1 != 0) {
                		mapper.deleteAtchfileId(cW15030001U);	
                	}
                	mapper.delete(cW15030001U);
                    break;
                default:
                    break;
            }
        }
    	return result;
    }

    private void insert(CW15030001U cW15030001U) {
        mapper.insert(cW15030001U);
    }

    private void update(CW15030001U cW15030001U) {
        mapper.update(cW15030001U);
    }
}
