package com.ruoyi.inventory.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.WarehouseConfig;
import com.ruoyi.common.core.domain.entity.Materials;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.inventory.domain.Owners;
import com.ruoyi.inventory.domain.StorageLocationsCategory;
import com.ruoyi.inventory.domain.vo.StorageLocationsLocationTemplateVO;
import com.ruoyi.inventory.mapper.MaterialsMapper;
import com.ruoyi.inventory.mapper.StorageLocationsCategoryMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.inventory.mapper.StorageLocationsMapper;
import com.ruoyi.inventory.domain.StorageLocations;
import com.ruoyi.inventory.service.IStorageLocationsService;

/**
 * 库位Service业务层处理
 *
 * @author ruoyi
 * @date 2025-12-01
 */
@Service
public class StorageLocationsServiceImpl implements IStorageLocationsService
{
    @Autowired
    private StorageLocationsMapper storageLocationsMapper;
    // 注释掉关联mapper（如果不需要可直接删除）
    // @Autowired
    // private StorageLocationsCategoryMapper storageLocationsCategoryMapper;
    // @Autowired
    // private MaterialsMapper materialsMapper;

    /**
     * 查询库位
     *
     * @param id 库位主键
     * @return 库位
     */
    @Override
    public StorageLocations selectStorageLocationsById(String id)
    {
        StorageLocations storageLocations = storageLocationsMapper.selectStorageLocationsById(id);
        // 注释掉物料反显逻辑
        /*String AllowedCategoryName = "";
        if (storageLocations.getAllowedCategoryIds() != null) {
            String[] AllowedCategoryIds = storageLocations.getAllowedCategoryIds().split(",");
            if (AllowedCategoryIds != null && AllowedCategoryIds.length > 0) {
                for (String AllowedCategoryId : AllowedCategoryIds) {
                    Materials materials = materialsMapper.selectMaterialsById(AllowedCategoryId);
                    if (materials != null && materials.getMaterialName() != null) {
                        String categoryName = materials.getMaterialName().trim(); // 去除首尾空格
                        if (AllowedCategoryName != "") {
                            AllowedCategoryName += ",";
                        }
                        AllowedCategoryName += categoryName;
                    }
                }
            }
        }
        storageLocations.setAllowedCategoryNames(AllowedCategoryName);*/
        return storageLocations;
    }

    @Override
    public List<StorageLocations> selectStorageLocationsByWarehousesCode(String warehousesCode) {
        return storageLocationsMapper.selectStorageLocationsByWarehousesCode(warehousesCode);
    }

    @Override
    public List<StorageLocations> selectStorageLocationsByWarehousesCodes(List<String> warehousesCodes) {
        return storageLocationsMapper.selectStorageLocationsByWarehousesCodes(warehousesCodes);
    }

    /**
     * 查询库位列表
     *
     * @param storageLocations 库位
     * @return 库位
     */
    @Override
    public List<StorageLocations> selectStorageLocationsList(StorageLocations storageLocations)
    {
        List<StorageLocations> storageLocations1 = storageLocationsMapper.selectStorageLocationsList(storageLocations);
        // 注释掉物料反显逻辑
        /*for (StorageLocations storageLocations2 : storageLocations1){
            String AllowedCategoryName = "";
            if (storageLocations2.getAllowedCategoryIds() != null && !storageLocations2.getAllowedCategoryIds().isEmpty()){
                String[] AllowedCategoryIds = storageLocations2.getAllowedCategoryIds().split(",");
                for (String AllowedCategoryId : AllowedCategoryIds) {
                    Materials materials = materialsMapper.selectMaterialsById(AllowedCategoryId);
                    if (materials != null && materials.getMaterialName() != null) {
                        String categoryName = materials.getMaterialName().trim(); // 去除首尾空格
                        if (AllowedCategoryName != "") {
                            AllowedCategoryName += ",";
                        }
                        AllowedCategoryName += categoryName;
                    }
                }
            }
            storageLocations2.setAllowedCategoryNames(AllowedCategoryName);
        }*/
        return storageLocations1;
    }

