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

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.business.dto.BpmBusinessFormCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.business.vo.BpmBusinessFormCreateReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.business.BpmBusinessFormDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.business.BpmBusinessFormMapper;
import cn.iocoder.yudao.module.bpm.service.business.BpmBusinessFormService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 业务表单 Api 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BpmBusinessFormApiImpl implements BpmBusinessFormApi {

    @Resource
    @Lazy
    private BpmBusinessFormService bpmBusinessFormService;

    @Resource
    private BpmBusinessFormMapper bpmBusinessFormMapper;

    @Override
    public Long createBusinessForm(@Valid BpmBusinessFormCreateReqDTO createReqDTO) {
        // 如果 status=5（系统审批），则直接插入记录，不走流程
        if (createReqDTO.getStatus() != null && createReqDTO.getStatus() == 5) {
            BpmBusinessFormDO businessFormDO = new BpmBusinessFormDO();
            businessFormDO.setBusinessId(createReqDTO.getBusinessId());
            businessFormDO.setBusinessId2(createReqDTO.getBusinessId2());
            businessFormDO.setUserId(createReqDTO.getUserId() != null ? createReqDTO.getUserId() : getLoginUserId());
            businessFormDO.setStatus(5); // 系统审批状态
            businessFormDO.setReadStatus(createReqDTO.getReadStatus() != null ? createReqDTO.getReadStatus() : 1); // 默认已读
            businessFormDO.setCompleteStatus(createReqDTO.getCompleteStatus() != null ? createReqDTO.getCompleteStatus() : 1); // 默认已完成
            businessFormDO.setType(createReqDTO.getType());
            businessFormDO.setProcessInstanceId(createReqDTO.getProcessInstanceId());
            businessFormDO.setTenantId(createReqDTO.getTenantId());
            businessFormDO.setStartTenantId(createReqDTO.getTenantId());
            bpmBusinessFormMapper.insert(businessFormDO);
            return businessFormDO.getId();
        }
        
        // 否则走正常流程
        // 将 DTO 转换为 VO
        BpmBusinessFormCreateReqVO createReqVO = BeanUtils.toBean(createReqDTO, BpmBusinessFormCreateReqVO.class);
        // 调用服务层创建业务表单
        return bpmBusinessFormService.create(createReqVO);
    }

}
