package cn.iocoder.yudao.module.pms.service.iotlockstock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotlockstock.vo.IotLockStockPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotlockstock.vo.IotLockStockSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotlockstock.IotLockStockDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotlockstock.IotLockStockMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptSapOrgApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptSapOrgRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_LOCK_STOCK_NOT_EXISTS;

/**
 * PMS 本地 库存 Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class IotLockStockServiceImpl implements IotLockStockService {

    @Resource
    private IotLockStockMapper iotLockStockMapper;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeptSapOrgApi deptSapOrgApi;

    @Override
    public Long createIotLockStock(IotLockStockSaveReqVO createReqVO) {
        // 插入
        IotLockStockDO iotLockStock = BeanUtils.toBean(createReqVO, IotLockStockDO.class);
        iotLockStockMapper.insert(iotLockStock);
        // 返回
        return iotLockStock.getId();
    }

    @Override
    public void updateIotLockStock(IotLockStockSaveReqVO updateReqVO) {
        // 校验存在
        validateIotLockStockExists(updateReqVO.getId());
        // 更新
        IotLockStockDO updateObj = BeanUtils.toBean(updateReqVO, IotLockStockDO.class);
        iotLockStockMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotLockStock(Long id) {
        // 校验存在
        validateIotLockStockExists(id);
        // 删除
        iotLockStockMapper.deleteById(id);
    }

    private void validateIotLockStockExists(Long id) {
        if (iotLockStockMapper.selectById(id) == null) {
            throw exception(IOT_LOCK_STOCK_NOT_EXISTS);
        }
    }

    @Override
    public IotLockStockDO getIotLockStock(Long id) {
        return iotLockStockMapper.selectById(id);
    }

    @Override
    public PageResult<IotLockStockDO> getIotLockStockPage(IotLockStockPageReqVO pageReqVO) {
        return iotLockStockMapper.selectPage(pageReqVO);
    }

    @Override
    public List<IotLockStockDO> getIotLockStocks(IotLockStockPageReqVO pageReqVO) {
        return iotLockStockMapper.selectList(pageReqVO);
    }

    @Override
    public Map<String, BigDecimal> getIotLockStockList(IotLockStockPageReqVO pageReqVO) {
        List<IotLockStockDO> lockStocks = iotLockStockMapper.selectList(pageReqVO);
        Map<String, BigDecimal> stockQuantityPair = new HashMap<>();
        if (CollUtil.isNotEmpty(lockStocks)) {
            lockStocks.forEach(stock -> {
                stockQuantityPair.put(StrUtil.join("-",stock.getCostCenterId(), stock.getMaterialCode()), stock.getQuantity());
            });
        }
        return stockQuantityPair;
    }

    @Override
    public Long manualWarehouse(List<IotLockStockSaveReqVO> createReqVO) {
        // 查询当前登录人所属组织 关联的工厂 库存地点 成本中心
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        Long deptId = user.getDeptId();
        List<DeptSapOrgRespDTO> deptSapOrgs = deptSapOrgApi.getDeptSapOrgList(deptId);
        List<Long> factoryIds = new ArrayList<>();
        List<Long> costCenterIds = new ArrayList<>();
        List<Long> storageLocationIds = new ArrayList<>();
        // 遍历数组 获得 工厂 成本中心
        deptSapOrgs.forEach(sapOrg -> {
            if (ObjectUtil.isNotNull(sapOrg.getFactoryId())) {
                factoryIds.add(sapOrg.getFactoryId());
            }
            if (ObjectUtil.isNotNull(sapOrg.getCostCenterId())) {
                costCenterIds.add(sapOrg.getCostCenterId());
            }
            if (ObjectUtil.isNotNull(sapOrg.getStockLocationId())) {
                storageLocationIds.add(sapOrg.getStockLocationId());
            }
        });
        // 保存入库数据
        createReqVO.forEach(req -> {
            req.setDeptId(deptId);
            if (CollUtil.isNotEmpty(factoryIds)) {
                req.setFactoryId(factoryIds.get(0));
            }
            if (CollUtil.isNotEmpty(costCenterIds)) {
                req.setCostCenterId(costCenterIds.get(0));
            }
            if (CollUtil.isNotEmpty(storageLocationIds)) {
                req.setStorageLocationId(storageLocationIds.get(0));
            }
            req.setStorageTime(LocalDateTime.now());
            req.setType(1);
        });
        List<IotLockStockDO> lockStockDOS = BeanUtils.toBean(createReqVO, IotLockStockDO.class);
        iotLockStockMapper.insertBatch(lockStockDOS);
        return 0l;
    }

}