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.IErpMaterialInventoryRecordService;
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.domain.entity.SysDept;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.enums.InventoryType;
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 com.maintain.system.mapper.SysDeptMapper;
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;
    private final ErpMaterialInventoryRecordMapper materialInventoryRecordMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询物料入库
     */
    @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) {
        List<SysDept> sysDeptList = deptMapper.selectChildrenDeptById(LoginHelper.getDeptId(), null);
        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.getPutawayCode()), ErpMaterialPutaway::getPutawayCode, bo.getPutawayCode());
        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.eq(bo.getState() != null, ErpMaterialPutaway::getState, bo.getState());
        lqw.in(!sysDeptList.isEmpty(), ErpMaterialPutaway::getCreateDeptId, sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        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.setPutawayCode(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.setMaterialId(material.getId());
                putawayInfo.setPutawayId(add.getId());
                putawayInfo.setState(bo.getState());
                putawayInfo.setVendorId(item.getVendorId());
                putawayInfo.setVendorName(item.getVendorName());
                return putawayInfo;
            }).collect(Collectors.toList());
            putawayInfoMapper.insertBatch(collect);

            /* 创建物料库存记录表 */
            if (bo.getState().equals(PickingState.TWO.getCode())) {
                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.getPutawayNumber());
                    record.setPrice(item.getPutawayPrice());
                    record.setMoney(item.getPutawayMoney());
                    record.setType(InventoryType.putaway.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        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);
            List<ErpMaterialPutawayInfo> putawayInfoList = putawayInfoMapper.selectList(queryWrapper);
            if (!putawayInfoList.isEmpty()) {
                List<ErpMaterialInventoryRecord> inventoryRecordList = putawayInfoList.stream().map(item -> {
                    ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                    record.setInfoId(item.getId());
                    record.setMaterialId(item.getMaterialId());
                    // 查出入库单
                    ErpMaterialPutaway materialPutaway = baseMapper.selectById(item.getPutawayId());
                    record.setWarehouseId(materialPutaway.getWarehouseId());
                    // 查出仓库
                    ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(materialPutaway.getWarehouseId());
                    if (null != warehouseVo) {
                        record.setDeptId(warehouseVo.getDeptId());
                    }
                    record.setVendorId(item.getVendorId());
                    record.setNumber(item.getPutawayNumber());
                    record.setPrice(item.getPutawayPrice());
                    record.setMoney(item.getPutawayMoney());
                    record.setType(InventoryType.putaway.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        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);
            if (!putawayInfoVoList.isEmpty() && update.getState().equals(PickingState.TWO.getCode())) {
                LambdaQueryWrapper<ErpMaterialInventoryRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.in(ErpMaterialInventoryRecord::getInfoId, putawayInfoVoList.stream().map(ErpMaterialPutawayInfoVo::getId).collect(Collectors.toList()));
                materialInventoryRecordMapper.delete(lambdaQueryWrapper);
            }
            putawayInfoMapper.delete(queryWrapper);
            // 绑定新的进货明细
            List<ErpMaterialPutawayInfo> collect = bo.getPutawayInfoList().stream().map(item -> {
                ErpMaterialPutawayInfo putawayInfo = BeanUtil.toBean(item, ErpMaterialPutawayInfo.class);
                ErpMaterial material = materialMapper.selectById(item.getMaterialId());
                BeanUtil.copyProperties(material, putawayInfo);
                putawayInfo.setId(null);
                putawayInfo.setVendorId(item.getVendorId());
                putawayInfo.setVendorName(item.getVendorName());
                putawayInfo.setMaterialId(material.getId());
                putawayInfo.setPutawayId(update.getId());
                putawayInfo.setState(bo.getState());
                return putawayInfo;
            }).collect(Collectors.toList());
            putawayInfoMapper.insertBatch(collect);

            /* 创建物料库存记录表 */
            if (update.getState().equals(PickingState.TWO.getCode())) {
                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.setNumber(item.getPutawayNumber());
                    record.setPrice(item.getPutawayPrice());
                    record.setMoney(item.getPutawayMoney());
                    record.setType(InventoryType.putaway.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        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);
        // 删除物料库存记录
        LambdaQueryWrapper<ErpMaterialInventoryRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.in(ErpMaterialInventoryRecord::getInfoId, putawayInfoVoList.stream().map(ErpMaterialPutawayInfoVo::getId).collect(Collectors.toList()));
        materialInventoryRecordMapper.delete(lambdaQueryWrapper);
        // 删除入库明细
        putawayInfoMapper.delete(queryWrapper);
        // 删除入库单
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
