package cn.palmte.work.service;


import cn.palmte.work.config.activiti.ActConstant;
import cn.palmte.work.model.ActTaskDef;
import cn.palmte.work.model.Admin;
import cn.palmte.work.model.AdminRepository;
import cn.palmte.work.utils.ActUtil;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
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;

import java.util.List;


/**
 * 流程节点监听
 */
@Service
public class ActListenerService {
    private static final Logger logger = LoggerFactory.getLogger(ActListenerService.class);


    @Autowired
    private ActTaskDefService actTaskDefService;

    @Autowired
    private ProjectInstanceService projectInstanceService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ActUtil actUtil;

    @Autowired
    private AdminRepository adminRepository;

    /**
     * 任务节点创建后监听 动态设置审批人
     *
     * @param delegateTask
     * @throws Exception
     */
    public void create(DelegateTask delegateTask) throws Exception {
        String procInsId = delegateTask.getProcessInstanceId();
        logger.info("--节点创建后监听--  procInsId:{},  {}", procInsId, delegateTask);
        logger.info("**** rwcjjt【{}】任务创建监听 procInsId:{} **** ", delegateTask, procInsId);

        String procDefId = delegateTask.getProcessDefinitionId();
        String taskDefKey = delegateTask.getTaskDefinitionKey();
        List<String> candidateUsers = actTaskDefService.findCandidateUsers(procDefId, procInsId, taskDefKey);
        logger.info("**** rwcjjt 任务创建监听 查询候选人 procInsId:{}，任务名称：{}，候选人：{} **** ", procInsId, delegateTask.getName(), candidateUsers);

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult();
        updateProjectApprover(candidateUsers, processInstance, procDefId, taskDefKey);

        delegateTask.addCandidateUsers(candidateUsers);
    }


    /**
     * 更新项目审批人 四算业务需要
     *
     * @param candidateUsers
     * @param processInstance
     */
    private void updateProjectApprover(List<String> candidateUsers, ProcessInstance processInstance, String procDefId, String taskDefKey) {
        String businessKey = processInstance.getBusinessKey();
        ActTaskDef actTaskDef = actTaskDefService.findFirstByProcDefIdAndTaskKey(procDefId, taskDefKey);

        try {
            int adminId = 0;
            if (!candidateUsers.isEmpty() && actTaskDef!=null && actTaskDef.getTaskIndex() != ActConstant.TASK_INDEX_FIRST_USER_TASK) {
                //回退到发起节点 审批人设置为空
                for (String id : candidateUsers) {
                    Admin one = adminRepository.findOne(Integer.parseInt(id));
                    if (!one.isDeleted() && one.getEnabled() == 1) {
                        //找到有效账号 发送任务
                        adminId = one.getId();
                        break;
                    }
                }
            }
            logger.info("**** rwcjjt 任务创建监听 更新审批人 procInsId:{}, projectId:{}, adminId:{} **** ",
                    processInstance.getProcessInstanceId(), businessKey, adminId);
            projectInstanceService.updateApprover(Integer.parseInt(businessKey), adminId);
        } catch (Exception e) {
            logger.error("", e);
        }

    }
}
