package cn.iocoder.yudao.module.bpm.api.model;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.bpm.api.model.vo.BpmModelRpcVO;
import cn.iocoder.yudao.module.bpm.service.definition.dto.BpmModelMetaInfoRespDTO;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Model;
import org.flowable.engine.repository.ModelQuery;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

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

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * Flowable 流程实例 Api 实现类
 *
 * @author jason
 */
@RestController
@Validated
public class BpmModelApiImpl implements BpmModelApi {

    @Resource
    private RepositoryService repositoryService;


    @Override
    public CommonResult<List<BpmModelRpcVO>> getModelList() {
        ModelQuery modelQuery = repositoryService.createModelQuery();
        /**对模型添加租户*/
        modelQuery.modelTenantId(TenantContextHolder.getTenantId().toString());
        // 执行查询
        List<Model> models = modelQuery.orderByCreateTime().desc().list();
        List<BpmModelRpcVO> list = new ArrayList<>();
        // -- 需要过滤的 - 列表
        List<String> filterList = Arrays.asList("work_task");
        for (Model model : models) {
            BpmModelMetaInfoRespDTO metaInfo = JsonUtils.parseObject(model.getMetaInfo(), BpmModelMetaInfoRespDTO.class);
            if (filterList.contains(model.getKey()) || metaInfo == null) {
                continue;
            }
            list.add(new BpmModelRpcVO().setId(model.getId())
                    .setName(model.getName())
                    .setProcessImg(metaInfo.getProcessImg())
                    .setFormCustomCreatePath(metaInfo.getFormCustomCreatePath()));
        }
        return success(list);
    }
}
