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.ErpMaterialInventoryRecord;
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.domain.vo.ErpWarehouseVo;
import com.maintain.business.mapper.*;
import com.maintain.business.service.IErpMaterialService;
import com.maintain.common.core.domain.BaseEntity;
import com.maintain.common.core.domain.entity.SysDept;
import com.maintain.common.enums.InventoryType;
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 com.maintain.system.mapper.SysDeptMapper;
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.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;
    private final ErpMaterialInventoryRecordMapper erpMaterialInventoryRecordMapper;
    private final ErpWarehouseMapper warehouseMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询物料退货
     */
    @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) {
        List<SysDept> sysDeptList = deptMapper.selectChildrenDeptById(LoginHelper.getDeptId(), null);
        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.in(!sysDeptList.isEmpty(), ErpMaterialReturns::getCreateDeptId, sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        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());
                returnsInfo.setCreateTime(null);
                returnsInfo.setCreateBy(null);
                returnsInfo.setUpdateTime(null);
                returnsInfo.setUpdateBy(null);
                return returnsInfo;
            }).collect(Collectors.toList());
            materialReturnsInfoMapper.insertBatch(collect);
            // 创建物料库存记录
            ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(materialReturns.getWarehouseId());
            List<ErpMaterialInventoryRecord> inventoryRecordList = collect.stream().map(item -> {
                ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                record.setInfoId(item.getId());
                record.setMaterialId(item.getMaterialId());
                record.setWarehouseId(warehouseVo.getId());
                record.setDeptId(warehouseVo.getDeptId());
                record.setVendorId(item.getVendorId());
                record.setNumber(item.getReturnsNumber());
                record.setPrice(item.getReturnsPrice());
                record.setMoney(item.getReturnsMoney());
                record.setType(InventoryType.returns.getCode());
                return record;
            }).collect(Collectors.toList());
            erpMaterialInventoryRecordMapper.insertBatch(inventoryRecordList);

            // 处理入库明细状态(记录已退数量)
            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);
            // 删除物料库存记录数据
            if (!returnsInfoVoList.isEmpty()) {
                LambdaQueryWrapper<ErpMaterialInventoryRecord> lambdaQuery = Wrappers.lambdaQuery();
                lambdaQuery.in(ErpMaterialInventoryRecord::getInfoId, returnsInfoVoList.stream().map(ErpMaterialReturnsInfoVo::getId).collect(Collectors.toList()));
                erpMaterialInventoryRecordMapper.delete(lambdaQuery);
            }
            // 删除原有退货明细
            materialReturnsInfoMapper.delete(queryWrapper);
            // 绑定新的退货明细
            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());
                returnsInfo.setCreateTime(null);
                returnsInfo.setCreateBy(null);
                returnsInfo.setUpdateTime(null);
                returnsInfo.setUpdateBy(null);
                return returnsInfo;
            }).collect(Collectors.toList());
            materialReturnsInfoMapper.insertBatch(collect);
            // 创建物料库存记录
            ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(materialReturns.getWarehouseId());
            List<ErpMaterialInventoryRecord> inventoryRecordList = collect.stream().map(item -> {
                ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                record.setInfoId(item.getId());
                record.setMaterialId(item.getMaterialId());
                record.setWarehouseId(warehouseVo.getId());
                record.setDeptId(warehouseVo.getDeptId());
                record.setVendorId(item.getVendorId());
                record.setNumber(item.getReturnsNumber());
                record.setPrice(item.getReturnsPrice());
                record.setMoney(item.getReturnsMoney());
                record.setType(InventoryType.returns.getCode());
                return record;
            }).collect(Collectors.toList());
            erpMaterialInventoryRecordMapper.insertBatch(inventoryRecordList);
            // 还原入库明细状态（是否存在退货改为否）
            LambdaUpdateWrapper<ErpMaterialPutawayInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(ErpMaterialPutawayInfo::getPutawayId, bo.getPutawayId()).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);
        // 处理入库明细状态(取消入库明细是否存在退货标记,回退已退数量)
        for (ErpMaterialReturnsInfoVo returnsInfoVo : returnsInfoVoList) {
            ErpMaterialPutawayInfo putawayInfo = materialPutawayInfoMapper.selectById(returnsInfoVo.getPutawayInfoId());
            putawayInfo.setIsReturns(IsEnableStatus.NO.getCode());
            putawayInfo.setReturnedNumber(putawayInfo.getReturnedNumber().subtract(returnsInfoVo.getReturnsNumber()));
            materialPutawayInfoMapper.updateById(putawayInfo);
        }
        // 删除物料库存记录
        LambdaQueryWrapper<ErpMaterialInventoryRecord> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.in(ErpMaterialInventoryRecord::getInfoId, returnsInfoVoList.stream().map(ErpMaterialReturnsInfoVo::getId).collect(Collectors.toList()));
        erpMaterialInventoryRecordMapper.delete(lambdaQuery);
        // 删除退货明细
        materialReturnsInfoMapper.delete(queryWrapper);
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
