package com.jy.flow.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.flow.mapper.WarmFlowMapper;
import com.jy.flow.model.dto.FlowHisTaskDto;
import com.jy.flow.model.dto.FlowTaskDto;
import com.jy.flow.model.enums.FlowStatusEnum;
import com.jy.flow.model.vo.FlowTaskVo;
import com.jy.flow.service.ExecuteService;
import com.jy.framework.exception.ServiceException;
import com.jy.framework.satoken.LoginContext;
import jakarta.annotation.Resource;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.Instance;
import org.dromara.warm.flow.core.service.InsService;
import org.dromara.warm.flow.core.service.TaskService;
import org.dromara.warm.flow.orm.entity.FlowHisTask;
import org.dromara.warm.flow.orm.entity.FlowInstance;
import org.springframework.stereotype.Service;

@Service
public class ExecuteServiceImpl implements ExecuteService {

    @Resource
    private WarmFlowMapper flowMapper;

    @Resource
    private TaskService taskService;

    @Resource
    private InsService insService;

    @Override
    public Page<FlowTaskVo> toDoPage(FlowTaskDto dto) {
        return flowMapper.toDoPage(dto.getPage(), dto);
    }

    @Override
    public Page<FlowHisTask> donePage(FlowHisTaskDto dto) {
        return flowMapper.donePage(dto.getPage(), dto);
    }

    @Override
    public Page<FlowHisTask> copyPage(FlowTaskDto dto) {
        return flowMapper.copyPage(dto.getPage(), dto);
    }

    @Override
    public void retrieveByInstanceId(Long instanceId) {
        FlowParams flowParams = new FlowParams();
        flowParams.flowStatus(FlowStatusEnum.RETRIEVE.getKeyStr());
        flowParams.hisStatus(FlowStatusEnum.RETRIEVE.getKeyStr());
        flowParams.handler(LoginContext.getUserId().toString());
        taskService.retrieve(instanceId, flowParams);
    }

    @Override
    public void retrieveByBusinessId(Long businessId) {
        retrieveByBusinessId(businessId + "");
    }

    @Override
    public void retrieveByBusinessId(String businessId) {
        Instance instance = insService.getOne(new FlowInstance().setBusinessId(businessId));
        if (instance == null || ObjectUtil.notEqual(instance.getBusinessId(), businessId)) {
            throw new ServiceException("未知流程实例");
        }

        retrieveByInstanceId(instance.getId());
    }

}
