package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.maintain.business.domain.ErpMaterialPutawayInfo;
import com.maintain.business.domain.ErpMaterialReturnsInfo;
import com.maintain.business.domain.bo.ErpMaterialReturnsInfoBo;
import com.maintain.business.domain.vo.ErpMaterialPutawayVo;
import com.maintain.business.domain.vo.ErpMaterialReturnsInfoVo;
import com.maintain.business.mapper.ErpMaterialPutawayInfoMapper;
import com.maintain.business.mapper.ErpMaterialPutawayMapper;
import com.maintain.business.mapper.ErpMaterialReturnsInfoMapper;
import com.maintain.business.service.IErpMaterialService;
import com.maintain.common.core.domain.BaseEntity;
import com.maintain.common.enums.IsEnableStatus;
import com.maintain.common.helper.LoginHelper;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maintain.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.maintain.business.domain.bo.ErpMaterialReturnsBo;
import com.maintain.business.domain.vo.ErpMaterialReturnsVo;
import com.maintain.business.domain.ErpMaterialReturns;
import com.maintain.business.mapper.ErpMaterialReturnsMapper;
import com.maintain.business.service.IErpMaterialReturnsService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 物料退货Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-07
 */
@RequiredArgsConstructor
@Service
public class ErpMaterialReturnsServiceImpl implements IErpMaterialReturnsService {

    private final ErpMaterialReturnsMapper baseMapper;
    private final ErpMaterialReturnsInfoMapper materialReturnsInfoMapper;
    private final ErpMaterialPutawayMapper materialPutawayMapper;
    private final ErpMaterialPutawayInfoMapper materialPutawayInfoMapper;
    private final IErpMaterialService materialService;

