package com.ruoyi.asset.service.impl;

import java.util.List;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.AmsWarehouseMapper;
import com.ruoyi.asset.domain.AmsWarehouse;
import com.ruoyi.asset.service.IAmsWarehouseService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 仓库管理Service业务层处理
 * 
 * @author Yangk
 * @date 2026-06-03
 */
@Service
public class AmsWarehouseServiceImpl implements IAmsWarehouseService 
{
    private static final String ENABLED_YES = "Y";

    private static final String DEL_FLAG_NORMAL = "0";

    @Autowired
    private AmsWarehouseMapper amsWarehouseMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询仓库管理
     * 
     * @param warehouseId 仓库管理主键
     * @return 仓库管理
     */
    @Override
    public AmsWarehouse selectAmsWarehouseByWarehouseId(Long warehouseId)
    {
        return amsWarehouseMapper.selectAmsWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 查询仓库管理列表
     * 
     * @param amsWarehouse 仓库管理
     * @return 仓库管理
     */
    @Override
    public List<AmsWarehouse> selectAmsWarehouseList(AmsWarehouse amsWarehouse)
    {
        return amsWarehouseMapper.selectAmsWarehouseList(amsWarehouse);
    }

    /**
     * 校验仓库编码是否唯一
     *
     * @param amsWarehouse 仓库管理
     * @return 结果
     */
    @Override
    public boolean checkWarehouseCodeUnique(AmsWarehouse amsWarehouse)
    {
        if (StringUtils.isEmpty(amsWarehouse.getWarehouseCode()))
        {
            return UserConstants.UNIQUE;
        }
        Long warehouseId = StringUtils.isNull(amsWarehouse.getWarehouseId()) ? -1L : amsWarehouse.getWarehouseId();
        AmsWarehouse info = amsWarehouseMapper.checkWarehouseCodeUnique(amsWarehouse.getWarehouseCode());
        if (StringUtils.isNotNull(info) && info.getWarehouseId().longValue() != warehouseId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增仓库管理
     * 
     * @param amsWarehouse 仓库管理
     * @return 结果
     */
    @Override
    public int insertAmsWarehouse(AmsWarehouse amsWarehouse)
    {
        if (StringUtils.isEmpty(amsWarehouse.getEnabled()))
        {
            amsWarehouse.setEnabled(ENABLED_YES);
        }
        fillManageDeptName(amsWarehouse);
        fillManagerUserSnapshot(amsWarehouse);
        amsWarehouse.setDelFlag(DEL_FLAG_NORMAL);
        amsWarehouse.setCreateTime(DateUtils.getNowDate());
        return amsWarehouseMapper.insertAmsWarehouse(amsWarehouse);
    }

    /**
     * 修改仓库管理
     * 
     * @param amsWarehouse 仓库管理
     * @return 结果
     */
    @Override
    public int updateAmsWarehouse(AmsWarehouse amsWarehouse)
    {
        fillManageDeptName(amsWarehouse);
        fillManagerUserSnapshot(amsWarehouse);
        amsWarehouse.setUpdateTime(DateUtils.getNowDate());
        return amsWarehouseMapper.updateAmsWarehouse(amsWarehouse);
    }

    /**
     * 批量删除仓库管理
     * 
     * @param warehouseIds 需要删除的仓库管理主键
     * @return 结果
     */
    @Override
    public int deleteAmsWarehouseByWarehouseIds(String warehouseIds)
    {
        String[] ids = Convert.toStrArray(warehouseIds);
        for (String id : ids)
        {
            checkWarehouseReferenced(Long.valueOf(id));
        }
        return amsWarehouseMapper.deleteAmsWarehouseByWarehouseIds(ids);
    }

    /**
     * 删除仓库管理信息
     * 
     * @param warehouseId 仓库管理主键
     * @return 结果
     */
    @Override
    public int deleteAmsWarehouseByWarehouseId(Long warehouseId)
    {
        checkWarehouseReferenced(warehouseId);
        return amsWarehouseMapper.deleteAmsWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 删除前做引用保护，避免仓库作为资产位置主数据被逻辑删除后产生悬挂引用。
     */
    private void checkWarehouseReferenced(Long warehouseId)
    {
        AmsWarehouse warehouse = selectAmsWarehouseByWarehouseId(warehouseId);
        if (StringUtils.isNotNull(warehouse) && amsWarehouseMapper.countWarehouseReferences(warehouseId) > 0)
        {
            throw new ServiceException(String.format("仓库【%1$s】已被引用，不允许删除", warehouse.getWarehouseName()));
        }
    }

    /**
     * 部门名称作为仓库责任部门快照保存，避免前端传入名称和部门ID不一致。
     */
    private void fillManageDeptName(AmsWarehouse amsWarehouse)
    {
        if (StringUtils.isNull(amsWarehouse.getManageDeptId()))
        {
            amsWarehouse.setManageDeptName(null);
            return;
        }

        SysDept query = new SysDept();
        query.setDeptId(amsWarehouse.getManageDeptId());
        query.setStatus(UserConstants.DEPT_NORMAL);
        List<SysDept> deptList = sysDeptService.selectDeptList(query);
        if (deptList == null || deptList.isEmpty())
        {
            throw new ServiceException("管理部门不存在或已停用");
        }
        amsWarehouse.setManageDeptName(deptList.get(0).getDeptName());
    }

    /**
     * 负责人以用户ID为准，姓名只做快照，避免同名用户导致仓库负责人关联错误。
     */
    private void fillManagerUserSnapshot(AmsWarehouse amsWarehouse)
    {
        if (StringUtils.isNull(amsWarehouse.getManagerUserId()))
        {
            amsWarehouse.setManagerName(null);
            amsWarehouse.setContactPhone(null);
            return;
        }

        SysUser user = sysUserService.selectUserById(amsWarehouse.getManagerUserId());
        if (StringUtils.isNull(user)
                || !StringUtils.equals(UserConstants.NORMAL, user.getStatus())
                || !StringUtils.equals(DEL_FLAG_NORMAL, user.getDelFlag()))
        {
            throw new ServiceException("负责人不存在或已停用");
        }
        amsWarehouse.setManagerName(user.getUserName());
        // 联系电话跟随负责人手机号，避免前端手工填写导致负责人和电话不一致。
        amsWarehouse.setContactPhone(StringUtils.isEmpty(user.getPhonenumber()) ? null : user.getPhonenumber());
    }
}
