package com.leanwo.activiti.rest.base;

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

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leanwo.activiti.dto.approver.WorkflowDefData;
import com.leanwo.activiti.dto.base.BpmnCreateResponse;
import com.leanwo.activiti.exception.ServerException;
import com.leanwo.activiti.service.base.ApproveEditService;
import com.leanwo.activiti.service.base.BpmnCreateBo;
import com.leanwo.activiti.service.base.WorkflowService;
import com.leanwo.activiti.service.base.impl.UserPreference;
import com.leanwo.activiti.util.StringUtil;

/**
 * 
 * 审批编辑服务
 * 
 * @author YangZhiJie
 *
 */
@RestController
@RequestMapping("/workflow-prodog/ApproveEditResource")
public class ApproveEditResource {
	
	private static Logger logger = LoggerFactory.getLogger(ApproveEditResource.class);
	
	@Inject 
	private ApproveEditService approveEditService;
	
	@Inject
	private ObjectMapper objectMapper;
	
	@Inject
	private WorkflowService workflowService;
	
	/**
	 * 创建流程文件
	 * @author shenchong 2020-09-11 15:21:37
	 * @param json
	 */
	@RequestMapping(value = "/createBpmnFile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
	public BpmnCreateResponse createBpmnFile(@RequestBody String jsonData) {
		logger.debug(jsonData);
		
		if(StringUtil.isEmpty(jsonData)) {
			return null;
		}
		
		WorkflowDefData workflowDefData;
		try {
			workflowDefData = objectMapper.readValue(jsonData, WorkflowDefData.class);
		} catch (JsonProcessingException e) {
			throw new ServerException("生成BPMN文件的数据异常。" + e.getMessage());
		}
		
		BpmnCreateBo bpmnCreateBo = approveEditService.createBpmnFile(workflowDefData);
		

		// 部署的时候，把表单数据，流程数据，高级设置存储在部署附件中
	    Map<String, String> extraStringDatas = new HashMap<String, String>();
	    extraStringDatas.put(UserPreference.FORM_DATA, workflowDefData.getFormDataStr());
	    extraStringDatas.put(UserPreference.PROCESS_DATA, workflowDefData.getProcessDataStr());
	    extraStringDatas.put(UserPreference.ADVANCED_SETTING, workflowDefData.getAdvancedSettingDataStr());
	    
		String deploymentId = workflowService.deploy(bpmnCreateBo.getBpmnModel(), extraStringDatas);
		
		
		BpmnCreateResponse bpmnCreateResponse = new BpmnCreateResponse();
		bpmnCreateResponse.setDeploymentId(deploymentId);
		bpmnCreateResponse.setUserSelectDefineList(bpmnCreateBo.getUserSelectDefineList());
		bpmnCreateResponse.setPreviousAssigneeSelectDefineList(bpmnCreateBo.getPreviousAssigneeSelectDefineList());
		
		return bpmnCreateResponse;
	}
}