    /**
     * 查询物料退货
     */
    @Override
    public ErpMaterialReturnsVo queryById(Long id){
        ErpMaterialReturnsVo returnsVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<ErpMaterialReturnsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpMaterialReturnsInfo::getReturnsId, id);
        List<ErpMaterialReturnsInfoVo> returnsInfoVos = materialReturnsInfoMapper.selectVoList(lqw);
        returnsVo.setReturnsInfoList(returnsInfoVos);
        return returnsVo;
    }

    /**
     * 查询物料退货列表
     */
    @Override
    public TableDataInfo<ErpMaterialReturnsVo> queryPageList(ErpMaterialReturnsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaterialReturns> lqw = buildQueryWrapper(bo);
        Page<ErpMaterialReturnsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询物料退货列表
     */
    @Override
    public List<ErpMaterialReturnsVo> queryList(ErpMaterialReturnsBo bo) {
        LambdaQueryWrapper<ErpMaterialReturns> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增物料退货
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpMaterialReturnsBo bo) {
        ErpMaterialPutawayVo materialPutawayVo = materialPutawayMapper.selectVoById(bo.getPutawayId());
        ErpMaterialReturns materialReturns = BeanUtil.toBean(materialPutawayVo, ErpMaterialReturns.class);
        materialReturns.setId(null);
        materialReturns.setPutawayId(bo.getPutawayId());
        materialReturns.setReturnsCode(RedisUtils.generateNextNumber("TH"));
        materialReturns.setReturnsMoney(bo.getReturnsMoney());
        materialReturns.setReturnsTime(bo.getReturnsTime());
        materialReturns.setCreateDeptId(LoginHelper.getDeptId());
        boolean flag = baseMapper.insert(materialReturns) > 0;
        if (flag) {
            List<ErpMaterialReturnsInfoBo> infoBoList = bo.getReturnsInfoBoList();
            // 处理退货明细列表
            List<ErpMaterialReturnsInfo> collect = infoBoList.stream().map(item -> {
                ErpMaterialReturnsInfo returnsInfo = BeanUtil.toBean(item, ErpMaterialReturnsInfo.class);
                ErpMaterialPutawayInfo putawayInfo = materialPutawayInfoMapper.selectById(item.getPutawayInfoId());
                BeanUtil.copyProperties(putawayInfo, returnsInfo);
                returnsInfo.setId(null);
                returnsInfo.setReturnsId(materialReturns.getId());
                // 更新物料库存
                materialService.modifyMaterialInventory(item.getMaterialId(), item.getReturnsNumber(), false);
                return returnsInfo;
            }).collect(Collectors.toList());
            materialReturnsInfoMapper.insertBatch(collect);
            // 处理入库明细状态
            List<ErpMaterialPutawayInfo> putawayInfoList = infoBoList.stream().map(item -> {
                ErpMaterialPutawayInfo putawayInfo = materialPutawayInfoMapper.selectById(item.getPutawayInfoId());
                putawayInfo.setIsReturns(IsEnableStatus.YES.getCode());
                putawayInfo.setReturnedNumber(putawayInfo.getReturnedNumber().add(item.getReturnsNumber()));
                return putawayInfo;
            }).collect(Collectors.toList());
            materialPutawayInfoMapper.updateBatchById(putawayInfoList);
        }
        return flag;
    }

    /**
     * 修改物料退货
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ErpMaterialReturnsBo bo) {
        ErpMaterialPutawayVo materialPutawayVo = materialPutawayMapper.selectVoById(bo.getPutawayId());
        ErpMaterialReturns materialReturns = BeanUtil.toBean(materialPutawayVo, ErpMaterialReturns.class);
        materialReturns.setId(bo.getId());
        materialReturns.setReturnsMoney(bo.getReturnsMoney());
        materialReturns.setReturnsTime(bo.getReturnsTime());
        boolean flag = baseMapper.updateById(materialReturns) > 0;
        if (flag) {
            // 删除原有退货明细
            LambdaQueryWrapper<ErpMaterialReturnsInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ErpMaterialReturnsInfo::getReturnsId, bo.getId());
            List<ErpMaterialReturnsInfoVo> returnsInfoVoList = materialReturnsInfoMapper.selectVoList(queryWrapper);
            for (ErpMaterialReturnsInfoVo infoVo : returnsInfoVoList) {
                // 更新物料库存
                materialService.modifyMaterialInventory(infoVo.getMaterialId(), infoVo.getReturnsNumber(), true);
            }

            List<ErpMaterialReturnsInfoBo> infoBoList = bo.getReturnsInfoBoList();
            // 绑定新的退货明细
            List<ErpMaterialReturnsInfo> collect = infoBoList.stream().map(item -> {
                ErpMaterialReturnsInfo returnsInfo = BeanUtil.toBean(item, ErpMaterialReturnsInfo.class);
                ErpMaterialPutawayInfo putawayInfo = materialPutawayInfoMapper.selectById(item.getPutawayInfoId());
                BeanUtil.copyProperties(putawayInfo, returnsInfo);
                returnsInfo.setId(null);
                returnsInfo.setReturnsId(materialReturns.getId());
                // 更新物料库存
                materialService.modifyMaterialInventory(item.getMaterialId(), item.getReturnsNumber(), false);
                return returnsInfo;
            }).collect(Collectors.toList());
            materialReturnsInfoMapper.insertBatch(collect);
            // 还原入库明细状态
            LambdaUpdateWrapper<ErpMaterialPutawayInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(ErpMaterialPutawayInfo::getPutawayId, bo.getPutawayId());
            updateWrapper.set(ErpMaterialPutawayInfo::getIsReturns, IsEnableStatus.NO.getCode());
            materialPutawayInfoMapper.update(updateWrapper);

            // 处理入库明细状态
            List<ErpMaterialPutawayInfo> putawayInfoList = infoBoList.stream().map(item -> {
                ErpMaterialPutawayInfo putawayInfo = new ErpMaterialPutawayInfo();
                putawayInfo.setId(item.getId());
                putawayInfo.setIsReturns(IsEnableStatus.YES.getCode());
                return putawayInfo;
            }).collect(Collectors.toList());
            materialPutawayInfoMapper.updateBatchById(putawayInfoList);
        }
        return flag;
    }

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

    /**
     * 批量删除物料退货
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 根据ID查询物料退货明细列表
        LambdaQueryWrapper<ErpMaterialReturnsInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ErpMaterialReturnsInfo::getReturnsId, ids);
        List<ErpMaterialReturnsInfoVo> returnsInfoVoList = materialReturnsInfoMapper.selectVoList(queryWrapper);
        // 处理入库明细状态(取消入库明细是否存在退货标记)
        List<ErpMaterialPutawayInfo> putawayInfoList = returnsInfoVoList.stream().map(item -> {
            ErpMaterialPutawayInfo putawayInfo = new ErpMaterialPutawayInfo();
            putawayInfo.setId(item.getId());
            putawayInfo.setIsReturns(IsEnableStatus.NO.getCode());
            // 更新物料库存
            materialService.modifyMaterialInventory(item.getMaterialId(), item.getReturnsNumber(), true);
            return putawayInfo;
        }).collect(Collectors.toList());
        // 更新入库明细列表
        materialPutawayInfoMapper.updateBatchById(putawayInfoList);
        // 删除退货明细
        materialReturnsInfoMapper.delete(queryWrapper);
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
