package cn.iocoder.yudao.module.bpm.service.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmHistoryProcessInstanceDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.task.BpmHistoryProcessInstanceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

/**
 * BPM 历史流程实例 Service 实现类
 */
@Service
@Slf4j
@Validated
public class BpmHistoryProcessInstanceServiceImpl implements BpmHistoryProcessInstanceService{

    @Resource
    private BpmHistoryProcessInstanceMapper historyProcessInstanceMapper;

    @Override
    public void createHistoryProcessInstance(String processInstanceId, String historyProcessInstanceId) {

        // 获得历史流程关联记录
        BpmHistoryProcessInstanceDO historyProcessInstanceDO = getHistoryProcessInstanceDO(historyProcessInstanceId);
        if (historyProcessInstanceDO == null) {

            historyProcessInstanceMapper.insert(new BpmHistoryProcessInstanceDO()
                    .setProcessInstanceId(processInstanceId)
                    .setHistoryProcessInstanceIds(Collections.singletonList(historyProcessInstanceId)));
        }else {

            List<String> historyProcessInstanceIds = historyProcessInstanceDO.getHistoryProcessInstanceIds();
            historyProcessInstanceIds.add(historyProcessInstanceId);

            historyProcessInstanceMapper.updateById(historyProcessInstanceDO
                    .setProcessInstanceId(processInstanceId)
                    .setHistoryProcessInstanceIds(historyProcessInstanceIds));
        }
    }

    @Override
    public BpmHistoryProcessInstanceDO getHistoryProcessInstanceDO(String processInstanceId) {

        List<BpmHistoryProcessInstanceDO> list = historyProcessInstanceMapper.selectList(BpmHistoryProcessInstanceDO::getProcessInstanceId, processInstanceId);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        return list.get(0);
    }
}
