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

import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.ems.info.domain.SparePartsInventory;
import org.dromara.ems.info.domain.SparePartsInventoryCheck;
import org.dromara.ems.info.domain.SparePartsInventoryExportVO;
import org.dromara.ems.info.mapper.SparePartsInventoryCheckMapper;
import org.dromara.ems.info.mapper.SparePartsInventoryMapper;
import org.dromara.ems.info.service.ISparePartsInventoryService;
import org.dromara.ems.info.util.InventoryQuantityUpdater;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 备件库记录主Service业务层处理
 * 
 * @author Yinq
 * @date 2025-06-05
 */
@Service
@RequiredArgsConstructor
public class SparePartsInventoryServiceImpl implements ISparePartsInventoryService 
{
    
    private final SparePartsInventoryMapper sparePartsInventoryMapper;
    
    
    private final SparePartsInventoryCheckMapper sparePartsInventoryCheckMapper;

    
    private final InventoryQuantityUpdater inventoryQuantityUpdater;

    /**
     * 查询备件库记录主
     * 
     * @param objid 备件库记录主主键
     * @return 备件库记录主
     */
    @Override
    public SparePartsInventory selectSparePartsInventoryByObjid(Long objid)
    {
        return sparePartsInventoryMapper.selectSparePartsInventoryByObjid(objid);
    }

    /**
     * 查询备件库记录主列表
     * 
     * @param sparePartsInventory 备件库记录主
     * @return 备件库记录主
     */
    @Override
    public List<SparePartsInventory> selectSparePartsInventoryList(SparePartsInventory sparePartsInventory)
    {
        return sparePartsInventoryMapper.selectSparePartsInventoryList(sparePartsInventory);
    }

    /**
     * 查询备件库记录导出列表（包含动态列）
     * 
     * @param sparePartsInventory 备件库记录主
     * @return 备件库记录导出列表
     */
    @Override
    public List<SparePartsInventoryExportVO> selectSparePartsInventoryExportList(SparePartsInventory sparePartsInventory)
    {
        // 1. 查询主表数据
        List<SparePartsInventory> mainList = sparePartsInventoryMapper.selectSparePartsInventoryList(sparePartsInventory);
        
        // 2. 查询所有明细数据
        List<SparePartsInventoryCheck> checkList = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(new SparePartsInventoryCheck());
        
        // 3. 按主表ID分组明细数据
        Map<Long, List<SparePartsInventoryCheck>> checkMap = checkList.stream()
                .collect(Collectors.groupingBy(SparePartsInventoryCheck::getInventoryObjid));
        
        // 4. 转换为导出VO
        List<SparePartsInventoryExportVO> exportList = new ArrayList<>();
        for (SparePartsInventory main : mainList) {
            SparePartsInventoryExportVO exportVO = new SparePartsInventoryExportVO();
            BeanUtils.copyProperties(main, exportVO);
            
            // 设置动态盘点数据
            List<SparePartsInventoryCheck> checks = checkMap.get(main.getObjid());
            if (checks != null) {
                for (SparePartsInventoryCheck check : checks) {
                    exportVO.setCheckValue(check.getCheckName(), check.getCheckQuantity());
                }
            }
            
            exportList.add(exportVO);
        }
        
        return exportList;
    }

    /**
     * 查询备件库记录主详细信息（包含盘点数据）
     * 
     * @param objid 备件库记录主主键
     * @return 备件库记录主VO
     */
    @Override
    public SparePartsInventoryExportVO selectSparePartsInventoryWithChecksByObjid(Long objid)
    {
        // 查询主记录
        SparePartsInventory inventory = sparePartsInventoryMapper.selectSparePartsInventoryByObjid(objid);
        if (inventory == null) {
            return null;
        }
        
        // 创建VO并复制基础属性
        SparePartsInventoryExportVO vo = new SparePartsInventoryExportVO();
        BeanUtils.copyProperties(inventory, vo);
        
        // 查询盘点记录
        SparePartsInventoryCheck checkParam = new SparePartsInventoryCheck();
        checkParam.setInventoryObjid(objid);
        List<SparePartsInventoryCheck> checkList = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(checkParam);
        
        // 构建盘点数据Map
        Map<String, Long> checkData = new HashMap<>();
        for (SparePartsInventoryCheck check : checkList) {
            if (ObjectUtil.isNotEmpty(check.getCheckName())) {
                checkData.put(check.getCheckName(), check.getCheckQuantity());
            }
        }
        vo.setCheckData(checkData);
        
        return vo;
    }

    /**
     * 新增备件库记录主
     * 
     * @param sparePartsInventory 备件库记录主
     * @return 结果
     */
    @Override
    public int insertSparePartsInventory(SparePartsInventory sparePartsInventory)
    {
        return sparePartsInventoryMapper.insertSparePartsInventory(sparePartsInventory);
    }

