package com.srs.diagnostic.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.srs.common.utils.DateUtils;
import com.srs.diagnostic.domain.DiaReportItems;
import com.srs.diagnostic.domain.DiaReportRelease;
import com.srs.diagnostic.domain.DiaReports;
import com.srs.diagnostic.mapper.DiaReportItemsMapper;
import com.srs.diagnostic.mapper.DiaReportsMapper;
import com.srs.diagnostic.service.IDiaReportItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 诊断报告指标项Service业务层处理
 *
 * @author srs
 * @date 2025-06-20
 */
@Service
public class DiaReportItemsServiceImpl extends ServiceImpl<DiaReportItemsMapper,DiaReportItems> implements IDiaReportItemsService {
    private static final Logger log = LoggerFactory.getLogger(DiaReportItemsServiceImpl.class);
    @Autowired
    private DiaReportsMapper diaReportsMapper;
    @Autowired
    private DiaReportItemsMapper diaReportItemsMapper;

    /**
     * 查询诊断报告指标项
     *
     * @param itemId 诊断报告指标项主键
     * @return 诊断报告指标项
     */
    @Override
    public DiaReportItems selectDiaReportItemsByItemId(Long itemId) {
        return diaReportItemsMapper.selectDiaReportItemsByItemId(itemId);
    }

    /**
     * 查询诊断报告指标项列表
     *
     * @param diaReportItems 诊断报告指标项
     * @return 诊断报告指标项
     */
    @Override
    public List<DiaReportItems> selectDiaReportItemsList(DiaReportItems diaReportItems) {
        return diaReportItemsMapper.selectDiaReportItemsList(diaReportItems);
    }

    /**
     * 新增诊断报告指标项
     *
     * @param diaReportItems 诊断报告指标项
     * @return 结果
     */
    @Override
    public int insertDiaReportItems(DiaReportItems diaReportItems) {
                diaReportItems.setCreateTime(DateUtils.getNowDate());
            return diaReportItemsMapper.insertDiaReportItems(diaReportItems);
    }

    /**
     * 修改诊断报告指标项
     *
     * @param diaReportItems 诊断报告指标项
     * @return 结果
     */
    @Override
    public int updateDiaReportItems(DiaReportItems diaReportItems) {
                diaReportItems.setUpdateTime(DateUtils.getNowDate());
        return diaReportItemsMapper.updateDiaReportItems(diaReportItems);
    }

    /**
     * 批量删除诊断报告指标项
     *
     * @param itemIds 需要删除的诊断报告指标项主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportItemsByItemIds(Long[] itemIds) {
        return diaReportItemsMapper.deleteDiaReportItemsByItemIds(itemIds);
    }

    /**
     * 删除诊断报告指标项信息
     *
     * @param itemId 诊断报告指标项主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportItemsByItemId(Long itemId) {
        return diaReportItemsMapper.deleteDiaReportItemsByItemId(itemId);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void convertReportsToItems(int curReportId) {
        log.info("开始执行报告数据转换...");

        // 1. 清空目标表
        diaReportItemsMapper.truncateTable();

        // 2. 获取所有报告数据并按父ID分组
        List<DiaReports> allReports = diaReportsMapper.selectAllReports(curReportId);
        Map<Integer, List<DiaReports>> reportsByParentId = allReports.stream()
                .collect(Collectors.groupingBy(DiaReports::getParentId));

        // 3. 处理根节点(父ID=0)
        List<DiaReports> rootReports = reportsByParentId.getOrDefault(0, Collections.emptyList());
        List<DiaReportItems> items = new ArrayList<>();

        for (DiaReports root : rootReports) {
            processReportNode(root, null, null, items, reportsByParentId,curReportId);
        }

        // 4. 批量插入
        if (!items.isEmpty()) {
            diaReportItemsMapper.batchInsertReportItems(items);
            log.info("成功转换 {} 条报告数据到指标项表", items.size());
        } else {
            log.warn("未找到可转换的报告数据");
        }
    }

    /**
     * 递归处理报告节点
     */
    private void processReportNode(DiaReports report,
                                   String currentDimension,
                                   String currentControlPoint,
                                   List<DiaReportItems> items,
                                   Map<Integer, List<DiaReports>> reportsByParentId,
                                   int curReportId) {
        // 确定节点类型
        boolean isRoot = report.getParentId() ==curReportId;
        boolean isLeaf = !reportsByParentId.containsKey(report.getReportId());

        // 设置维度、质控点和指标名称
        String dimension = isRoot ? report.getName() : currentDimension;
        String controlPoint = (!isRoot && !isLeaf) ? report.getName() : currentControlPoint;

        // 如果是叶子节点，创建指标项
        if (isLeaf) {
            DiaReportItems item = new DiaReportItems();
            item.setReportId(report.getIsMoudId());
            item.setDimension(dimension);
            item.setControlPoint(controlPoint);
            item.setIndicatorName(report.getName());
            item.setCreateBy(report.getCreateBy());
            item.setCreateTime(report.getCreateTime());
            item.setUpdateBy(report.getUpdateBy());
            item.setUpdateTime(report.getUpdateTime());
            items.add(item);
        }

        // 处理子节点
        List<DiaReports> children = reportsByParentId.get(report.getReportId());
        if (children != null) {
            for (DiaReports child : children) {
                processReportNode(child, dimension, controlPoint, items, reportsByParentId,curReportId);
            }
        }
    }
}
