package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.shkj.common.constant.HttpStatus;
import com.shkj.common.core.domain.Result;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.wms.bo.SysStockAddBo;
import com.shkj.wms.bo.SysStockEditBo;
import com.shkj.wms.bo.SysStockQueryBo;
import com.shkj.wms.bo.SysStockSaveOrUpdateBo;
import com.shkj.wms.domain.SysStock;
import com.shkj.wms.mapper.SysStockMapper;
import com.shkj.wms.service.IBaseLocationService;
import com.shkj.wms.service.ISysStockDetailService;
import com.shkj.wms.service.ISysStockService;
import com.shkj.wms.vo.BaseLocationVo;
import com.shkj.wms.vo.BusinBillHeadbodyInVo;
import com.shkj.wms.vo.SysStockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库存管理Service业务层处理
 *
 * @author lch
 * @date 2023-05-07
 */
@Slf4j
@Service
public class SysStockServiceImpl extends ServiceImpl<SysStockMapper, SysStock> implements ISysStockService {
    @Autowired
    private IBaseLocationService iBaseLocationService;

    @Autowired
    private ISysStockDetailService iSysStockDetailService;

    @Override
    public Result<SysStockVo> queryById(Long id) {
        SysStock db = this.baseMapper.selectById(id);
        SysStockVo vo = BeanUtil.toBean(db, SysStockVo.class);
        return Result.ok().data(vo);
    }

    @Override
    public List<SysStockVo> queryList(SysStockQueryBo bo) {
        LambdaQueryWrapper<SysStock> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getConsignorId() != null, SysStock::getConsignorId, bo.getConsignorId());
        lqw.eq(bo.getBranchId() != null, SysStock::getBranchId, bo.getBranchId());
        lqw.eq(bo.getStorageId() != null, SysStock::getStorageId, bo.getStorageId());
        lqw.eq(bo.getAreaId() != null, SysStock::getAreaId, bo.getAreaId());
        lqw.eq(StrUtil.isNotBlank(bo.getTunnel()), SysStock::getTunnel, bo.getTunnel());
        lqw.eq(StrUtil.isNotBlank(bo.getGoodsNo()), SysStock::getGoodsNo, bo.getGoodsNo());
        lqw.eq(bo.getQty() != null, SysStock::getQty, bo.getQty());
        lqw.eq(bo.getInQty() != null, SysStock::getInQty, bo.getInQty());
        lqw.eq(bo.getOutQty() != null, SysStock::getOutQty, bo.getOutQty());
        lqw.eq(StrUtil.isNotBlank(bo.getStockStatus()), SysStock::getStockStatus, bo.getStockStatus());
        lqw.orderByDesc(SysStock::getCreateTime);
        List<SysStockVo> voList = entity2Vo(this.list(lqw));
        return voList;

    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<SysStockVo> entity2Vo(Collection<SysStock> collection) {
        List<SysStockVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, SysStockVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<SysStock> page = (Page<SysStock>) collection;
            Page<SysStockVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> insertByAddBo(SysStockAddBo bo) {
        SysStock add = BeanUtil.toBean(bo, SysStock.class);
        this.save(add);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> updateByEditBo(SysStockEditBo bo) {
        SysStock one = getById(bo.getId());
        if (one == null) {
            return Result.err().msg("不存在");
        }
        SysStock update = BeanUtil.toBean(bo, SysStock.class);
        this.updateById(update);
        return Result.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> deleteWithValidById(List<Long> ids, Boolean isValid) {
        LambdaQueryWrapper<SysStock> wrapper = new LambdaQueryWrapper<SysStock>().in(SysStock::getId, ids)
                .eq(SysStock::getBranchId, SecurityUtils.getCurrentBranchId());
        this.remove(wrapper);
        return Result.ok();
    }

    @Override
       @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> productDeposit(Long locationId, Long containerId, String batch, String isPuch, List<Map<String, String>> goods, Long storageCode) {
        //获取库位信息
        Result<BaseLocationVo> baseLocationVoResult = iBaseLocationService.queryById(locationId);
        if (HttpStatus.SUCCESS == baseLocationVoResult.getCode()) {
            Result<Boolean> stockDetailResult = iSysStockDetailService.productDepositDetail(locationId, containerId, batch, isPuch, goods,storageCode);
            if (HttpStatus.SUCCESS != stockDetailResult.getCode()) {
                return Result.err().msg(stockDetailResult.getMsg());
            }
            BaseLocationVo locationVo = baseLocationVoResult.getData();
            SysStockQueryBo stockQueryBo = new SysStockQueryBo();
            stockQueryBo.setBranchId(locationVo.getBranchId());
            stockQueryBo.setStorageId(storageCode);
            stockQueryBo.setAreaId(locationVo.getAreaId());
            stockQueryBo.setTunnel(locationVo.getTunnel());
            List<SysStockVo> sysStockVos = this.queryList(stockQueryBo);
            SysStock sysStock = null;
            for (Map<String, String> good : goods) {
                if (sysStockVos.size() > 0) {
                    sysStock = this.getById(sysStockVos.get(0).getId());
                    sysStock.setStorageId(storageCode);
                    sysStock.setGoodsNo(good.get("goodsNo"));
                    BigDecimal oldQty = sysStock.getQty() != null ? sysStock.getQty() : BigDecimal.valueOf(0);
                    sysStock.setQty(oldQty.add(BigDecimal.valueOf(goods.size())));
                    this.updateById(sysStock);
                } else {
                    sysStock = new SysStock();
                    sysStock.setBranchId(locationVo.getBranchId());
                    sysStock.setStorageId(storageCode);
                    sysStock.setAreaId(locationVo.getAreaId());
                    sysStock.setGoodsNo(good.get("goodsNo"));
                    sysStock.setTunnel(locationVo.getTunnel());
                    sysStock.setQty(BigDecimal.valueOf(goods.size()));
                    this.baseMapper.insert(sysStock);
                }
            }
            return Result.ok();
        } else {
            return Result.err().msg("未找到对应货位信息");
        }
    }





    @Override
    public Result<Boolean> saveOrUpdateStock(SysStockSaveOrUpdateBo bo) {
        SysStock saveOrupDate = null;
        if (bo.getId() != null) {
            SysStock one = getById(bo.getId());
            if (one == null) {
                log.info("库存信息不存在:" + bo.toString());
                return Result.err().msg("库存信息不存在");
            }
        }
        saveOrupDate = BeanUtil.toBean(bo, SysStock.class);
        saveOrupDate.setBranchId(SecurityUtils.getCurrentBranchId());
        this.saveOrUpdate(saveOrupDate);
        return Result.ok();
    }
}
