package com.ycwl.basic.image.pipeline.stages;

import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.mapper.PrinterMapper;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import lombok.extern.slf4j.Slf4j;

/**
 * 更新MemberPrint记录Stage
 * 用于更新member_print表中的cropUrl字段
 */
@Slf4j
@StageConfig(
    stageId = "update_member_print",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "更新MemberPrint记录",
    defaultEnabled = true
)
public class UpdateMemberPrintStage extends AbstractPipelineStage<PhotoProcessContext> {

    private final PrinterMapper printerMapper;
    private final Integer memberPrintId;
    private final Long memberId;
    private final Long scenicId;

    /**
     * 构造函数
     * @param printerMapper PrinterMapper实例
     * @param memberPrintId MemberPrint记录ID
     * @param memberId 用户ID
     * @param scenicId 景区ID
     */
    public UpdateMemberPrintStage(PrinterMapper printerMapper, Integer memberPrintId, Long memberId, Long scenicId) {
        this.printerMapper = printerMapper;
        this.memberPrintId = memberPrintId;
        this.memberId = memberId;
        this.scenicId = scenicId;
    }

    @Override
    public String getName() {
        return "UpdateMemberPrintStage";
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        String resultUrl = context.getResultUrl();

        if (resultUrl == null || resultUrl.trim().isEmpty()) {
            return StageResult.skipped("结果URL为空,跳过更新");
        }

        if (memberPrintId == null || memberId == null || scenicId == null) {
            log.warn("MemberPrint更新参数不完整: memberPrintId={}, memberId={}, scenicId={}",
                     memberPrintId, memberId, scenicId);
            return StageResult.skipped("更新参数不完整");
        }

        try {
            log.debug("开始更新MemberPrint记录: id={}, newCropUrl={}", memberPrintId, resultUrl);

            // 更新cropUrl字段
            int rows = printerMapper.setPhotoCropped(memberId, scenicId, memberPrintId.longValue(), resultUrl, null);

            if (rows > 0) {
                log.info("MemberPrint记录更新成功: id={}, cropUrl已更新", memberPrintId);
                return StageResult.success("更新成功");
            } else {
                log.warn("MemberPrint记录更新失败: 可能记录不存在, id={}", memberPrintId);
                return StageResult.degraded("更新失败,记录可能不存在");
            }

        } catch (Exception e) {
            log.error("更新MemberPrint记录异常: id={}", memberPrintId, e);
            // 更新失败不影响整个流程,使用降级状态
            return StageResult.degraded("更新异常: " + e.getMessage());
        }
    }
}
