package cn.iocoder.foodnexus.module.erp.service.stock;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.foodnexus.framework.common.enums.CommonStatusEnum;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpWarehouseApi;
import cn.iocoder.foodnexus.module.erp.api.vo.warehouse.WarehouseInfo;
import cn.iocoder.foodnexus.module.erp.controller.admin.stock.vo.warehouse.ErpWarehouseSaveReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.stock.vo.warehouse.ErpWarehousePageReqVO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.stock.ErpWarehouseDO;
import cn.iocoder.foodnexus.module.erp.dal.mysql.stock.ErpWarehouseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.foodnexus.module.erp.enums.ErrorCodeConstants.*;

/**
 * ERP 仓库 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpWarehouseServiceImpl implements ErpWarehouseService, ErpWarehouseApi {

    @Resource
    private ErpWarehouseMapper warehouseMapper;

    @Override
    public Long createWarehouse(ErpWarehouseSaveReqVO createReqVO) {
        // 插入
        ErpWarehouseDO warehouse = BeanUtils.toBean(createReqVO, ErpWarehouseDO.class);
        warehouseMapper.insert(warehouse);
        // 返回
        return warehouse.getId();
    }

    @Override
    public void updateWarehouse(ErpWarehouseSaveReqVO updateReqVO) {
        // 校验存在
        validateWarehouseExists(updateReqVO.getId());
        // 更新
        ErpWarehouseDO updateObj = BeanUtils.toBean(updateReqVO, ErpWarehouseDO.class);
        warehouseMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWarehouseDefaultStatus(Long id, Boolean defaultStatus) {
        // 1. 校验存在
        validateWarehouseExists(id);

        // 2.1 如果开启，则需要关闭所有其它的默认
        if (defaultStatus) {
            ErpWarehouseDO warehouse = warehouseMapper.selectByDefaultStatus();
            if (warehouse != null) {
                warehouseMapper.updateById(new ErpWarehouseDO().setId(warehouse.getId()).setDefaultStatus(false));
            }
        }
        // 2.2 更新对应的默认状态
        warehouseMapper.updateById(new ErpWarehouseDO().setId(id).setDefaultStatus(defaultStatus));
    }

    @Override
    public void deleteWarehouse(Long id) {
        // 校验存在
        validateWarehouseExists(id);
        // 删除
        warehouseMapper.deleteById(id);
    }

    private void validateWarehouseExists(Long id) {
        if (warehouseMapper.selectById(id) == null) {
            throw exception(WAREHOUSE_NOT_EXISTS);
        }
    }

    @Override
    public ErpWarehouseDO getWarehouse(Long id) {
        return warehouseMapper.selectById(id);
    }

    @Override
    public List<ErpWarehouseDO> validWarehouseList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<ErpWarehouseDO> list = warehouseMapper.selectByIds(ids);
        Map<Long, ErpWarehouseDO> warehouseMap = convertMap(list, ErpWarehouseDO::getId);
        for (Long id : ids) {
            ErpWarehouseDO warehouse = warehouseMap.get(id);
            if (warehouseMap.get(id) == null) {
                throw exception(WAREHOUSE_NOT_EXISTS);
            }
            if (CommonStatusEnum.isDisable(warehouse.getStatus())) {
                throw exception(WAREHOUSE_NOT_ENABLE, warehouse.getName());
            }
        }
        return list;
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseListByStatus(Integer status, String level) {
        return warehouseMapper.selectListByStatus(status, level);
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseList(Collection<Long> ids) {
        return warehouseMapper.selectByIds(ids);
    }

    @Override
    public PageResult<ErpWarehouseDO> getWarehousePage(ErpWarehousePageReqVO pageReqVO) {
        return warehouseMapper.selectPage(pageReqVO);
    }

    @Override
    public Map<Long, String> queryNameByIds(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return new HashMap<>();
        }
        Map<Long, String> rootMap = new HashMap<>();
        rootMap.put(ErpWarehouseDO.PARENT_ID_ROOT, "");
        List<Long> collect = ids.stream().filter(id -> !Objects.equals(id, ErpWarehouseDO.PARENT_ID_ROOT)).toList();
        if (CommonUtil.isEmpty(collect)) {
            return rootMap;
        }
        List<ErpWarehouseDO> erpWarehouseDOS = warehouseMapper.selectByIds(collect);
        Map<Long, String> result = CommonUtil.listConvertMap(erpWarehouseDOS, ErpWarehouseDO::getId, ErpWarehouseDO::getName);
        result.putAll(rootMap);
        return result;
    }

    /**
     * 获取仓库/库区名称
     *
     * @param ids
     * @return
     */
    @Override
    public Map<Long, String> getNameWithParentMap(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return new HashMap<>();
        }
        List<ErpWarehouseDO> erpWarehouseDOS = warehouseMapper.selectByIds(ids);
        return CommonUtil.listConvertMap(erpWarehouseDOS, ErpWarehouseDO::getId, value -> {
            if (!ErpWarehouseDO.PARENT_ID_ROOT.equals(value.getParentId())) {
                return Optional.ofNullable(this.getWarehouse(value.getParentId())).map(parent -> parent.getName() + "/").orElse("") + value.getName();
            }
            return value.getName();
        });
    }

    @Override
    public boolean existsById(Long warehouseId) {
        return warehouseMapper.exists(Wrappers.<ErpWarehouseDO>lambdaQuery()
                .eq(ErpWarehouseDO::getId, warehouseId)
                .eq(ErpWarehouseDO::getStatus, CommonStatusEnum.ENABLE.getStatus()));
    }

    @Override
    public WarehouseInfo getInfoByWarehouseAreaId(Long warehouseAreaId) {
        ErpWarehouseDO erpWarehouseDO = warehouseMapper.selectOne(Wrappers.<ErpWarehouseDO>lambdaQuery()
                .eq(ErpWarehouseDO::getId, warehouseAreaId)
                .eq(ErpWarehouseDO::getStatus, CommonStatusEnum.ENABLE.getStatus()));
        if (CommonUtil.isNotEmpty(erpWarehouseDO)) {
            WarehouseInfo info = BeanUtils.toBean(erpWarehouseDO, WarehouseInfo.class);
            info.setWarehouseId(erpWarehouseDO.getParentId());
            info.setWarehouseId(erpWarehouseDO.getId());
            return info;
        }
        return null;
    }
}
