package com.wansenai.service.stock.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wansenai.entities.stock.BasStockAccount;
import com.wansenai.entities.warehouse.Warehouse;
import com.wansenai.mappers.stock.BasStockAccountMapper;
import com.wansenai.mappers.warehouse.WarehouseMapper;
import com.wansenai.service.product.ProductService;
import com.wansenai.service.stock.BasStockAccountService;
import com.wansenai.service.user.ISysUserService;
import com.wansenai.utils.SnowflakeIdUtil;
import com.wansenai.vo.product.ProductDetailVO;
import com.wansenai.vo.stock.StockAccountVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BasStockAccountServiceImpl extends ServiceImpl<BasStockAccountMapper, BasStockAccount> implements BasStockAccountService {

    private final ISysUserService sysUserService;
    private final WarehouseMapper warehouseMapper;
    private final ProductService productService;

    @Override
    public BasStockAccount getStockInfo(Long warehouseId, Long goodsId) {
        return baseMapper.getStockByWarehouseAndGoods(warehouseId, goodsId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStockQty(Long id, BigDecimal qty) {
        return baseMapper.updateStockQty(id, qty) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLockQty(Long id, BigDecimal qtyLock) {
        return baseMapper.updateLockQty(id, qtyLock) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTranQty(Long id, BigDecimal qtyTran) {
        return baseMapper.updateTranQty(id, qtyTran) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAddStock(List<BasStockAccount> stockList) {
        if (CollectionUtils.isEmpty(stockList)) {
            return false;
        }
        
        Date now = new Date();
        String currentUser = sysUserService.getCurrentUserName();
        stockList.forEach(stock -> {
            stock.setId(SnowflakeIdUtil.nextId());
            stock.setCreateTime(now);
            stock.setCreateBy(currentUser);
        });
        
        return baseMapper.batchInsert(stockList) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStock(BasStockAccount stock) {
        stock.setId(SnowflakeIdUtil.nextId());
        stock.setCreateTime(new Date());
        stock.setCreateBy(sysUserService.getCurrentUserName());
        return save(stock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(BasStockAccount stock) {
        stock.setUpdateTime(new Date());
        stock.setUpdateBy(sysUserService.getCurrentUserName());
        return updateById(stock);
    }

    @Override
    public StockAccountVO getStockDetailById(Long id) {
        BasStockAccount stock = getById(id);
        if (stock == null) {
            return null;
        }
        
        return convertToVO(stock);
    }

    @Override
    public IPage<StockAccountVO> getStockVOPage(Page<BasStockAccount> page, Long warehouseId, Long goodsId) {
        LambdaQueryWrapper<BasStockAccount> queryWrapper = new LambdaQueryWrapper<BasStockAccount>()
                .eq(warehouseId != null, BasStockAccount::getWarehouseId, warehouseId)
                .eq(goodsId != null, BasStockAccount::getGoodsId, goodsId);
        
        Page<BasStockAccount> stockPage = page(page, queryWrapper);
        
        return stockPage.convert(this::convertToVO);
    }

    private StockAccountVO convertToVO(BasStockAccount stock) {
        StockAccountVO vo = new StockAccountVO();
        BeanUtils.copyProperties(stock, vo);
        
        // 获取仓库信息
        if (stock.getWarehouseId() != null) {
            Warehouse warehouse = warehouseMapper.selectById(stock.getWarehouseId());
            if (warehouse != null) {
                vo.setWarehouseName(warehouse.getWarehouseName());
            }
        }
        
        // 获取商品信息
        if (stock.getGoodsId() != null) {
            ProductDetailVO product = productService.getProductInfoDetail(stock.getGoodsId()).getData();
            if (product != null) {
                vo.setGoodsName(product.getProductName());
                vo.setGoodsStandard(product.getStandard());
                vo.setGoodsModel(product.getModel());
                vo.setGoodsUnit(product.getUnit());
            }
        }
        
        return vo;
    }
}