    /**
     * 新增库位
     *
     * @param storageLocations 库位
     * @return 结果
     */
    @Override
    public int insertStorageLocations(StorageLocations storageLocations)
    {
        storageLocations.setCreateTime(DateUtils.getNowDate());

        // 注释掉所有库位分类关联逻辑
        /*StorageLocationsCategory storageLocationsCategory = new StorageLocationsCategory();
        BeanUtils.copyBeanProp(storageLocationsCategory,storageLocations);*/
        String LocationsID = UUID.randomUUID().toString();
        storageLocations.setId(LocationsID);
        storageLocations.setCreateTime(DateUtils.getNowDate());
        storageLocations.setCreateUserCode(String.valueOf(SecurityUtils.getUserId()));
        storageLocations.setWarehousesId(WarehouseConfig.DEFAULT_WAREHOUSE_ID);
        /*storageLocationsCategory.setLocationCode(LocationsID);


        if (storageLocations.getAllowedCategoryIds() != null && !storageLocations.getAllowedCategoryIds().isEmpty()){
            String[] CategoryId = storageLocations.getAllowedCategoryIds().split(",");
            for (String categoryId : CategoryId) {
                storageLocationsCategory.setId(java.util.UUID.randomUUID().toString());
                storageLocationsCategory.setCategoryId(categoryId);
                storageLocationsCategory.setCreateTime(DateUtils.getNowDate());
                storageLocationsCategory.setCreateUserCode(String.valueOf(SecurityUtils.getUserId()));
                Materials materials = materialsMapper.selectMaterialsById(categoryId);
                storageLocationsCategory.setCategoryName(materials.getMaterialName());
                storageLocationsCategoryMapper.insertStorageLocationsCategory(storageLocationsCategory);
            }
        }*/
        return storageLocationsMapper.insertStorageLocations(storageLocations);
    }

    /**
     * 修改库位
     *
     * @param storageLocations 库位
     * @return 结果
     */
    @Override
    public int updateStorageLocations(StorageLocations storageLocations)
    {
        storageLocations.setUpdateTime(DateUtils.getNowDate());
        storageLocations.setUpdateUserCode(String.valueOf(SecurityUtils.getUserId()));

        String LocationsID = storageLocations.getId();
        String LocationsCode = storageLocations.getLocationCode();
        StorageLocations storageLocations1 = storageLocationsMapper.selectStorageLocationsById(LocationsID);
        // 注释掉库位分类关联修改逻辑
        /*if (storageLocations1.getAllowedCategoryIds()!=storageLocations.getAllowedCategoryIds()||storageLocations1.getIsEnabled()!=storageLocations.getIsEnabled()){
            storageLocationsCategoryMapper.deleteStorageLocationsCategoryByLocationCode(LocationsID);

            String[] CategoryId = storageLocations.getAllowedCategoryIds().split(",");
            StorageLocationsCategory storageLocationsCategory = new StorageLocationsCategory();
            BeanUtils.copyBeanProp(storageLocationsCategory,storageLocations);

            storageLocationsCategory.setLocationCode(LocationsCode);
            for (String categoryId : CategoryId) {
                storageLocationsCategory.setId(java.util.UUID.randomUUID().toString());
                storageLocationsCategory.setCategoryId(categoryId);
                storageLocationsCategory.setUpdateTime(DateUtils.getNowDate());
                storageLocationsCategory.setUpdateUserCode(String.valueOf(SecurityUtils.getUserId()));
                Materials materials = materialsMapper.selectMaterialsById(categoryId);
                storageLocationsCategory.setCategoryName(materials.getMaterialName());
                storageLocationsCategoryMapper.insertStorageLocationsCategory(storageLocationsCategory);
            }
        }*/

        return storageLocationsMapper.updateStorageLocations(storageLocations);
    }

    /**
     * 批量删除库位
     *
     * @param ids 需要删除的库位主键
     * @return 结果
     */
    @Override
    public int deleteStorageLocationsByIds(String[] ids)
    {
        return storageLocationsMapper.deleteStorageLocationsByIds(ids);
    }

    /**
     * 删除库位信息
     *
     * @param id 库位主键
     * @return 结果
     */
    @Override
    public int deleteStorageLocationsById(String id)
    {
        // 注释掉关联的库位分类删除逻辑
        // storageLocationsCategoryMapper.deleteStorageLocationsCategoryById(id);
        return storageLocationsMapper.deleteStorageLocationsById(id);
    }

    @Override
    public int updateLocationsCategoryStatus(String id)
    {
        return storageLocationsMapper.updateStorageLocationsStatus(id);
    }

    /**
     * @description: 获取库位表 的 location_code 编码 location_name 做成字典
     * @author cs
     * @date 2025/12/4
     * @version 1.0
     */
    @Override
    public List<Map<String, Object>> getMapList(StorageLocations storageLocations)
    {
        return storageLocationsMapper.getMapList(storageLocations);
    }

    /**
     * 查询库位列表
     *
     * @param storageLocations 库位
     * @return 库位集合
     */
    @Override
    public List<StorageLocations> getStorageLocationsList(StorageLocations storageLocations) {
        List<StorageLocations> storageLocations1 =storageLocationsMapper.getStorageLocationsList(storageLocations);
        return storageLocations1;
    }

