package com.njzscloud.dispose.wh.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.sn.support.SnUtil;
import com.njzscloud.dispose.wh.mapper.InventoryMapper;
import com.njzscloud.dispose.wh.mapper.OutOrderMapper;
import com.njzscloud.dispose.wh.pojo.entity.InventoryEntity;
import com.njzscloud.dispose.wh.pojo.entity.OutOrderEntity;
import com.njzscloud.dispose.wh.pojo.param.AddOutOrderParam;
import com.njzscloud.dispose.wh.pojo.param.SearchOutOrderParam;
import com.njzscloud.dispose.wh.pojo.result.SearchOutOrderResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 出库单
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OutOrderService extends ServiceImpl<OutOrderMapper, OutOrderEntity> {

    private final InventoryMapper inventoryMapper;

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(AddOutOrderParam addOutOrderParam) {
        OutOrderEntity entity = BeanUtil.copyProperties(addOutOrderParam, OutOrderEntity.class);
        entity.setSn(this.generateSn());
        entity.setOutTime(LocalDateTime.now());
        this.save(entity);

        // 更新库存信息
        InventoryEntity inventory = inventoryMapper.selectOne(Wrappers.<InventoryEntity>lambdaQuery()
            .eq(InventoryEntity::getGoodsId, entity.getGoodsId())
            .eq(InventoryEntity::getWarehouseId, entity.getWarehouseId())
            .eq(InventoryEntity::getDeleted, Boolean.FALSE));

        if (inventory != null) {
            // 更新当前库存数量
            inventory.setStockQuantity(inventory.getStockQuantity() - entity.getQuantity());
            // 计算剩余量 = 总量 - 当前库存数量
            inventory.setRemainingQuantity(inventory.getTotalQuantity() - inventory.getStockQuantity());
            inventoryMapper.updateById(inventory);
        } else {
            log.info("通过仓库id: {}和产品id: {}未查询到库存信息，无法处理库存", entity.getWarehouseId(), entity.getGoodsId());
        }
    }

    /**
     * 修改
     */
    public void modify(OutOrderEntity outOrderEntity) {
        this.updateById(outOrderEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public SearchOutOrderResult detail(Long id) {
        return baseMapper.detail(id);
    }

    /**
     * 分页查询
     */
    public PageResult<SearchOutOrderResult> paging(PageParam pageParam, SearchOutOrderParam param) {
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.query()
            .eq("woo.deleted", 0)
            .eq(StrUtil.isNotBlank(param.getSn()), "woo.sn", param.getSn())
            .eq(StrUtil.isNotBlank(param.getOrderSn()), "woo.order_sn", param.getOrderSn())
            .eq(StrUtil.isNotBlank(param.getWarehouseName()), "ww.warehouse_name", param.getWarehouseName())
            .eq(StrUtil.isNotBlank(param.getGoodsName()), "woo.goods_name", param.getGoodsName())
        ));
    }

    /**
     * 生成入库单号
     *
     * @return sn 入库单号
     */
    public String generateSn() {
        String sn = SnUtil.next("Out-Order-SN");
        if (this.exists(Wrappers.<OutOrderEntity>lambdaQuery().eq(OutOrderEntity::getSn, sn)
            .eq(OutOrderEntity::getDeleted, Boolean.FALSE))) {
            this.generateSn();
        }
        return sn;
    }

}
