package com.ruoyi.web.report.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.web.report.domain.ErpReportDefinition;
import com.ruoyi.web.report.mapper.ErpReportDefinitionMapper;
import com.ruoyi.web.report.service.IReportDynamicMenuService;
import com.ruoyi.web.report.service.IErpReportDefinitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Locale;

/**
 * 报表定义服务实现。
 *
 * <p>当前实现聚焦基础管理能力：
 * 查询、唯一性校验、新增默认值填充、发布动作封装。</p>
 */
@Service
public class ErpReportDefinitionServiceImpl implements IErpReportDefinitionService {

    @Autowired
    private ErpReportDefinitionMapper erpReportDefinitionMapper;

    @Autowired
    private IReportDynamicMenuService reportDynamicMenuService;

    @Override
    public ErpReportDefinition selectById(Long id) {
        // 直接按主键查询详情，供编辑页回显和运行态读取元信息。
        return erpReportDefinitionMapper.selectErpReportDefinitionById(id);
    }

    @Override
    public List<ErpReportDefinition> selectList(ErpReportDefinition query) {
        // 列表查询通过 Mapper 动态 SQL 处理可选过滤条件。
        return erpReportDefinitionMapper.selectErpReportDefinitionList(query);
    }

    @Override
    public boolean checkReportCodeUnique(ErpReportDefinition entity) {
        // 新增场景给一个不存在的占位ID，避免空值比较导致逻辑偏差。
        Long id = entity.getId() == null ? -1L : entity.getId();
        ErpReportDefinition db = erpReportDefinitionMapper.selectErpReportDefinitionByCode(entity.getReportCode());
        // 若数据库已存在同编码且非当前记录，则判定为不唯一。
        if (db != null && !id.equals(db.getId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ErpReportDefinition entity) {
        // 首次创建统一从版本 1 开始。
        entity.setVersionNo(1);
        // 未传状态时默认草稿，保证发布前可继续编辑。
        if (entity.getStatus() == null || entity.getStatus().trim().isEmpty()) {
            entity.setStatus("DRAFT");
        }
        int affected = erpReportDefinitionMapper.insertErpReportDefinition(entity);
        if (affected > 0 && isPublished(entity.getStatus())) {
            reportDynamicMenuService.createOrUpdateReportMenu(entity, entity.getCreateBy());
        }
        return affected;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(ErpReportDefinition entity) {
        // 编辑动作不直接变更版本号，版本号由发布动作统一维护。
        int affected = erpReportDefinitionMapper.updateErpReportDefinition(entity);
        if (affected > 0 && isPublished(entity.getStatus())) {
            ErpReportDefinition db = erpReportDefinitionMapper.selectErpReportDefinitionById(entity.getId());
            reportDynamicMenuService.createOrUpdateReportMenu(db, entity.getUpdateBy());
        }
        return affected;
    }

    @Override
    public int removeById(Long id) {
        // 当前为物理删除，后续可按治理要求升级为逻辑删除。
        return erpReportDefinitionMapper.deleteErpReportDefinitionById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publishById(Long id, String updateBy) {
        // 发布时由 SQL 统一完成状态置为 PUBLISHED 与版本号自增。
        int affected = erpReportDefinitionMapper.publishErpReportDefinition(id, updateBy);
        if (affected > 0) {
            ErpReportDefinition definition = erpReportDefinitionMapper.selectErpReportDefinitionById(id);
            reportDynamicMenuService.createOrUpdateReportMenu(definition, updateBy);
        }
        return affected;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int rebuildMenusForPublished(String operator) {
        ErpReportDefinition query = new ErpReportDefinition();
        query.setStatus("PUBLISHED");
        List<ErpReportDefinition> list = erpReportDefinitionMapper.selectErpReportDefinitionList(query);
        int count = 0;
        for (ErpReportDefinition definition : list) {
            reportDynamicMenuService.createOrUpdateReportMenu(definition, operator);
            count++;
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int rebuildMenuByReportId(Long reportId, String operator) {
        ErpReportDefinition definition = erpReportDefinitionMapper.selectErpReportDefinitionById(reportId);
        if (definition == null) {
            return 0;
        }
        reportDynamicMenuService.createOrUpdateReportMenu(definition, operator);
        return 1;
    }

    /**
     * 判断状态是否已发布。
     */
    private boolean isPublished(String status) {
        return status != null && "PUBLISHED".equals(status.trim().toUpperCase(Locale.ROOT));
    }
}
