package com.willalp.flow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.utils.StringUtils;
import com.willalp.flow.domain.HsFlowTask;
import com.willalp.flow.mapper.HsFlowTaskMapper;
import com.willalp.flow.service.HsFlowEngineService;
import com.willalp.flow.service.IHsFlowTaskService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

/**
 * 流程任务Service业务层处理
 *
 * @author willalp
 * @date 2022-10-09
 */
@Service
public class HsFlowTaskServiceImpl extends ServiceImpl<HsFlowTaskMapper, HsFlowTask> implements IHsFlowTaskService {
    @Resource
    private HsFlowTaskMapper hsFlowTaskMapper;

    @Resource
    private HsFlowEngineService flowEngineService;

    /**
     * 查询流程任务列表
     *
     * @param hsFlowTask 流程任务
     * @return 流程任务
     */
    @Override
    public List<HsFlowTask> selectHsFlowTaskList(HsFlowTask hsFlowTask) {
        return hsFlowTaskMapper.selectHsFlowTaskList(hsFlowTask);
    }

    @Override
    public void readTask(String taskId) {
        if (StringUtils.isNotBlank(taskId)) {
            hsFlowTaskMapper.readTask(taskId);
        }
    }


    @Async("threadPoolTaskExecutor")
    @Override
    public void removeWaitTimeOutTask(HsFlowTask hsFlowTask) {
        int timeout = 0;
        for (; ; ){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            timeout++;
            hsFlowTask = hsFlowTaskMapper.selectById(hsFlowTask.getId());
            if (StringUtils.isNotBlank(hsFlowTask.getOperator())) {
                break;
            }
            //超过[1]分钟未选择候选人删除任务及提交的表单
            if (timeout >= 60) {
                if (StringUtils.isBlank(hsFlowTask.getOperator())) {
                    flowEngineService.removeBusinessForm(hsFlowTask.getExamplesId(), hsFlowTask.getBusinessId());
                    baseMapper.deleteById(hsFlowTask);
                    break;
                }
            }
        }
    }
}
