package cokr.xit.fims.cmmn.service.bean;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cokr.xit.base.code.service.CodeQuery;
import cokr.xit.base.code.service.bean.CodeBean;
import cokr.xit.fims.cmmn.service.StngService;
import cokr.xit.fims.mngt.Task;
import cokr.xit.fims.mngt.Vltn;
import cokr.xit.fims.mngt.service.bean.TaskBean;
import cokr.xit.fims.mngt.service.bean.TaskProcessor;
import cokr.xit.fims.mngt.service.bean.VltnBean;
import cokr.xit.foundation.component.AbstractServiceBean;
import cokr.xit.foundation.data.DataObject;

@Service("stngService")
public class StngServiceBean extends AbstractServiceBean implements StngService {
	/** 업무 정보 Bean */
	@Resource(name = "taskBean")
	private TaskBean taskBean;
	/** 위반 정보 Bean */
	@Resource(name = "vltnBean")
	private VltnBean vltnBean;
	@Resource(name = "codeBean")
	private CodeBean codeBean;

	@Override
	public String updateTaskStng(Task task, List<Vltn> vltnList) {
		boolean result = taskBean.update(task);
		if(!result)
			throw new RuntimeException("[F]업무 설정 수정 중 오류가 발생하였습니다.");

		for(Vltn vltn : vltnList) {
			result = vltnBean.update(vltn);
			if(!result)
				throw new RuntimeException("[F]위반 설정 수정 중 오류가 발생하였습니다.");
		}

		return "[S]";
	}

	@Override
	public String createTaskStng(String sggCd, String taskSeCd) {
		Task task = new Task();
		task.setSggCd(sggCd);
		task.setTaskSeCd(taskSeCd);
		CodeQuery cq = new CodeQuery();
		cq.setGroupIDs("FIM054");
		List<DataObject> taskCodes = codeBean.getCodeList(cq);
		for(DataObject taskCodeInfo : taskCodes) {
			if(taskCodeInfo.string("CODE").equals(taskSeCd)) {
				task.setTaskSeNm(taskCodeInfo.string("CODE_VAL"));
			}
		}

		boolean result = taskBean.create(task);
		if(!result)
			throw new RuntimeException("[F]업무 설정 추가 중 오류가 발생하였습니다.");

		String vltnByTask = TaskProcessor.get().getVltnCdGrp(taskSeCd);
		if (isEmpty(vltnByTask)) return "[F]";

		for (DataObject vltnCdInfo: codeBean.getCodeList(new CodeQuery().setGroupIDs(vltnByTask))) {
			Vltn vltn = new Vltn();
			vltn.setSggCd(sggCd);
			vltn.setTaskSeCd(taskSeCd);
			vltn.setVltnCd(vltnCdInfo.string("CODE"));
			vltn.setVltnArtcl(vltnCdInfo.string("CODE_VAL"));

			result = vltnBean.create(vltn);
			if(!result)
				throw new RuntimeException("[F]위반 설정 추가 중 오류가 발생하였습니다.");
		};
		return result ? "[S]" : "[F]";
	}
}