package com.ruoyi.inventory.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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;
    @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<>();

        for (StorageLocationsLocationTemplateVO templateVO : storageLocationsLocationTemplateVOS) {
            try {
                StorageLocations storageLocations = new StorageLocations();
                // 拷贝基础属性
                BeanUtils.copyProperties(templateVO, storageLocations);
                storageLocations.setLocationName(templateVO.getLocationCode());

                // 字段类型转换与赋值
                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 locationName = templateVO.getLocationCode() != null ? templateVO.getLocationCode() : "未知名称";
                String msg = "<br/>" + failureNum + "、库位 " + locationName + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                // 异常数据跳过，继续处理下一条
                continue;
            }
        }

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

        // 结果反馈处理
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
