package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maintain.business.domain.*;
import com.maintain.business.domain.bo.ErpMaterialPutawayBo;
import com.maintain.business.domain.bo.ErpMaterialPutawayInfoBo;
import com.maintain.business.domain.vo.*;
import com.maintain.business.mapper.*;
import com.maintain.business.service.IErpMaterialPutawayService;
import com.maintain.business.service.IErpMaterialService;
import com.maintain.common.core.domain.BaseEntity;
import com.maintain.common.core.domain.PageQuery;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.enums.PickingState;
import com.maintain.common.helper.LoginHelper;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 物料入库Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-03
 */
@RequiredArgsConstructor
@Service
public class ErpMaterialPutawayServiceImpl implements IErpMaterialPutawayService {

    private final ErpMaterialPutawayMapper baseMapper;
    private final ErpMaterialVendorMapper materialVendorMapper;
    private final ErpWarehouseMapper warehouseMapper;
    private final ErpMaterialPutawayInfoMapper putawayInfoMapper;
    private final ErpMaterialMapper materialMapper;
    private final IErpMaterialService materialService;

    /**
     * 查询物料入库
     */
    @Override
    public ErpMaterialPutawayVo queryById(Long id){
        ErpMaterialPutawayVo putawayVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<ErpMaterialPutawayInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpMaterialPutawayInfo::getPutawayId, id);
        putawayVo.setPutawayInfoList(putawayInfoMapper.selectVoList(lqw));
        return putawayVo;
    }

    /**
     * 查询物料入库列表
     */
    @Override
    public TableDataInfo<ErpMaterialPutawayVo> queryPageList(ErpMaterialPutawayBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaterialPutaway> lqw = buildQueryWrapper(bo);
        Page<ErpMaterialPutawayVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询物料入库列表
     */
    @Override
    public List<ErpMaterialPutawayVo> queryList(ErpMaterialPutawayBo bo) {
        LambdaQueryWrapper<ErpMaterialPutaway> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpMaterialPutaway> buildQueryWrapper(ErpMaterialPutawayBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpMaterialPutaway> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getOrderNumber()), ErpMaterialPutaway::getOrderNumber, bo.getOrderNumber());
        lqw.like(StringUtils.isNotBlank(bo.getArrivalNumber()), ErpMaterialPutaway::getArrivalNumber, bo.getArrivalNumber());
        lqw.like(StringUtils.isNotBlank(bo.getPutawayNumber()), ErpMaterialPutaway::getPutawayNumber, bo.getPutawayNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getPutawayType()), ErpMaterialPutaway::getPutawayType, bo.getPutawayType());
        lqw.eq(bo.getPutawayTime() != null, ErpMaterialPutaway::getPutawayTime, bo.getPutawayTime());
        lqw.eq(bo.getPutawayMoney() != null, ErpMaterialPutaway::getPutawayMoney, bo.getPutawayMoney());
        lqw.eq(bo.getWarehouseId() != null, ErpMaterialPutaway::getWarehouseId, bo.getWarehouseId());
        lqw.like(StringUtils.isNotBlank(bo.getWarehouseName()), ErpMaterialPutaway::getWarehouseName, bo.getWarehouseName());
        lqw.eq(bo.getVendorId() != null, ErpMaterialPutaway::getVendorId, bo.getVendorId());
        lqw.like(StringUtils.isNotBlank(bo.getVendorName()), ErpMaterialPutaway::getVendorName, bo.getVendorName());
        lqw.eq(bo.getCreateDeptId() != null, ErpMaterialPutaway::getCreateDeptId, bo.getCreateDeptId());
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增物料入库
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpMaterialPutawayBo bo) {
        ErpMaterialPutaway add = BeanUtil.toBean(bo, ErpMaterialPutaway.class);
        validEntityBeforeSave(add);
        add.setPutawayNumber(RedisUtils.generateNextNumber("RK"));
        ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(add.getWarehouseId());
        add.setWarehouseName(warehouseVo.getName());
        add.setCreateDeptId(LoginHelper.getDeptId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            List<ErpMaterialPutawayInfoBo> infoBoList = bo.getPutawayInfoList();
            List<ErpMaterialPutawayInfo> collect = infoBoList.stream().map(item -> {
                ErpMaterialPutawayInfo putawayInfo = BeanUtil.toBean(item, ErpMaterialPutawayInfo.class);
                ErpMaterial material = materialMapper.selectById(item.getMaterialId());
                BeanUtil.copyProperties(material, putawayInfo);
                putawayInfo.setId(null);
                putawayInfo.setPutawayId(add.getId());
                if (bo.getState().equals(PickingState.TWO.getCode())) {
                    // 更新物料库存
                    materialService.modifyMaterialInventory(item.getMaterialId(), item.getPutawayNumber(), true);
                }
                putawayInfo.setState(bo.getState());
                return putawayInfo;
            }).collect(Collectors.toList());
            bo.setId(add.getId());
            putawayInfoMapper.insertBatch(collect);
        }
        return flag;
    }

    /**
     * 批量确认物料入库
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean confirmByIds(Collection<Long> ids) {
        // 更新物料入库状态
        LambdaUpdateWrapper<ErpMaterialPutaway> lqw = Wrappers.lambdaUpdate();
        lqw.in(ErpMaterialPutaway::getId, ids);
        lqw.set(ErpMaterialPutaway::getState, PickingState.TWO.getCode());
        boolean flag = baseMapper.update(lqw) > 0;
        if (flag) {
            // 更新入库明细状态
            LambdaUpdateWrapper<ErpMaterialPutawayInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.in(ErpMaterialPutawayInfo::getPutawayId, ids).set(ErpMaterialPutawayInfo::getState, PickingState.TWO.getCode());
            putawayInfoMapper.update(updateWrapper);

            // 更新物料库存
            LambdaQueryWrapper<ErpMaterialPutawayInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(ErpMaterialPutawayInfo::getPutawayId, ids).eq(ErpMaterialPutawayInfo::getState, PickingState.ONE.getCode());
            List<ErpMaterialPutawayInfo> putawayInfoList = putawayInfoMapper.selectList(queryWrapper);
            for (ErpMaterialPutawayInfo info : putawayInfoList) {
                materialService.modifyMaterialInventory(info.getMaterialId(), info.getPutawayNumber(), false);
            }
        }
        return flag;
    }

    /**
     * 修改物料入库
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ErpMaterialPutawayBo bo) {
        ErpMaterialPutaway update = BeanUtil.toBean(bo, ErpMaterialPutaway.class);
        validEntityBeforeSave(update);
        ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(update.getWarehouseId());
        update.setWarehouseName(warehouseVo.getName());
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 删除原有进货明细
            LambdaQueryWrapper<ErpMaterialPutawayInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ErpMaterialPutawayInfo::getPutawayId, bo.getId());
            List<ErpMaterialPutawayInfoVo> putawayInfoVoList = putawayInfoMapper.selectVoList(queryWrapper);
            for (ErpMaterialPutawayInfoVo infoVo : putawayInfoVoList) {
                if (infoVo.getState().equals(PickingState.TWO.getCode())) {
                    // 更新物料库存
                    materialService.modifyMaterialInventory(infoVo.getMaterialId(), infoVo.getPutawayNumber(), false);
                }
            }
            putawayInfoMapper.delete(queryWrapper);
            // 绑定新的进货明细
            List<ErpMaterialPutawayInfoBo> infoBoList = bo.getPutawayInfoList();
            List<ErpMaterialPutawayInfo> collect = infoBoList.stream().map(item -> {
                ErpMaterialPutawayInfo putawayInfo = BeanUtil.toBean(item, ErpMaterialPutawayInfo.class);
                ErpMaterial material = materialMapper.selectById(item.getMaterialId());
                BeanUtil.copyProperties(material, putawayInfo);
                putawayInfo.setId(null);
                putawayInfo.setPutawayId(update.getId());
                if (bo.getState().equals(PickingState.TWO.getCode())) {
                    // 更新物料库存
                    materialService.modifyMaterialInventory(item.getMaterialId(), item.getPutawayNumber(), true);
                }
                putawayInfo.setState(bo.getState());
                return putawayInfo;
            }).collect(Collectors.toList());
            putawayInfoMapper.insertBatch(collect);
        }
        return flag;
    }

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

    /**
     * 批量删除物料入库
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 根据ID列表查询入库明细
        LambdaQueryWrapper<ErpMaterialPutawayInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ErpMaterialPutawayInfo::getPutawayId, ids);
        List<ErpMaterialPutawayInfoVo> putawayInfoVoList = putawayInfoMapper.selectVoList(queryWrapper);
        // 遍历处理明细数据
        for (ErpMaterialPutawayInfoVo infoVo : putawayInfoVoList) {
            if (infoVo.getState().equals(PickingState.TWO.getCode())) {
                // 更新物料库存
                materialService.modifyMaterialInventory(infoVo.getMaterialId(), infoVo.getPutawayNumber(), false);
            }
        }
        // 删除入库明细
        putawayInfoMapper.delete(queryWrapper);
        // 删除入库单
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
