package cn.palmte.work.service;

import cn.palmte.work.model.ActTaskDefRepository;
import cn.palmte.work.pojo.ActProcDef;
import cn.palmte.work.utils.ActUtil;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.jfunc.common.db.QueryHelper;
import top.jfunc.common.db.bean.Page;
import top.jfunc.common.db.utils.Pagination;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class ActProcDefService {
    private static final Logger logger = LoggerFactory.getLogger(ActProcDefService.class);
    @Autowired
    private RepositoryService repositoryService; //管理流程定义  与流程定义和部署对象相关的Service
    @Autowired
    private ActTaskDefRepository actTaskDefRepository;
    @Autowired
    private ActUtil actUtil;
    @Autowired
    Pagination pagination;


    public Page<ActProcDef> list(ConcurrentHashMap<String, String> searchInfo, int pageNumber, int pageSize) {
        String select = "select p.ID_ as id,p.NAME_ as procName,p.KEY_ as procKey,p.VERSION_ as version,p.DEPLOYMENT_ID_ as deploymentId,p.RESOURCE_NAME_ as resourceName,\n" +
                " p.DGRM_RESOURCE_NAME_ as dgrmResourceName,p.SUSPENSION_STATE_ as suspensionState, d.DEPLOY_TIME_ as deployTime ";
        QueryHelper queryHelper = new QueryHelper(select, " act_re_procdef p LEFT JOIN act_re_deployment d on p.DEPLOYMENT_ID_ = d.ID_");
        String name = searchInfo.get("name");
        queryHelper.addCondition(StringUtils.isNotEmpty(name), "(p.NAME_=? or p.KEY_=?)", name, name);
        queryHelper.addOrderProperty("p.KEY_,p.VERSION_", false);
        return pagination.paginate(queryHelper.getSql(), ActProcDef.class, pageNumber, pageSize);
    }


    /**
     * 创建默认的png
     *
     * @param response
     * @param deploymentId
     * @throws IOException
     */
    public void createProcDefPng(HttpServletResponse response, String deploymentId) throws IOException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        // 获取bpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        actUtil.responsePng(response, bpmnModel, new ArrayList<>(), new ArrayList<>());
    }




    @Transactional(rollbackFor = Exception.class)
    public void deleteDeployment(String deploymentId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        actTaskDefRepository.deleteByProcDefId(processDefinition.getId());

        //repositoryService.deleteDeployment(deploymentId); 		//不带级联的删除，此删除只能删除没有启动的流程，否则抛出异常 .act_re_deployment，act_re_procdef 和  act_ge_bytearray 三张表中相关数据都删除
        repositoryService.deleteDeployment(deploymentId, true);    //级联删除，不管流程是否启动，都可以删除
    }


    /**
     * 挂起与激活
     *
     * @param procDefId
     * @param status
     */
    public void suspend(String procDefId, int status) {
        if (1 == status) {
            repositoryService.activateProcessDefinitionById(procDefId, true, null);
        } else {
            repositoryService.suspendProcessDefinitionById(procDefId, true, null);
        }
    }
}
