package com.yunzhupaas.flowable.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.flowable.entity.NodeRecordEntity;
import com.yunzhupaas.flowable.mapper.NodeRecordMapper;
import com.yunzhupaas.flowable.model.record.NodeRecordModel;
import com.yunzhupaas.flowable.service.NodeRecordService;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.RandomUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类的描述
 *
 * @author YUNZHUPAASYUNZHUPAAS开发组
 * @version 5.0.x
 * @since 2024/6/25 17:08
 */
@Service
public class NodeRecordServiceImpl extends SuperServiceImpl<NodeRecordMapper, NodeRecordEntity>
        implements NodeRecordService {
    @Override
    public List<NodeRecordEntity> getList(String taskId) {
        QueryWrapper<NodeRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(NodeRecordEntity::getTaskId, taskId).orderByAsc(NodeRecordEntity::getCreatorTime);
        return this.list(wrapper);
    }

    @Override
    public void create(NodeRecordModel model) {
        NodeRecordEntity entity = JsonUtil.getJsonToBean(model, NodeRecordEntity.class);
        entity.setId(RandomUtil.uuId());
        this.save(entity);
    }

    @Override
    public void update(NodeRecordModel model) {
        QueryWrapper<NodeRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(NodeRecordEntity::getTaskId, model.getTaskId())
                .eq(NodeRecordEntity::getNodeCode, model.getNodeCode());
        if (ObjectUtil.isNotEmpty(model.getNodeId())) {
            wrapper.lambda().eq(NodeRecordEntity::getNodeId, model.getNodeId());
        }
        wrapper.lambda().orderByDesc(NodeRecordEntity::getCreatorTime);
        List<NodeRecordEntity> list = this.list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            NodeRecordEntity entity = list.get(0);
            entity.setNodeStatus(model.getNodeStatus());
            this.updateById(entity);
        }
    }
}
