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

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.reimbursement.BpmOAReimbursementCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.upload.UploadUserFile;
import cn.iocoder.yudao.module.bpm.convert.oa.BpmOAReimbursementConvert;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAImprestDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAReimbursementDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAImprestMapper;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAReimbursementMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
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_REIMBURSEMENT_NOT_EXISTS;

/**
 * 功能描述
 * OA 报销申请 Service 实现类
 *
 * @author: yj
 * @date: 2024年02月09日 15:33
 */
@Service
@Validated
public class BpmOAReimbursementServiceImpl extends BpmOABaseService implements BpmOAReimbursementService{

    /**
     * OA 请假对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_reimbursement";

    @Resource
    private BpmOAReimbursementMapper reimbursementMapper ;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessInstanceService bpmProcessInstanceService;

    @Resource
    private BpmOAImprestService bpmOAImprestService;

    @Resource
    private BpmOAImprestMapper bpmOAImprestMapper;

    @Override
    public Long createReimbursement(Long userId, BpmOAReimbursementCreateReqVO createReqVO) {
        BpmOAReimbursementDO reimbursement = BpmOAReimbursementConvert.INSTANCE.convert(createReqVO).setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        reimbursementMapper.insert(reimbursement) ;

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

        // 将工作流的编号，更新到 OA 报销表单中
        reimbursementMapper.updateById(new BpmOAReimbursementDO().setId(reimbursement.getId()).setProcessInstanceId(processInstanceId));

        //如果是备用金报销，则更新备用金流程status
        if (createReqVO.getDifference() != null) {
            BpmOAImprestDO bpmOAImprestDO = bpmOAImprestService.getImprestByUserId(userId);
            bpmOAImprestMapper.updateById(new BpmOAImprestDO().setId(bpmOAImprestDO.getId()).setStatus(BpmOAImprestDO.IN_PROGRESS));
        }

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

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

        //审核通过 （最后节点）
        if (BpmProcessInstanceResultEnum.APPROVE.getResult().equals(result)) {

            ProcessInstance instance = bpmProcessInstanceService.getProcessInstance(processInstanceId);
            BpmOAImprestDO bpmOAImprestDO = bpmOAImprestMapper.selectByUserId(Long.valueOf(instance.getStartUserId()), BpmOAImprestDO.IN_PROGRESS);

            if (instance.isEnded() && bpmOAImprestDO != null) {

                //将相应备用金申请状态改为 已报销
                bpmOAImprestMapper.updateById(new BpmOAImprestDO().setId(bpmOAImprestDO.getId()).setStatus(BpmOAImprestDO.FLAG_TRUE));
            }
        }

        // -- 自己取消
        // -- 审核拒绝
        //所有关联的采购申请改为 未支付状态
        if (BpmProcessInstanceResultEnum.REJECT.getResult().equals(result)
                || BpmProcessInstanceResultEnum.CANCEL.getResult().equals(result)
                || BpmProcessInstanceResultEnum.BACK.getResult().equals(result)) {

            ProcessInstance instance = bpmProcessInstanceService.getProcessInstance(processInstanceId);
            BpmOAImprestDO bpmOAImprestDO = bpmOAImprestMapper.selectByUserId(Long.valueOf(instance.getStartUserId()), BpmOAImprestDO.IN_PROGRESS);

            if (bpmOAImprestDO != null) {

                //将相应备用金申请状态改为 未报销
                bpmOAImprestMapper.updateById(new BpmOAImprestDO().setId(bpmOAImprestDO.getId()).setStatus(BpmOAImprestDO.FLAG_FALSE));
            }
        }

        reimbursementMapper.updateById(new BpmOAReimbursementDO().setId(id).setResult(result));
    }

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

    @Override
    public BpmOAReimbursementDO getReimbursement(Long id) {
        return reimbursementMapper.selectById(id);
    }
}
