package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.enums.biz.ProductType;
import org.dromara.common.core.enums.biz.StockOperType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.web.domain.*;
import org.dromara.web.domain.bo.ProductInOutRecordBo;
import org.dromara.web.domain.vo.ProductInOutRecordVo;
import org.dromara.web.mapper.*;
import org.dromara.web.service.IProductInOutRecordService;
import org.springframework.stereotype.Service;

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

/**
 * 产品出入库记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProductInOutRecordServiceImpl implements IProductInOutRecordService {

    private final ProductInOutRecordMapper baseMapper;

    private final ProductStockMapper productStockMapper;

    private final StorageLocationMapper locationMapper;

    private final ProductCategoryMapper productCategoryMapper;

    private final SuppliesCategoryMapper suppliesCategoryMapper;

    /**
     * 查询产品出入库记录
     *
     * @param id 主键
     * @return 产品出入库记录
     */
    @Override
    public ProductInOutRecordVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询产品出入库记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品出入库记录分页列表
     */
    @Override
    public TableDataInfo<ProductInOutRecordVo> queryPageList(ProductInOutRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProductInOutRecord> lqw = buildQueryWrapper(bo);
        Page<ProductInOutRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的产品出入库记录列表
     *
     * @param bo 查询条件
     * @return 产品出入库记录列表
     */
    @Override
    public List<ProductInOutRecordVo> queryList(ProductInOutRecordBo bo) {
        LambdaQueryWrapper<ProductInOutRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ProductInOutRecord> buildQueryWrapper(ProductInOutRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ProductInOutRecord> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ProductInOutRecord::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ProductInOutRecord::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getProductType()), ProductInOutRecord::getProductType, bo.getProductType());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitType()), ProductInOutRecord::getVisitType, bo.getVisitType());
        lqw.eq(StringUtils.isNotBlank(bo.getPreUnit()), ProductInOutRecord::getPreUnit, bo.getPreUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), ProductInOutRecord::getUnit, bo.getUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getSerialNo()), ProductInOutRecord::getSerialNo, bo.getSerialNo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ProductInOutRecord::getStatus, bo.getStatus());
        if (bo.getSearchValue() != null) {
            lqw.and(wrapper -> wrapper.eq(ProductInOutRecord::getProductName, bo.getSearchValue()).or().eq(ProductInOutRecord::getProductNo, bo.getSearchValue()));
        }
        return lqw;
    }

    /**
     * 新增产品出入库记录
     *
     * @param boList 产品出入库记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(List<ProductInOutRecordBo> boList) {
        boolean flag = false;
        if (CollUtil.isNotEmpty(boList)) {
            ProductInOutRecordBo bo = null;
            ProductInOutRecord add = null;
            List<ProductStock> stockList = null;
            ProductStock stock = null;
            List<StorageLocation> locationList = locationMapper.selectList(Wrappers.lambdaQuery(StorageLocation.class).select(StorageLocation::getId, StorageLocation::getStorageName));
            Map<Long, String> locationMap = locationList.stream().collect(Collectors.toMap(k1 -> k1.getId(), k2 -> String.valueOf(k2.getStorageName()), (k1, k2) -> k1));

            List<ProductCategory> productCategoryList = productCategoryMapper.selectList(Wrappers.lambdaQuery(ProductCategory.class).select(ProductCategory::getCategoryId, ProductCategory::getCategoryName));
            Map<Long, String> productCategoryMap = productCategoryList.stream().collect(Collectors.toMap(k1 -> k1.getCategoryId(), k2 -> String.valueOf(k2.getCategoryName()), (k1, k2) -> k1));

            List<SuppliesCategory> suppliesCategoryList = suppliesCategoryMapper.selectList(Wrappers.lambdaQuery(SuppliesCategory.class).select(SuppliesCategory::getCategoryId, SuppliesCategory::getCategoryName));
            Map<Long, String> suppliesCategoryMap = suppliesCategoryList.stream().collect(Collectors.toMap(k1 -> k1.getCategoryId(), k2 -> String.valueOf(k2.getCategoryName()), (k1, k2) -> k1));
            for (int i = 0; i < boList.size(); i++) {
                bo = boList.get(i);
                bo.setLocationName(locationMap.get(bo.getLocationId()));
                if (bo.getProductType().equals(ProductType.TYPE_ONE.getCode())) {
                    bo.setCategoryName(productCategoryMap.get(bo.getCategoryId()));
                } else {
                    bo.setCategoryName(suppliesCategoryMap.get(bo.getCategoryId()));

                }
                add = MapstructUtils.convert(bo, ProductInOutRecord.class);
                validEntityBeforeSave(add);

                flag = baseMapper.insert(add) > 0;
                if (flag) {
                    bo.setId(add.getId());
                    stockList = productStockMapper.selectList(new LambdaQueryWrapper<ProductStock>().eq(ProductStock::getProductId, bo.getProductId()).eq(ProductStock::getLocationId, bo.getLocationId()));
                    if (CollUtil.isNotEmpty(stockList)) {
                        stock = stockList.get(0);
                        if (bo.getType().equals(StockOperType.OPER_TYPE_ZERO.getCode())) {
                            stock.setStockNum(stock.getStockNum() + bo.getNum());
                            stock.setTotalStockNum(stock.getTotalStockNum() + bo.getNum());
                        } else {
                            stock.setStockNum(stock.getStockNum() - bo.getNum());
//                            stock.setTotalStockNum(stock.getTotalStockNum() - bo.getNum());  出库时总库存应保持不变  只修改可用库存
                        }
                        productStockMapper.updateById(stock);
                    } else {
                        stock = new ProductStock();
                        stock.setProductType(add.getProductType());
                        stock.setProductNo(add.getProductNo());
                        stock.setCategoryId(add.getCategoryId());
                        stock.setCategoryName(add.getCategoryName());
                        stock.setProductId(add.getProductId());
                        stock.setProductName(add.getProductName());
                        stock.setSpecsName(add.getSpecsName());
                        stock.setLocationId(add.getLocationId());
                        stock.setLocationName(add.getLocationName());
                        stock.setLineNo(add.getLineNo());
                        stock.setTotalStockNum(add.getNum());
                        stock.setStockNum(add.getNum());
                        stock.setExpirationNum(0L);
                        stock.setStockUnit(add.getUnit());
                        productStockMapper.insert(stock);
                    }
                }
            }
        }
        return flag;
    }


    /**
     * 修改产品出入库记录
     *
     * @param bo 产品出入库记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductInOutRecordBo bo) {
        ProductInOutRecord update = MapstructUtils.convert(bo, ProductInOutRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public TableDataInfo<ProductInOutRecordVo> queryStockBalancePage(ProductInOutRecordBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();

        // 计算正确的offset
        int offset = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        Integer count = baseMapper.queryStockBalanceCount(bo.getSearchValue());
        List<ProductInOutRecordVo> balanceVoList = baseMapper.queryStockBalance(bo.getSearchValue(), offset, pageQuery.getPageSize());
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(balanceVoList);
        tableDataInfo.setTotal(count);
        return tableDataInfo;
    }

 /*   @Override
    public TableDataInfo<ProductInOutRecordVo> queryStockBalance(FoodIngredientStockBo bo ) {
        Map<String, Object> params = bo.getParams();

        Integer count = baseMapper.queryStockBalanceCount( bo.getSearchValue());
        List<ProductInOutRecordVo> balanceVoList = baseMapper.queryStockBalance( bo.getSearchValue(), null,null);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(balanceVoList);
        tableDataInfo.setTotal(count);
        return tableDataInfo;
    }*/

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProductInOutRecord entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品出入库记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
