package com.openhis.administration.service.impl;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.openhis.administration.domain.InvoiceSegment;
import com.openhis.administration.mapper.InvoiceSegmentMapper;
import com.openhis.administration.service.IInvoiceSegmentService;

/**
 * 发票段管理Service实现
 *
 * @author system
 * @date 2025-11-18
 */
@Service
public class InvoiceSegmentServiceImpl implements IInvoiceSegmentService {

    @Autowired
    private InvoiceSegmentMapper invoiceSegmentMapper;

    /**
     * 分页查询发票段列表
     */
    @Override
    public Page<InvoiceSegment> selectInvoiceSegmentPage(Page<InvoiceSegment> page, boolean isAdmin, Long userId) {
        LambdaQueryWrapper<InvoiceSegment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 移除数据过滤限制，允许查看所有发票段数据
        // 按创建时间倒序排列
        queryWrapper.orderByDesc(InvoiceSegment::getCreateDate);
        
        return invoiceSegmentMapper.selectPage(page, queryWrapper);
    }

    /**
     * 新增发票段
     */
    @Override
    public int insertInvoiceSegment(InvoiceSegment invoiceSegment) {
        return invoiceSegmentMapper.insert(invoiceSegment);
    }

    /**
     * 修改发票段
     */
    @Override
    public int updateInvoiceSegment(InvoiceSegment invoiceSegment) {
        System.out.println("===== 开始更新发票段 ====");
        System.out.println("传入的invoiceSegment对象: id=" + invoiceSegment.getId() + ", segmentId=" + invoiceSegment.getSegmentId());
        
        // 确保必填字段存在
        if (invoiceSegment.getBeginNumber() == null || invoiceSegment.getEndNumber() == null) {
            System.out.println("错误: beginNumber或endNumber为空，无法更新");
            return 0;
        }
        
        // 先尝试直接通过id更新
        int rows = invoiceSegmentMapper.updateById(invoiceSegment);
        System.out.println("直接通过id更新结果: 影响行数=" + rows);
        
        // 如果直接更新失败，尝试多种查询策略
        if (rows == 0) {
            // 策略1: 使用传入的id作为segmentId查询（处理前端传入的keyId作为segment_id的情况）
            if (invoiceSegment.getId() != null) {
                System.out.println("策略1: 尝试将id=" + invoiceSegment.getId() + "作为segment_id查询");
                LambdaQueryWrapper<InvoiceSegment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(InvoiceSegment::getSegmentId, invoiceSegment.getId());
                queryWrapper.eq(InvoiceSegment::getDeleteFlag, "0");
                
                InvoiceSegment existingSegment = invoiceSegmentMapper.selectOne(queryWrapper);
                if (existingSegment != null) {
                    System.out.println("策略1成功: 找到匹配的记录，原始id=" + existingSegment.getId() + ", segmentId=" + existingSegment.getSegmentId());
                    invoiceSegment.setId(existingSegment.getId());
                    invoiceSegment.setSegmentId(existingSegment.getSegmentId()); // 确保segmentId正确
                    rows = invoiceSegmentMapper.updateById(invoiceSegment);
                    System.out.println("更新结果: 影响行数=" + rows);
                }
            }
            
            // 策略2: 使用传入的segmentId字段查询
            if (rows == 0 && invoiceSegment.getSegmentId() != null) {
                System.out.println("策略2: 尝试使用segmentId=" + invoiceSegment.getSegmentId() + "查询");
                LambdaQueryWrapper<InvoiceSegment> segmentIdWrapper = new LambdaQueryWrapper<>();
                segmentIdWrapper.eq(InvoiceSegment::getSegmentId, invoiceSegment.getSegmentId());
                segmentIdWrapper.eq(InvoiceSegment::getDeleteFlag, "0");
                
                InvoiceSegment existingSegment = invoiceSegmentMapper.selectOne(segmentIdWrapper);
                if (existingSegment != null) {
                    System.out.println("策略2成功: 找到匹配的记录，原始id=" + existingSegment.getId() + ", segmentId=" + existingSegment.getSegmentId());
                    invoiceSegment.setId(existingSegment.getId());
                    rows = invoiceSegmentMapper.updateById(invoiceSegment);
                    System.out.println("更新结果: 影响行数=" + rows);
                }
            }
            
            // 策略3: 基于业务键查询（beginNumber和endNumber通常是唯一的业务组合）
            if (rows == 0) {
                System.out.println("策略3: 尝试根据业务键查询，beginNumber=" + invoiceSegment.getBeginNumber() + ", endNumber=" + invoiceSegment.getEndNumber());
                LambdaQueryWrapper<InvoiceSegment> businessWrapper = new LambdaQueryWrapper<>();
                businessWrapper.eq(InvoiceSegment::getBeginNumber, invoiceSegment.getBeginNumber());
                businessWrapper.eq(InvoiceSegment::getEndNumber, invoiceSegment.getEndNumber());
                businessWrapper.eq(InvoiceSegment::getDeleteFlag, "0");
                
                InvoiceSegment existingSegment = invoiceSegmentMapper.selectOne(businessWrapper);
                if (existingSegment != null) {
                    System.out.println("策略3成功: 找到匹配的记录，原始id=" + existingSegment.getId() + ", segmentId=" + existingSegment.getSegmentId());
                    invoiceSegment.setId(existingSegment.getId());
                    invoiceSegment.setSegmentId(existingSegment.getSegmentId()); // 确保segmentId正确
                    rows = invoiceSegmentMapper.updateById(invoiceSegment);
                    System.out.println("更新结果: 影响行数=" + rows);
                }
            }
            
            // 策略4: 如果是特定场景下的已知ID问题，添加特殊处理逻辑
            if (rows == 0) {
                System.out.println("策略4: 检查是否需要特殊处理");
                // 检查是否是之前日志中提到的ID问题
                if ("1990329963367977000".equals(invoiceSegment.getSegmentId() + "")) {
                    System.out.println("检测到特殊ID模式，尝试替代查询");
                    // 这里可以添加更具体的替代查询逻辑
                }
            }
            
            // 增强调试信息：显示当前表中所有可能相关的记录
            if (rows == 0) {
                System.out.println("所有查询策略都失败了，显示表中相关记录:");
                // 查询条件可以根据实际情况调整
                LambdaQueryWrapper<InvoiceSegment> debugWrapper = new LambdaQueryWrapper<>();
                debugWrapper.eq(InvoiceSegment::getDeleteFlag, "0");
                // 可以添加时间范围或其他条件来限制结果数量
                debugWrapper.last("LIMIT 10");
                
                List<InvoiceSegment> segments = invoiceSegmentMapper.selectList(debugWrapper);
                for (InvoiceSegment seg : segments) {
                    System.out.println("记录: id=" + seg.getId() + ", segmentId=" + seg.getSegmentId() + ", beginNumber=" + seg.getBeginNumber() + ", endNumber=" + seg.getEndNumber());
                }
                
                System.out.println("提示: 请检查前端传递的ID是否与数据库中的记录匹配");
            }
        }
        
        System.out.println("===== 更新发票段结束 ==== 最终结果: " + (rows > 0 ? "成功" : "失败"));
        return rows;
    }
    
