package com.junmp.junmpProcess.service.impl;

import com.junmp.junmpProcess.entity.ProcessTemplates;
import com.junmp.junmpProcess.service.IFlowDefinitionService;
import com.junmp.junmpProcess.service.Repository.ProcessTemplateService;
import com.junmp.jyzb.api.bean.query.processReq.SuspendOrActivateDefinitionReq;
import com.junmp.v2.common.bean.response.ApiRes;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 流程定义
 *
 * @author Tony
 * @date 2021-04-03
 */
@Service
@Slf4j
public class FlowDefinitionServiceImpl  implements IFlowDefinitionService {
    @Autowired
    private ProcessTemplateService processTemplateService;

    @Resource
    private RepositoryService repositoryService;

    @Override
    public Boolean updateState(SuspendOrActivateDefinitionReq req) {
        ProcessTemplates processTemplates = processTemplateService.getById(req.getFormId());
        if (req.getIsStop() == true){
            repositoryService.suspendProcessDefinitionById(req.getProcessDefinitionId(), true, null);
            processTemplates.setIsStop(true);
        }else {
            processTemplates.setIsStop(false);
            repositoryService.activateProcessDefinitionById(req.getProcessDefinitionId(), true, null);
        }
        processTemplates.setUpdated(new Date());
        return   processTemplateService.updateById(processTemplates);//更新表单明细表信息
    }

    @Override
    public ApiRes<String> getLatestDefinitionId(String formId) {
        String defId="";
        ProcessDefinition ProDef=repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("Process_"+formId)
                .latestVersion()
                .singleResult();
        if(ProDef!=null)
        {
            defId=ProDef.getId();
        }

        return ApiRes.success(defId);
    }
}
