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.testreport.pojo.constant.TestReportConst;
import com.njcn.gather.aireport.testreport.pojo.po.TestReportPO;
import com.njcn.gather.aireport.testreport.service.TestReportService;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
public class TestReportApprovalHandler extends AbstractReportApprovalHandler {

    private final TestReportService testReportService;

    public TestReportApprovalHandler(ReportApprovalMapper reportApprovalMapper,
                                     ReportApprovalUserNameResolver reportApprovalUserNameResolver,
                                     TestReportService testReportService) {
        super(reportApprovalMapper, reportApprovalUserNameResolver);
        this.testReportService = testReportService;
    }

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

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