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.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.finance.BpmOAFinanceCreateReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAFinanceDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAFinanceMapper;
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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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_FINANCE_NOT_EXISTS;

/**
 * OA 活动经费申请 Service 实现类
 *
 * @author 符溶馨

 */
@Service
@Validated
public class BpmOAFinanceServiceImpl extends BpmOABaseService implements BpmOAFinanceService{

    /**
     * OA 活动经费的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_finance_2";

    @Resource
    private BpmOAFinanceMapper financeMapper;

    @Resource
    private BpmProcessInstanceService processInstanceService;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Override
    public Long createFinance(Long userId, BpmOAFinanceCreateReqVO createReqVO) {

        //插入OA 活动经费申请
        BpmOAFinanceDO finance = BeanUtils.toBean(createReqVO, BpmOAFinanceDO.class)
                .setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        financeMapper.insert(finance) ;

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

        // 将工作流的编号，更新到 OA 活动经费单中
        financeMapper.updateById(new BpmOAFinanceDO().setId(finance.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 finance.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinanceResult(String processInstanceId, Long id, Integer result) {

        validateLeaveExists(id);
        financeMapper.updateById(new BpmOAFinanceDO().setId(id).setResult(result));
    }

    @Override
    public BpmOAFinanceDO getByProcessInstanceId(String processInstanceId) {

        return financeMapper.selectOne(BpmOAFinanceDO::getProcessInstanceId, processInstanceId);
    }

    @Override
    public BpmOAFinanceDO getFinance(Long id) {
        return financeMapper.selectById(id);
    }

    private void validateLeaveExists(Long id) {
        if (financeMapper.selectById(id) == null) {
            throw exception(OA_FINANCE_NOT_EXISTS);
        }
    }
}
