package com.fs.audit.chain.handler;

import com.fs.audit.chain.AbstractAuditHandler;
import com.fs.audit.chain.AuditContext;
import com.fs.audit.chain.AuditResult;
import com.fs.audit.domain.AuditFlow;
import com.fs.audit.enums.AuditStatus;
import com.fs.audit.mapper.AuditFlowMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 审核执行处理器
 * 执行审核动作，更新当前步骤状态
 */
@Slf4j
@Component
@Order(3)
@RequiredArgsConstructor
public class AuditExecuteHandler extends AbstractAuditHandler {

    private final AuditFlowMapper auditFlowMapper;

    @Override
    protected AuditResult doHandle(AuditContext context) {
        log.info("执行审核处理器");

        AuditFlow currentFlow = context.getCurrentFlow();

        // 更新当前步骤记录
        currentFlow.setAuditUserId(context.getUserId());
        currentFlow.setComment(context.getComment());
        currentFlow.setAuditTime(LocalDateTime.now());
        currentFlow.setCompanyId(context.getCompanyId());
        currentFlow.setAuditUserType(context.getUserType());
        currentFlow.setCreateTime(LocalDateTime.now());
        currentFlow.setUpdateTime(LocalDateTime.now());
        if (context.isApproved()) {
            currentFlow.setStatus(AuditStatus.APPROVED.getCode());
            log.info("步骤{}审核通过", currentFlow.getStepNumber());
        } else {
            currentFlow.setStatus(AuditStatus.REJECTED.getCode());
            log.info("步骤{}审核驳回", currentFlow.getStepNumber());
        }

        auditFlowMapper.updateById(currentFlow);

        return AuditResult.success("审核执行成功");
    }

    @Override
    public int getOrder() {
        return 3;
    }
}

