package cn.iocoder.yudao.module.wms.service.depot;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.FactoryInfoApi;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.dto.FactoryInfoDTO;
import cn.iocoder.yudao.module.wms.controller.admin.depot.vo.DepotPageReqVO;
import cn.iocoder.yudao.module.wms.controller.admin.depot.vo.DepotRespVO;
import cn.iocoder.yudao.module.wms.controller.admin.depot.vo.DepotSaveReqVO;
import cn.iocoder.yudao.module.wms.dal.dataobject.depot.DepotDO;
import cn.iocoder.yudao.module.wms.dal.mysql.depot.DepotMapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仓库管理 Service 实现类
 *
 * @author 艾楷
 */
@Service
@Validated
public class DepotServiceImpl implements DepotService {

    @Resource
    private DepotMapper depotMapper;
    @Resource
    private FactoryInfoApi factoryInfoApi;

    @Override
    public Long createDepot(DepotSaveReqVO createReqVO) {
        // 插入
        DepotDO depot = BeanUtils.toBean(createReqVO, DepotDO.class);
        depot.setDepotNo(IdWorker.get32UUID());
        depotMapper.insert(depot);
        // 返回
        return depot.getId();
    }

    @Override
    public void updateDepot(DepotSaveReqVO updateReqVO) {
        // 更新
        DepotDO updateObj = BeanUtils.toBean(updateReqVO, DepotDO.class);
        depotMapper.updateById(updateObj);
    }

    @Override
    public void deleteDepot(Long id) {
        // 删除
        depotMapper.deleteById(id);
    }

    @Override
    public DepotDO getDepot(Long id) {
        return depotMapper.selectById(id);
    }

    @Override
    public PageResult<DepotDO> getDepotPage(DepotPageReqVO pageReqVO) {
        PageResult<DepotDO> depotDOPageResult = depotMapper.selectPage(pageReqVO);
        List<Long> factoryIds = depotDOPageResult.getList().stream().map(DepotDO::getFactoryId).collect(Collectors.toList());
        //获取工厂列表名称
        List<FactoryInfoDTO> factoryInfoList = factoryInfoApi.getFactoryInfoList(factoryIds).getCheckedData();
        Map<Long, String> map = factoryInfoList.stream().collect(Collectors.toMap(FactoryInfoDTO::getId, FactoryInfoDTO::getName));
        for (DepotDO depotDO : depotDOPageResult.getList()) {
            depotDO.setFactoryName(map.get(depotDO.getFactoryId()));
        }
        return depotDOPageResult;
    }

    @Override
    public List<DepotRespVO> getDepotList(DepotPageReqVO pageReqVO) {
        return depotMapper.selectAllList(pageReqVO);
    }

}
