package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProcessTypeEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProcessRelationDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProcessRelation;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProcessRelationMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProcessRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

@Service
public class ProcessRelationServiceImpl extends BaseService<ProcessRelationDto, ProcessRelation, ProcessRelationMapper> implements IProcessRelationService {


    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    /**
     * 保存资源流程关系信息
     *
     * @param instanceId 流程实例id
     * @param sourceId 资源id
     * @param processName 流程名称（文字）
     */
    @Override
    public void savePR(String instanceId, Long sourceId, String processName){
        //此处不给state赋值，待流程执行更新state字段
        ProcessRelation processRelation = new ProcessRelation();
        processRelation.setInstanceId(instanceId);
        processRelation.setSourceId(sourceId);
        processRelation.setDefName(processName);
        processRelation.setDefCode(ProcessTypeEnum.getCodeByName.get(processName));
        this.save(processRelation);
    }

    /**
     * 更新资源流程关系信息 state字段
     *
     * @param instanceId 流程实例id
     * @Param taskName 任务节点名称，可为null
     */
    @Override
    public void updateState(String instanceId,String taskName){
        LambdaQueryWrapper<ProcessRelation> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ProcessRelation::getInstanceId,instanceId);
        ProcessRelation processRelation = this.getOne(wrapper);
        try {
            if(ValidationUtil.isEmpty(taskName)) {
                taskName = projectInitiationService.getFlowTaskName(instanceId);
            }
            processRelation.setStatus(taskName);
            this.updateById(processRelation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
