package cn.iocoder.yudao.module.bpm.service.business.listener;

import cn.iocoder.yudao.module.bpm.dal.dataobject.business.BpmBusinessFormDO;
import cn.iocoder.yudao.module.bpm.enums.BpmBusinessTypeEnum;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.event.BpmProcessInstanceStatusEvent;
import cn.iocoder.yudao.module.bpm.event.BpmProcessInstanceStatusEventListener;
import cn.iocoder.yudao.module.bpm.service.business.BpmBusinessFormService;
import cn.iocoder.yudao.module.system.api.bpm.BpmAskLeaveApi;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class BpmOutboundRegistrationStatusListener extends BpmProcessInstanceStatusEventListener {

    @Resource
    private BpmBusinessFormService businessFormService;

    @Resource
    private BpmAskLeaveApi askLeaveApi;

    @Override
    protected String getProcessDefinitionKey() {
        return BpmBusinessTypeEnum.OUTBOUND_REGISTRATION.getKey();
    }

    @Override
    protected void onEvent(BpmProcessInstanceStatusEvent event) {
        BpmBusinessFormDO businessFormDO = businessFormService.getBusinessFormByInstanceId(event.getId());
        businessFormDO.setStatus(event.getStatus());
        businessFormService.updateBusinessForm(businessFormDO);

        if (BpmProcessInstanceStatusEnum.APPROVE.getStatus().equals(event.getStatus())) {
            askLeaveApi.updateLeaveStatus(businessFormDO.getBusinessId(), 1);
        } else if (BpmProcessInstanceStatusEnum.REJECT.getStatus().equals(event.getStatus())) {
            askLeaveApi.updateLeaveStatus(businessFormDO.getBusinessId(), 2);
        } else if (BpmProcessInstanceStatusEnum.CANCEL.getStatus().equals(event.getStatus())) {
            askLeaveApi.updateLeaveStatus(businessFormDO.getBusinessId(), 3);
        }

        if (BpmProcessInstanceStatusEnum.isProcessEndStatus(event.getStatus())) {
            BpmBusinessFormDO updateDO = new BpmBusinessFormDO();
            updateDO.setId(businessFormDO.getId());
            updateDO.setCompleteStatus(1);
            businessFormService.updateBusinessForm(updateDO);
        }
    }
}
