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

import cn.iocoder.yudao.framework.common.pojo.UploadUserFile;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.project.BpmOAProjectCreateReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAProjectDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAProjectMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import cn.iocoder.yudao.module.bpm.service.task.BpmHistoryProcessInstanceService;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import cn.iocoder.yudao.module.system.api.project.ProjectApi;
import cn.iocoder.yudao.module.system.api.project.dto.ProjectDTO;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_PROJECT_NOT_EXISTS;

/**
 * OA 项目申请 Service 实现类
 *
 * @author 符溶馨

 */
@Service
@Validated
public class BpmOAProjectServiceImpl extends BpmOABaseService implements BpmOAProjectService{

    /**
     * OA 项目申请对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_project_2";

    @Resource
    private BpmOAProjectMapper projectMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Resource
    private BpmProcessInstanceService bpmProcessInstanceService;

    @Resource
    private ProjectApi projectApi;

    @Override
    public Long createProject(Long userId, BpmOAProjectCreateReqVO createReqVO) {

        //插入OA 项目申请
        BpmOAProjectDO project = BeanUtils.toBean(createReqVO, BpmOAProjectDO.class)
                .setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        projectMapper.insert(project) ;

        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        String processInstanceId = processInstanceApi.createProcessInstance(userId,
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(project.getId()))).getCheckedData();

        // 将工作流的编号，更新到 OA 项目申请单中
        projectMapper.updateById(new BpmOAProjectDO().setId(project.getId()).setProcessInstanceId(processInstanceId));

        // 判断是否为重新发起的流程
        if (createReqVO.getProcessInstanceId() != null && createReqVO.getResult() == 3) {

            historyProcessInstanceService.createHistoryProcessInstance(processInstanceId, createReqVO.getProcessInstanceId());
        }

        List<UploadUserFile> fileItems = createReqVO.getFileItems() ;
        //这里的逻辑，如果fileItems不为空，且有数据，那么说明是上传了附件的，则需要更工作流文件表对应的实例Id
        if (fileItems != null && !fileItems.isEmpty()) {
            uploadBpmFileProcessInstanceId(processInstanceId,fileItems) ;
        }
        return project.getId();
    }

    @Override
    public void updateProjectResult(String processInstanceId, Long id, Integer result) {

        BpmOAProjectDO project = validateLeaveExists(id);
        //审核通过 （最后节点）
        if (BpmProcessInstanceResultEnum.APPROVE.getResult().equals(result)) {

            ProcessInstance instance = bpmProcessInstanceService.getProcessInstance(processInstanceId);

            if (instance.isEnded()) {

                // 同步创建 项目
                projectApi.create(BeanUtils.toBean(project, ProjectDTO.class).setStatus(1));
            }
        }

        projectMapper.updateById(new BpmOAProjectDO().setId(id).setResult(result));
    }

    private BpmOAProjectDO validateLeaveExists(Long id) {
        BpmOAProjectDO project = projectMapper.selectById(id);
        if (project == null) {
            throw exception(OA_PROJECT_NOT_EXISTS);
        }
        return project;
    }

    @Override
    public BpmOAProjectDO getProject(Long id) {

        return projectMapper.selectById(id);
    }

    @Override
    public BpmOAProjectDO getByProcessInstanceId(String processInstanceId) {

        return projectMapper.selectOne(BpmOAProjectDO::getProcessInstanceId, processInstanceId);
    }
}