    /**
     * 修改备件库记录主
     * 
     * @param sparePartsInventory 备件库记录主
     * @return 结果
     */
    @Override
    public int updateSparePartsInventory(SparePartsInventory sparePartsInventory)
    {
        return sparePartsInventoryMapper.updateSparePartsInventory(sparePartsInventory);
    }

    /**
     * 批量删除备件库记录主
     * 
     * @param objids 需要删除的备件库记录主主键
     * @return 结果
     */
    @Override
    public int deleteSparePartsInventoryByObjids(Long[] objids)
    {
        return sparePartsInventoryMapper.deleteSparePartsInventoryByObjids(objids);
    }

    /**
     * 删除备件库记录主信息
     * 
     * @param objid 备件库记录主主键
     * @return 结果
     */
    @Override
    public int deleteSparePartsInventoryByObjid(Long objid)
    {
        return sparePartsInventoryMapper.deleteSparePartsInventoryByObjid(objid);
    }

    /**
     * 导入备件库记录主数据（支持动态列）
     *
     * @param exportList 导入数据列表（包含动态列）
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSparePartsInventoryWithDynamicColumns(List<SparePartsInventoryExportVO> exportList, Boolean isUpdateSupport, String operName)
    {
        if (ObjectUtil.isNull(exportList) || exportList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (SparePartsInventoryExportVO exportVO : exportList)
        {
            try
            {
                // 1. 转换为主表实体
                SparePartsInventory main = new SparePartsInventory();
                BeanUtils.copyProperties(exportVO, main);
                
                // 2. 检查是否存在
                SparePartsInventory existRecord = null;
                if (ObjectUtil.isNotEmpty(main.getItemName()) && ObjectUtil.isNotEmpty(main.getOriginalPartNumber()))
                {
                    SparePartsInventory queryRecord = new SparePartsInventory();
                    queryRecord.setItemName(main.getItemName());
                    queryRecord.setOriginalPartNumber(main.getOriginalPartNumber());
                    List<SparePartsInventory> existRecords = sparePartsInventoryMapper.selectSparePartsInventoryList(queryRecord);
                    if (existRecords.size() > 0)
                    {
                        existRecord = existRecords.get(0);
                    }
                }
                
                Long objid;
                if (ObjectUtil.isNull(existRecord))
                {
                    // 3. 插入主表
                    sparePartsInventoryMapper.insertSparePartsInventory(main);
                    objid = main.getObjid();
                }
                else if (isUpdateSupport)
                {
                    // 4. 更新主表
                    main.setObjid(existRecord.getObjid());
                    sparePartsInventoryMapper.updateSparePartsInventory(main);
                    objid = existRecord.getObjid();
                    
                    // 删除现有的盘点记录
                    SparePartsInventoryCheck deleteQuery = new SparePartsInventoryCheck();
                    deleteQuery.setInventoryObjid(objid);
                    List<SparePartsInventoryCheck> existingChecks = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(deleteQuery);
                    for (SparePartsInventoryCheck check : existingChecks) {
                        sparePartsInventoryCheckMapper.deleteSparePartsInventoryCheckById(check.getId());
                    }
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、备件库记录 " + main.getItemName() + " 已存在");
                    continue;
                }
                
                // 5. 处理动态盘点数据
                Map<String, Long> checkData = exportVO.getCheckData();
                if (checkData != null && !checkData.isEmpty()) {
                    for (Map.Entry<String, Long> entry : checkData.entrySet()) {
                        if (entry.getValue() != null) {
                            SparePartsInventoryCheck check = new SparePartsInventoryCheck();
                            check.setInventoryObjid(objid);
                            check.setCheckName(entry.getKey());
                            check.setCheckQuantity(entry.getValue());
                            check.setCheckDate(DateUtils.dateTimeNow());
                            sparePartsInventoryCheckMapper.insertSparePartsInventoryCheck(check);
                        }
                    }
                    
                    // 盘点记录插入后，更新主表的剩余数量为最新盘点数量
                    inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(objid);
                }
                
                successNum++;
                successMsg.append("<br/>" + successNum + "、备件库记录 " + main.getItemName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、备件库记录导入失败：";
                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();
    }

    /**
     * 导入备件库记录主数据
     *
     * @param recordList 记录数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSparePartsInventory(List<SparePartsInventory> 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 (SparePartsInventory record : recordList)
        {
            try
            {
                // 设置操作人
                
                // 验证是否存在这个记录
                SparePartsInventory existRecord = null;
                if (ObjectUtil.isNotEmpty(record.getItemName()) && ObjectUtil.isNotEmpty(record.getOriginalPartNumber()))
                {
                    SparePartsInventory queryRecord = new SparePartsInventory();
                    queryRecord.setItemName(record.getItemName());
                    queryRecord.setOriginalPartNumber(record.getOriginalPartNumber());
                    List<SparePartsInventory> existRecords = sparePartsInventoryMapper.selectSparePartsInventoryList(queryRecord);
                    if (existRecords.size() > 0)
                    {
                        existRecord = existRecords.get(0);
                    }
                }
                
                if (ObjectUtil.isNull(existRecord))
                {
                    this.insertSparePartsInventory(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、备件库记录 " + record.getItemName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    record.setObjid(existRecord.getObjid());
                    this.updateSparePartsInventory(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、备件库记录 " + record.getItemName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、备件库记录 " + record.getItemName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、备件库记录 " + record.getItemName() + " 导入失败：";
                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();
    }

    /**
     * 新增备件库记录主（包含动态列）
     * 
     * @param sparePartsInventoryVO 备件库记录主VO
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSparePartsInventoryWithDynamicColumns(SparePartsInventoryExportVO sparePartsInventoryVO)
    {
        // 创建主记录
        SparePartsInventory inventory = new SparePartsInventory();
        BeanUtils.copyProperties(sparePartsInventoryVO, inventory);
        
        // 插入主记录
        int result = sparePartsInventoryMapper.insertSparePartsInventory(inventory);
        
        // 处理盘点记录
        if (result > 0 && sparePartsInventoryVO.getCheckData() != null && !sparePartsInventoryVO.getCheckData().isEmpty()) {
            Long objid = inventory.getObjid();
            for (Map.Entry<String, Long> entry : sparePartsInventoryVO.getCheckData().entrySet()) {
                if (ObjectUtil.isNotEmpty(entry.getKey()) && entry.getValue() != null) {
                    SparePartsInventoryCheck check = new SparePartsInventoryCheck();
                    check.setInventoryObjid(objid);
                    check.setCheckName(entry.getKey());
                    check.setCheckQuantity(entry.getValue());
                    check.setCheckDate(DateUtils.dateTimeNow());
                    sparePartsInventoryCheckMapper.insertSparePartsInventoryCheck(check);
                }
            }
            
            // 在盘点记录插入后，更新主表的剩余数量为最新盘点数量
            inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(objid);
        }
        
        return result;
    }

    /**
     * 修改备件库记录主（包含动态列）
     * 
     * @param sparePartsInventoryVO 备件库记录主VO
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSparePartsInventoryWithDynamicColumns(SparePartsInventoryExportVO sparePartsInventoryVO)
    {
        // 更新主记录
        SparePartsInventory inventory = new SparePartsInventory();
        BeanUtils.copyProperties(sparePartsInventoryVO, inventory);
        int result = sparePartsInventoryMapper.updateSparePartsInventory(inventory);
        
        // 处理盘点记录
        if (result > 0 && sparePartsInventoryVO.getObjid() != null) {
            Long objid = sparePartsInventoryVO.getObjid();
            
            // 删除原有的盘点记录
            SparePartsInventoryCheck deleteParam = new SparePartsInventoryCheck();
            deleteParam.setInventoryObjid(objid);
            List<SparePartsInventoryCheck> existingChecks = sparePartsInventoryCheckMapper.selectSparePartsInventoryCheckList(deleteParam);
            for (SparePartsInventoryCheck existingCheck : existingChecks) {
                sparePartsInventoryCheckMapper.deleteSparePartsInventoryCheckById(existingCheck.getId());
            }
            
            // 插入新的盘点记录
            if (sparePartsInventoryVO.getCheckData() != null && !sparePartsInventoryVO.getCheckData().isEmpty()) {
                for (Map.Entry<String, Long> entry : sparePartsInventoryVO.getCheckData().entrySet()) {
                    if (ObjectUtil.isNotEmpty(entry.getKey()) && entry.getValue() != null) {
                        SparePartsInventoryCheck check = new SparePartsInventoryCheck();
                        check.setInventoryObjid(objid);
                        check.setCheckName(entry.getKey());
                        check.setCheckQuantity(entry.getValue());
                        check.setCheckDate(DateUtils.dateTimeNow());
                        sparePartsInventoryCheckMapper.insertSparePartsInventoryCheck(check);
                    }
                }
            }
            
            // 在盘点记录更新后，同步更新主表的剩余数量为最新盘点数量
            inventoryQuantityUpdater.updateRemainingQuantityByLatestCheck(objid);
        }
        
        return result;
    }

    /**
     * 获取所有盘点名称
     * 
     * @return 盘点名称列表
     */
    @Override
    public List<String> getAllCheckNames()
    {
        return sparePartsInventoryCheckMapper.selectDistinctCheckNames();
    }
}
