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.ErpMaterialPicking;
import com.maintain.business.domain.ErpMaterialPickingInfo;
import com.maintain.business.domain.ErpSettlementMaterialInfo;
import com.maintain.business.domain.bo.ErpSettlementMaterialInfoBo;
import com.maintain.business.domain.vo.*;
import com.maintain.business.mapper.*;
import com.maintain.common.enums.PickingSettlementState;
import com.maintain.common.enums.SettlementState;
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.ErpSettlementMaterialBo;
import com.maintain.business.domain.ErpSettlementMaterial;
import com.maintain.business.service.IErpSettlementMaterialService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 结算物料Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-16
 */
@RequiredArgsConstructor
@Service
public class ErpSettlementMaterialServiceImpl implements IErpSettlementMaterialService {

    private final ErpSettlementMaterialMapper baseMapper;
    private final ErpSettlementMaterialInfoMapper settlementMaterialInfoMapper;
    private final ErpMaterialPickingMapper pickingMapper;
    private final ErpMaterialPickingInfoMapper pickingInfoMapper;
    private final ErpMaterialVendorMapper vendorMapper;

    /**
     * 查询结算物料
     */
    @Override
    public ErpSettlementMaterialVo queryById(Long id){
        ErpSettlementMaterialVo settlementMaterialVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<ErpSettlementMaterialInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpSettlementMaterialInfo::getSettlementId, id);
        List<ErpSettlementMaterialInfo> materialInfoList = settlementMaterialInfoMapper.selectList(lqw);

        LambdaQueryWrapper<ErpMaterialPicking> pickingLambdaQueryWrapper = Wrappers.lambdaQuery();
        pickingLambdaQueryWrapper.in(ErpMaterialPicking::getId, materialInfoList.stream().map(ErpSettlementMaterialInfo::getPickingId).collect(Collectors.toSet()));
        List<ErpMaterialPickingVo> pickingList = pickingMapper.selectVoList(pickingLambdaQueryWrapper);
        for (ErpMaterialPickingVo pickingVo : pickingList) {
            LambdaQueryWrapper<ErpSettlementMaterialInfo> pickingInfoLambdaQueryWrapper = Wrappers.lambdaQuery();
            pickingInfoLambdaQueryWrapper.eq(ErpSettlementMaterialInfo::getPickingId, pickingVo.getId());
            List<ErpSettlementMaterialInfoVo> infoVoList = settlementMaterialInfoMapper.selectVoList(pickingInfoLambdaQueryWrapper);
            pickingVo.setSettlementMaterialInfoList(infoVoList);
        }
        settlementMaterialVo.setPickingList(pickingList);
        return settlementMaterialVo;
    }

    /**
     * 查询结算物料列表
     */
    @Override
    public TableDataInfo<ErpSettlementMaterialVo> queryPageList(ErpSettlementMaterialBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSettlementMaterial> lqw = buildQueryWrapper(bo);
        Page<ErpSettlementMaterialVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询结算物料列表
     */
    @Override
    public List<ErpSettlementMaterialVo> queryList(ErpSettlementMaterialBo bo) {
        LambdaQueryWrapper<ErpSettlementMaterial> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSettlementMaterial> buildQueryWrapper(ErpSettlementMaterialBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSettlementMaterial> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getSettlementNumber()), ErpSettlementMaterial::getSettlementNumber, bo.getSettlementNumber());
        lqw.like(StringUtils.isNotBlank(bo.getSettlementName()), ErpSettlementMaterial::getSettlementName, bo.getSettlementName());
        lqw.eq(bo.getSettlementTime() != null, ErpSettlementMaterial::getSettlementTime, bo.getSettlementTime());
        lqw.like(StringUtils.isNotBlank(bo.getVendorName()), ErpSettlementMaterial::getVendorName, bo.getVendorName());
        lqw.eq(bo.getState() != null, ErpSettlementMaterial::getState, bo.getState());
        lqw.orderByDesc(ErpSettlementMaterial::getCreateTime);
        return lqw;
    }

    /**
     * 新增结算物料
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpSettlementMaterialBo bo) {
        ErpSettlementMaterial add = BeanUtil.toBean(bo, ErpSettlementMaterial.class);
        validEntityBeforeSave(add);
        add.setSettlementNumber(RedisUtils.generateNextNumber("CKJS"));
        add.setCreateDeptId(LoginHelper.getDeptId());
        ErpMaterialVendorVo vendorVo = vendorMapper.selectVoById(bo.getVendorId());
        add.setVendorName(vendorVo.getVendorName());
        add.setState(2);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            // 创建结算明细
            List<ErpSettlementMaterialInfo> collect = bo.getInfoList().stream().map(item -> {
                ErpSettlementMaterialInfo materialInfo = BeanUtil.toBean(item, ErpSettlementMaterialInfo.class);
                materialInfo.setId(null);
                materialInfo.setSettlementId(add.getId());
                return materialInfo;
            }).collect(Collectors.toList());
            settlementMaterialInfoMapper.insertBatch(collect);
            // 更改出库单结算状态
            Set<Long> pickingIdSet = bo.getInfoList().stream().map(ErpSettlementMaterialInfoBo::getPickingId).collect(Collectors.toSet());
            LambdaUpdateWrapper<ErpMaterialPicking> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.in(ErpMaterialPicking::getId, pickingIdSet).set(ErpMaterialPicking::getSettlementState, PickingSettlementState.TWO.getCode());
            pickingMapper.update(updateWrapper);
        }
        return flag;
    }

    /**
     * 修改结算物料
     */
    @Override
    public Boolean updateByBo(ErpSettlementMaterialBo bo) {
        ErpSettlementMaterial update = BeanUtil.toBean(bo, ErpSettlementMaterial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 批量删除结算物料
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