    @Override
    public String importStorageLocationsLocation(List<StorageLocationsLocationTemplateVO> storageLocationsLocationTemplateVOS,
                                                 Boolean isUpdateSupport,
                                                 String operName) {
        // 空数据校验
        if (CollectionUtils.isEmpty(storageLocationsLocationTemplateVOS)) {
            throw new ServiceException("导入库位数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Date now = DateUtils.getNowDate();
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        String operId = userId.toString();

        // 批量插入数据集合
        List<StorageLocations> batchInsertList = new ArrayList<>();

        // ========== 核心优化：提前加载所有已存在的库位编码映射 ==========
        Map<String, String> locationCodeToIdMap = loadLocationCodeToIdMap();

        for (StorageLocationsLocationTemplateVO templateVO : storageLocationsLocationTemplateVOS) {
            try {
                StorageLocations storageLocations = new StorageLocations();
                // 1. 库位编码为空校验
                String locationCode = templateVO.getLocationCode();
                if (locationCode == null || locationCode.trim().isEmpty()) {
                    throw new ServiceException("【"+templateVO.getNo()+"】库位编码不能为空");
                }
                // 去除首尾空格，避免因空格导致的重复判断错误
                String cleanLocationCode = locationCode.trim();

                // 2. 库位编码已存在校验（优化：从Map中查询，无需数据库交互）
                if (locationCodeToIdMap.containsKey(cleanLocationCode)) {
                    throw new ServiceException("库位【" + cleanLocationCode + "】已存在");
                }

                // 拷贝基础属性
                BeanUtils.copyProperties(templateVO, storageLocations);
                storageLocations.setLocationName(cleanLocationCode); // 使用去空格后的编码

                // 字段类型转换与赋值
                storageLocations.setId(UUID.randomUUID().toString());
                if (StringUtils.isNotBlank(templateVO.getLocationUsage())) {
                    storageLocations.setLocationUsage(Integer.valueOf(templateVO.getLocationUsage()));
                }
                if (StringUtils.isNotBlank(templateVO.getIsEnabled())) {
                    storageLocations.setIsEnabled(Long.valueOf(templateVO.getIsEnabled()));
                }

                // 填充公共字段
                storageLocations.setCreateBy(operId);
                storageLocations.setCreateTime(now);
                storageLocations.setCreateUserCode(operId);
                storageLocations.setWarehousesCode("固定仓库");
                storageLocations.setWarehousesId(WarehouseConfig.DEFAULT_WAREHOUSE_ID);

                // 设置默认值
                if (storageLocations.getIsUsed() == null) {
                    storageLocations.setIsUsed(1L); // 默认未删除
                }
                if (storageLocations.getSortNo() == null) {
                    storageLocations.setSortNo(0L); // 默认排序号
                }

                // 加入批量集合
                batchInsertList.add(storageLocations);
                successNum++;
                String locationName = storageLocations.getLocationName() != null ? storageLocations.getLocationName() : "未知名称";
                successMsg.append("<br/>" + successNum + "、库位 " + locationName + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String locationCode = templateVO.getLocationCode() != null ? templateVO.getLocationCode() : "未知编码";
                String msg = "<br/>" + failureNum + "、库位编码 " + locationCode + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                // 异常数据跳过，继续处理下一条
                continue;
            }
        }

        // 执行批量插入（有有效数据时）
        if (!CollectionUtils.isEmpty(batchInsertList)) {
            try {
                storageLocationsMapper.batchInsertStorageLocations(batchInsertList);
            } catch (Exception e) {
                // 批量插入失败，更新失败统计
                int batchFailNum = batchInsertList.size();
                failureNum += batchFailNum;
                successNum -= batchFailNum;
                failureMsg.insert(0, String.format("<br/>批量插入失败：%s，失败条数追加 %d 条",
                        e.getMessage(), batchFailNum));
            }
        }

        // 结果反馈处理
        StringBuilder resultMsg = new StringBuilder();
        if (successNum > 0) {
            resultMsg.append("数据导入完成！成功导入 " + successNum + " 条，成功列表如下：");
            resultMsg.append(successMsg);
        }
        if (failureNum > 0) {
            resultMsg.append("<br/><br/>失败导入 " + failureNum + " 条，失败原因如下：");
            resultMsg.append(failureMsg);
        }
        // 如果全部失败，保留友好提示
        if (successNum == 0 && failureNum > 0) {
            resultMsg.insert(0, "很抱歉，所有数据均导入失败！");
        }

        return resultMsg.toString();
    }

    private Map<String, String> loadLocationCodeToIdMap() {
        StorageLocations query = new StorageLocations();
        query.setIsUsed(1L);
        List<StorageLocations> locationList = storageLocationsMapper.selectStorageLocationsList(query);
        if (org.springframework.util.CollectionUtils.isEmpty(locationList)) {
            return Collections.emptyMap();
        }
        return locationList.stream()
                .filter(l -> StringUtils.isNotBlank(l.getLocationCode()))
                // 核心优化：对编码去空格后作为Key，避免空格导致的匹配错误
                .collect(Collectors.toMap(
                        l -> l.getLocationCode().trim(),
                        StorageLocations::getId,
                        (k1, k2) -> k1 // 存在重复编码时保留第一条
                ));
    }
}