package com.ruoyi.inventory.service.impl;

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

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inventory.domain.StorageLocations;
import com.ruoyi.inventory.domain.vo.OwnerTemplateVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.inventory.mapper.OwnersMapper;
import com.ruoyi.inventory.domain.Owners;
import com.ruoyi.inventory.service.IOwnersService;

/**
 * 货主信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-28
 */
@Service
public class OwnersServiceImpl implements IOwnersService {
    @Autowired
    private OwnersMapper ownersMapper;

    /**
     * 查询货主信息
     *
     * @param id 货主信息主键
     * @return 货主信息
     */
    @Override
    public Owners selectOwnersById(String id) {
        return ownersMapper.selectOwnersById(id);
    }

    /**
     * 查询货主信息列表
     *
     * @param owners 货主信息
     * @return 货主信息
     */
    @Override
    public List<Owners> selectOwnersList(Owners owners) {
        return ownersMapper.selectOwnersList(owners);
    }

    /**
     * 新增货主信息
     *
     * @param owners 货主信息
     * @return 结果
     */
    @Override
    public int insertOwners(Owners owners) {
        Long userId = SecurityUtils.getUserId();
        String operId = userId.toString();
        Date now = DateUtils.getNowDate();
        // 填充创建人、创建时间、修改人、修改时间
        owners.setId(UUID.randomUUID().toString());
        owners.setCreateBy(operId);
        owners.setCreateTime(now);
        // 填充创建用户编码和更新用户编码
        owners.setCreateUserCode(operId);

        // 设置默认值
        if (owners.getIsActive() == null) {
            owners.setIsActive(1L); // 默认激活
        }
        if (owners.getIsUsed() == null) {
            owners.setIsUsed(1L); // 默认未删除
        }
        if (owners.getSortNo() == null) {
            owners.setSortNo(0L); // 默认排序号
        }
        return ownersMapper.insertOwners(owners);
    }

    @Override
    public String importOwners(List<OwnerTemplateVO> ownersList, Boolean isUpdateSupport, String operName) {
        // 空数据校验
        if (CollectionUtils.isEmpty(ownersList)) {
            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<Owners> batchInsertList = new ArrayList<>();

        // ========== 核心优化：提前加载所有已存在的用户编码映射 ==========
        Map<String, String> ownerCodeToIdMap = loadOwnerCodeToIdMap();

        for (OwnerTemplateVO ownerTemp : ownersList) {
            try {
                Owners owners = new Owners();

                // 核心校验：用户编码（ownerCode）不能为空
                String ownerCode = ownerTemp.getOwnerCode();
                if (ownerCode == null || ownerCode.trim().isEmpty()) {
                    throw new ServiceException("【"+ownerTemp.getNo()+"】用户编码不能为空");
                }
                // 去除首尾空格，避免因空格导致的重复判断错误
                String cleanOwnerCode = ownerCode.trim();

                // 核心优化：从Map中校验用户编码是否已存在（替代数据库查询）
                if (ownerCodeToIdMap.containsKey(cleanOwnerCode)) {
                    throw new ServiceException("用户【" + cleanOwnerCode + "】已存在");
                }

                // 处理激活状态转换
                BeanUtils.copyProperties(ownerTemp, owners);
                if (ownerTemp.getIsActive() != null) {
                    owners.setIsActive(Long.valueOf(ownerTemp.getIsActive()));
                }
                // 类型转换
                if (ownerTemp.getOwnerType() != null) {
                    owners.setOwnerType(Long.valueOf(ownerTemp.getOwnerType()));
                }
                // 生成UUID主键
                owners.setId(UUID.randomUUID().toString());

                // 填充公共字段
                owners.setCreateBy(operId);
                owners.setCreateTime(now);
                owners.setCreateUserCode(operId);

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

                // 加入批量集合
                batchInsertList.add(owners);
                successNum++;
                String ownerName = owners.getOwnerName() != null ? owners.getOwnerName() : cleanOwnerCode;
                successMsg.append("<br/>" + successNum + "、用户 " + ownerName + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String ownerCode = ownerTemp.getOwnerCode() != null ? ownerTemp.getOwnerCode() : "未知编码";
                String msg = "<br/>" + failureNum + "、用户编码 " + ownerCode + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                // 异常数据跳过，继续处理下一条
                continue;
            }
        }

        // 批量插入有效数据（如果有）
        if (!CollectionUtils.isEmpty(batchInsertList)) {
            try {
                ownersMapper.batchInsertOwners(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> loadOwnerCodeToIdMap() {
        // 查询条件补充：仅查询未删除的用户（符合业务逻辑）
        Owners query = new Owners();
        query.setIsUsed(1L);
        List<Owners> ownerList = ownersMapper.selectOwnersList(query);

        if (org.springframework.util.CollectionUtils.isEmpty(ownerList)) {
            return Collections.emptyMap();
        }
        return ownerList.stream()
                .filter(o -> StringUtils.isNotBlank(o.getOwnerCode()))
                // 核心优化：对编码去空格后作为Key，避免空格导致的匹配错误
                .collect(Collectors.toMap(
                        o -> o.getOwnerCode().trim(),
                        Owners::getId,
                        (k1, k2) -> k1 // 存在重复编码时保留第一条（避免Map键冲突）
                ));
    }

    /**
     * 修改货主信息
     * 
     * @param owners 货主信息
     * @return 结果
     */
    @Override
    public int updateOwners(Owners owners)
    {
        Long userId = SecurityUtils.getUserId();
        String operId = userId.toString();
        Date now = DateUtils.getNowDate();
        // 填充修改人、修改时间和更新用户编码
        owners.setUpdateBy(operId);
        owners.setUpdateTime(now);
        owners.setUpdateUserCode(operId);
        return ownersMapper.updateOwners(owners);
    }

    /**
     * 批量删除货主信息
     * 
     * @param ids 需要删除的货主信息主键
     * @return 结果
     */
    @Override
    public int deleteOwnersByIds(String[] ids)
    {
        return ownersMapper.deleteOwnersByIds(ids);
    }

    /**
     * 删除货主信息信息
     * 
     * @param id 货主信息主键
     * @return 结果
     */
    @Override
    public int deleteOwnersById(String id)
    {
        return ownersMapper.deleteOwnersById(id);
    }

}
