package com.ruoyi.inventory.service.impl;

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

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

        for (OwnerTemplateVO ownerTemp : ownersList) {
            try {
                Owners owners = new Owners();
                // 处理激活状态转换
                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++;
                successMsg.append("<br/>" + successNum + "、用户 " + owners.getOwnerName() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String ownerName = ownerTemp.getOwnerCode() != null ? ownerTemp.getOwnerCode() : "未知名称";
                String msg = "<br/>" + failureNum + "、账号 " + ownerName + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                // 异常数据不加入批量集合，继续处理下一条
                continue;
            }
        }

        // 批量插入有效数据（如果有）
        if (!CollectionUtils.isEmpty(batchInsertList)) {
            try {
                ownersMapper.batchInsertOwners(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();
    }

    /**
     * 修改货主信息
     * 
     * @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);
    }

}
