package com.activiti6.service.impl;

import com.activiti6.controller.ModelerController;
import com.activiti6.entity.MyFormDataExample;
import com.activiti6.mapper.MyFormDataMapper;
import com.activiti6.service.ModelService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ModelServiceImpl implements ModelService {
    private static final Logger logger = LoggerFactory.getLogger(ModelerController.class);

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private MyFormDataMapper myFormDataMapper;

    @Override
    public void deleteProcessInstance(String modelId) {
        logger.info("删除流程实例入参modelId：{}", modelId);
        Model modelData = repositoryService.getModel(modelId);
        //deleForm(modelData);
        if (null != modelData) {
            try {
                ProcessInstance pi = runtimeService.createProcessInstanceQuery().processDefinitionKey(modelData.getKey()).singleResult();
                if (null != pi) {
                    runtimeService.deleteProcessInstance(pi.getId(), "");
                    historyService.deleteHistoricProcessInstance(pi.getId());
                }
                repositoryService.deleteModel(modelId);
            } catch (Exception e) {
                logger.error("删除流程实例服务异常：{}", e);
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    private void deleForm(Model modelData) {
        String key = modelData.getKey();
        Integer version = modelData.getVersion();
        MyFormDataExample myFormDataExample = new MyFormDataExample();
        MyFormDataExample.Criteria criteria = myFormDataExample.createCriteria();
        criteria.andModelKeyEqualTo(key);
        criteria.andModelVersionEqualTo(version);
        myFormDataMapper.deleteByExample(myFormDataExample);
    }
}
