package org.dromara.ems.info.service.impl;

import org.dromara.common.core.exception.ServiceException;
import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.ems.info.domain.SparePartsInventoryCheck;
import org.dromara.ems.info.mapper.SparePartsInventoryCheckMapper;
import org.dromara.ems.info.service.ISparePartsInventoryCheckService;
import org.dromara.ems.info.util.InventoryQuantityUpdater;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 备件盘点记录明细Service业务层处理
 * 
 * @author Yinq
 * @date 2025-06-05
 */
@Service
@RequiredArgsConstructor
public class SparePartsInventoryCheckServiceImpl implements ISparePartsInventoryCheckService 
{
    
    private final SparePartsInventoryCheckMapper sparePartsInventoryCheckMapper;

    
    private final InventoryQuantityUpdater inventoryQuantityUpdater;

    /**
     * 查询备件盘点记录明细
     * 
     * @param id 备件盘点记录明细主键
     * @return 备件盘点记录明细
     */
    @Override
    public SparePartsInventoryCheck selectSparePartsInventoryCheckById(Long id)
    {
        return sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckById(id);
    }

    /**
     * 查询备件盘点记录明细列表
     * 
     * @param sparePartsInventoryCheck 备件盘点记录明细
     * @return 备件盘点记录明细
     */
    @Override
    public List<SparePartsInventoryCheck> selectSparePartsInventoryCheckList(SparePartsInventoryCheck sparePartsInventoryCheck)
    {
        return sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(sparePartsInventoryCheck);
    }

    /**
     * 新增备件盘点记录明细
     * 
     * @param sparePartsInventoryCheck 备件盘点记录明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSparePartsInventoryCheck(SparePartsInventoryCheck sparePartsInventoryCheck)
    {
        // 验证必要参数
        if (sparePartsInventoryCheck.getInventoryObjid() == null) {
            throw new ServiceException("库存记录ID不能为空");
        }
        
        int result = sparePartsInventoryCheckMapper.insertSparePartsInventoryCheck(sparePartsInventoryCheck);
        
        // 如果插入成功，更新主表的剩余数量
        if (result > 0) {
            inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(sparePartsInventoryCheck.getInventoryObjid());
        }
        
        return result;
    }

    /**
     * 修改备件盘点记录明细
     * 
     * @param sparePartsInventoryCheck 备件盘点记录明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSparePartsInventoryCheck(SparePartsInventoryCheck sparePartsInventoryCheck)
    {
        int result = sparePartsInventoryCheckMapper.updateSparePartsInventoryCheck(sparePartsInventoryCheck);
        
        // 如果更新成功，同步更新主表的剩余数量
        if (result > 0 && sparePartsInventoryCheck.getInventoryObjid() != null) {
            inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(sparePartsInventoryCheck.getInventoryObjid());
        }
        
        return result;
    }

    /**
     * 批量删除备件盘点记录明细
     * 
     * @param ids 需要删除的备件盘点记录明细主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSparePartsInventoryCheckByIds(Long[] ids)
    {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        
        // 先查询要删除的记录，收集相关的库存ID
        Set<Long> inventoryObjids = new HashSet<>();
        for (Long id : ids) {
            SparePartsInventoryCheck check = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckById(id);
            if (check != null && check.getInventoryObjid() != null) {
                inventoryObjids.add(check.getInventoryObjid());
            }
        }
        
        int result = sparePartsInventoryCheckMapper.deleteSparePartsInventoryCheckByIds(ids);
        
        // 如果删除成功，批量更新相关库存记录的剩余数量
        if (result > 0 && !inventoryObjids.isEmpty()) {
            Long[] objidArray = inventoryObjids.toArray(new Long[0]);
            inventoryQuantityUpdater.batchUpdateRemainingQuantity(objidArray);
        }
        
        return result;
    }

    /**
     * 删除备件盘点记录明细信息
     * 
     * @param id 备件盘点记录明细主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)   
    public int deleteSparePartsInventoryCheckById(Long id)
    {
        // 先查询要删除的记录，获取库存ID
        SparePartsInventoryCheck checkToDelete = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckById(id);
        
        int result = sparePartsInventoryCheckMapper.deleteSparePartsInventoryCheckById(id);
        
        // 如果删除成功，同步更新主表的剩余数量
        if (result > 0 && checkToDelete != null && checkToDelete.getInventoryObjid() != null) {
            inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(checkToDelete.getInventoryObjid());
        }
        
        return result;
    }

    /**
     * 导入备件盘点记录明细数据
     *
     * @param recordList 记录数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSparePartsInventoryCheck(List<SparePartsInventoryCheck> recordList, Boolean isUpdateSupport, String operName)
    {
        if (ObjectUtil.isNull(recordList) || recordList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SparePartsInventoryCheck record : recordList)
        {
            try
            {
                // 设置操作人
                
                // 验证是否存在这个记录
                SparePartsInventoryCheck existRecord = null;
                if (ObjectUtil.isNotEmpty(record.getCheckDate()) && ObjectUtil.isNotEmpty(record.getCheckName()))
                {
                    SparePartsInventoryCheck queryRecord = new SparePartsInventoryCheck();
                    queryRecord.setCheckDate(record.getCheckDate());
                    queryRecord.setCheckName(record.getCheckName());
                    List<SparePartsInventoryCheck> existRecords = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(queryRecord);
                    if (existRecords.size() > 0)
                    {
                        existRecord = existRecords.get(0);
                    }
                }
                
                if (ObjectUtil.isNull(existRecord))
                {
                    this.insertSparePartsInventoryCheck(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、备件盘点记录 " + record.getCheckName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    record.setId(existRecord.getId());
                    this.updateSparePartsInventoryCheck(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、备件盘点记录 " + record.getCheckName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、备件盘点记录 " + record.getCheckName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、备件盘点记录 " + record.getCheckName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
