package com.njcn.gather.aireport.reportapproval.handler;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.aireport.reportapproval.component.ReportApprovalUserNameResolver;
import com.njcn.gather.aireport.reportapproval.mapper.ReportApprovalMapper;
import com.njcn.gather.aireport.reportapproval.pojo.constant.ReportApprovalConst;
import com.njcn.gather.aireport.reportmodel.pojo.constant.ReportModelConst;
import com.njcn.gather.aireport.reportmodel.pojo.po.ReportModelPO;
import com.njcn.gather.aireport.reportmodel.service.ReportModelService;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class ReportModelApprovalHandler extends AbstractReportApprovalHandler {

    private final ReportModelService reportModelService;

    public ReportModelApprovalHandler(ReportApprovalMapper reportApprovalMapper,
                                      ReportApprovalUserNameResolver reportApprovalUserNameResolver,
                                      ReportModelService reportModelService) {
        super(reportApprovalMapper, reportApprovalUserNameResolver);
        this.reportModelService = reportModelService;
    }

    @Override
    public String getReportType() {
        return ReportApprovalConst.REPORT_TYPE_REPORT_MODEL;
    }

    @Override
    protected boolean doAudit(String reportId, String reason, boolean passed) {
        ReportModelPO reportModel = reportModelService.requireNormal(reportId);
        if (!ReportModelConst.STATE_AUDITING.equals(reportModel.getState())) {
            throw new BusinessException(CommonResponseEnum.FAIL, "仅待审状态的报告模板允许审批");
        }
        String userId = resolveCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        String targetState = passed ? ReportModelConst.STATE_APPROVED : ReportModelConst.STATE_REJECTED;
        boolean updated = reportModelService.lambdaUpdate()
                .set(ReportModelPO::getState, targetState)
                .set(ReportModelPO::getCheckId, userId)
                .set(ReportModelPO::getCheckTime, now)
                .set(ReportModelPO::getCheckResult, reason)
                .set(ReportModelPO::getUpdateBy, userId)
                .set(ReportModelPO::getUpdateTime, now)
                .eq(ReportModelPO::getId, reportId)
                .eq(ReportModelPO::getStatus, ReportModelConst.STATUS_NORMAL)
                .eq(ReportModelPO::getState, ReportModelConst.STATE_AUDITING)
                .update();
        if (!updated) {
            throw new BusinessException(CommonResponseEnum.FAIL, "报告模板状态已变更，请刷新后重试");
        }
        saveLog(reportModel.getId(), reportModel.getName(), ReportModelConst.STATE_AUDITING, targetState, reason, userId, now);
        return true;
    }
}