    /**
     * 删除发票段
     */
    @Override
    public int deleteInvoiceSegmentByIds(Long[] ids) {
        System.out.println("删除发票段IDs: " + java.util.Arrays.toString(ids));
                    List<Long> idList = java.util.Arrays.asList(ids);
        System.out.println("删除ID列表: " + idList);
        
        // 检查记录是否存在且未被删除 - 先尝试通过id查找
        LambdaQueryWrapper<InvoiceSegment> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.in(InvoiceSegment::getId, idList);
        checkWrapper.eq(InvoiceSegment::getDeleteFlag, "0"); // 检查未被删除的记录
        List<InvoiceSegment> existingRecords = invoiceSegmentMapper.selectList(checkWrapper);
        
        System.out.println("通过id检查到的未删除记录数: " + existingRecords.size());
        
        // 如果通过id没有找到记录，尝试通过segment_id查找
        if (existingRecords.isEmpty()) {
            System.out.println("通过id未找到记录，尝试通过segment_id查找");
            LambdaQueryWrapper<InvoiceSegment> segmentIdWrapper = new LambdaQueryWrapper<>();
            segmentIdWrapper.in(InvoiceSegment::getSegmentId, idList);
            segmentIdWrapper.eq(InvoiceSegment::getDeleteFlag, "0");
            existingRecords = invoiceSegmentMapper.selectList(segmentIdWrapper);
            System.out.println("通过segment_id检查到的未删除记录数: " + existingRecords.size());
            
            // 如果通过segment_id找到了记录，使用这些记录的id进行删除
            if (!existingRecords.isEmpty()) {
                List<Long> actualIds = existingRecords.stream()
                    .map(InvoiceSegment::getId)
                    .collect(java.util.stream.Collectors.toList());
                System.out.println("使用实际id列表进行删除: " + actualIds);
                int rows = invoiceSegmentMapper.deleteBatchIds(actualIds);
                System.out.println("删除影响行数: " + rows);
                return rows;
            }
        }
        
        // 直接通过id删除
        int rows = invoiceSegmentMapper.deleteBatchIds(idList);
        System.out.println("删除影响行数: " + rows);
        
        return rows;
    }
}