package sgc.portal.cd.cd0301.service;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sgc.portal.cd.cd0301.dto.CD03010001PSearch;
import sgc.portal.cd.cd0301.model.CD03010001P;
import sgc.portal.cd.cd0301.persistence.CD03010001PMapper;

@Service
public class CD03010001PService {

	private final CD03010001PMapper mapper;
	
    public CD03010001PService(CD03010001PMapper mapper) {
        this.mapper = mapper;
    }
	
    /**
     * 작업지시서 작성(팝업) 조회
     * @param search
     * @return
     */
	public CD03010001P selectConWkiOdr(CD03010001PSearch search) {
		CD03010001P cd03010001p = mapper.selectConWkiOdr(search);
		String[] wkiNoArr = cd03010001p.getWkiNo().split("-");//작업지시번호
		cd03010001p.setWkiNo1(wkiNoArr[1]);
		cd03010001p.setWkiNo2(wkiNoArr[2]);
		cd03010001p.setWkiNo3(wkiNoArr[3]);
		return cd03010001p;
	}
    
	/**
	 * 작업지시서 작성(팝업) 저장
	 * @param cD03010001P
	 * @return
	 */
    @Transactional
	public Map<String, String> saveConWkiOdr(CD03010001P cD03010001P) {
    	Map<String,String> result = new HashMap<>();
    	
    	if(StringUtils.isNotBlank(cD03010001P.getWkiSeq())) {
    		if(cD03010001P.getCallId().equals("CD03010001U")) {//작업지시서 작성
    			mapper.updateConWkiOdr(cD03010001P);
    		}else if(cD03010001P.getCallId().equals("CD03020001U")) {//작업지시서 견적(사전시행)
    			mapper.updateConWkiOdrEst(cD03010001P);		
    		}
    	}else {//신규일경우
        	cD03010001P.setWkiSeq(mapper.selectWkiSeq());//작업지시순번 조회
    		mapper.saveConWkiOdr(cD03010001P);
    	}
    	
		result.put("wkiSeq", cD03010001P.getWkiSeq());
		return result;
	}

    /**
     * 작업지시서 작성(팝업) 삭제
     * @param cD03010001P
     * @return
     */
    @Transactional
	public Map<String, String> deleteConWkiOdr(CD03010001P cD03010001P) {
    	Map<String,String> result = new HashMap<>();
    	mapper.deleteConWkiOdr(cD03010001P);
		return result;
	}
    
    /**
     * 작업지시서 작성(팝업) 결재 후처리
     * @param cD03010001P
     * @return
     */
    @Transactional
	public Map<String, String> approval(CD03010001P cD03010001P) {
    	Map<String,String> result = new HashMap<>();
    	if(cD03010001P.getCallId().equals("CD03010001U")) {//작업지시서 작성
    		mapper.approval(cD03010001P);	
    	}else if(cD03010001P.getCallId().equals("CD03020001U")) {//작업지시서 견적(사전시행)
    		mapper.approvalEst(cD03010001P);
    	}
		return result;
	}

}
