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.imprest.BpmOAImprestCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.upload.UploadUserFile;
import cn.iocoder.yudao.module.bpm.convert.oa.BpmOAImprestConvert;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAImprestDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAImprestMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
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_IMPREST_NOT_EXISTS;

/**
 * OA 备用金申请 Service 实现类
 *
 * @author 符溶馨

 */
@Service
@Validated
public class BpmOAImprestServiceImpl extends BpmOABaseService implements BpmOAImprestService{

    /**
     * OA 出差对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_imprest";

    @Resource
    private BpmOAImprestMapper imprestMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Override
    public Long createImprest(Long userId, BpmOAImprestCreateReqVO createReqVO) {

        //插入OA 备用金申请
        BpmOAImprestDO imprest = BpmOAImprestConvert.INSTANCE.convert(createReqVO).setUserId(userId)
                .setStatus(BpmOAImprestDO.FLAG_FALSE)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        imprestMapper.insert(imprest) ;

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

        // 将工作流的编号，更新到 OA 备用金单中
        imprestMapper.updateById(new BpmOAImprestDO().setId(imprest.getId()).setProcessInstanceId(processInstanceId));

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

    @Override
    public void updateImprestResult(Long id, Integer result) {

        validateLeaveExists(id);
        imprestMapper.updateById(new BpmOAImprestDO().setId(id).setResult(result));
    }

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

    @Override
    public BpmOAImprestDO getImprest(Long id) {

        return imprestMapper.selectById(id);
    }

    @Override
    public BpmOAImprestDO getImprestByUserId(Long userId) {

        //根据user 查询审批通过并且未报销得表单。
        return imprestMapper.selectByUserId(userId, BpmOAImprestDO.FLAG_FALSE);
    }

    @Override
    public BpmOAImprestDO getImprestByReimbursementId(Long reimbursementId) {

        //根据报销业务编号获取备用金详情
        return imprestMapper.selectOne(BpmOAImprestDO::getReimbursementId, reimbursementId);
    }
}
