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.businessHospitality.BpmOABusinessHospitalityCreateReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOABusinessHospitalityDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOABusinessHospitalityMapper;
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.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_BUSINESS_HOSPITALITY_NOT_EXISTS;

/**
 * OA 商务招待 Service 实现类
 *
 * @author 符溶馨
 */
@Service
@Validated
public class BpmOABusinessHospitalityServiceImpl extends BpmOABaseService implements BpmOABusinessHospitalityService{

    /**
     * OA 商务招待对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_business_hospitality_2";

    @Resource
    private BpmOABusinessHospitalityMapper bpmOABusinessHospitalityMapper;

    @Resource
    private BpmProcessInstanceService processInstanceService;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Override
    public Long createBusinessHospitality(Long userId, BpmOABusinessHospitalityCreateReqVO createReqVO) {

        //插入OA 商务招待申请
        BpmOABusinessHospitalityDO bpmOABusinessHospitalityDO = BeanUtils.toBean(createReqVO, BpmOABusinessHospitalityDO.class)
                .setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        bpmOABusinessHospitalityMapper.insert(bpmOABusinessHospitalityDO);

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

        // 将工作流的编号，更新到 OA 商务招待单中
        bpmOABusinessHospitalityMapper.updateById(new BpmOABusinessHospitalityDO()
                .setId(bpmOABusinessHospitalityDO.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 bpmOABusinessHospitalityDO.getId();
    }

    @Override
    public BpmOABusinessHospitalityDO getBusinessHospitality(Long id) {
        return bpmOABusinessHospitalityMapper.selectById(id);
    }

    @Override
    public BpmOABusinessHospitalityDO getByProcessInstanceId(String processInstanceId) {
        return bpmOABusinessHospitalityMapper.selectOne(BpmOABusinessHospitalityDO::getProcessInstanceId, processInstanceId);
    }

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

        validateLeaveExists(id);
        bpmOABusinessHospitalityMapper.updateById(new BpmOABusinessHospitalityDO().setId(id).setResult(result));
    }

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