package org.dromara.materials.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.materials.domain.MatMaterials;
import org.dromara.materials.domain.MatMaterialsInventory;
import org.dromara.materials.domain.enums.MatMaterialsInventoryOutPutEnum;
import org.dromara.materials.domain.dto.materialsinventory.MatMaterialsInventoryCreateReq;
import org.dromara.materials.domain.dto.materialsinventory.MatMaterialsInventoryQueryReq;
import org.dromara.materials.domain.dto.materialsinventory.MatMaterialsInventoryUpdateReq;
import org.dromara.materials.domain.vo.materialsinventory.MatMaterialsInventoryVo;
import org.dromara.materials.mapper.MatMaterialsInventoryMapper;
import org.dromara.materials.service.IMatMaterialsInventoryService;
import org.dromara.materials.service.IMatMaterialsService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 材料出/入库Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@Service
public class MatMaterialsInventoryServiceImpl extends ServiceImpl<MatMaterialsInventoryMapper, MatMaterialsInventory>
    implements IMatMaterialsInventoryService {

    @Resource
    private IMatMaterialsService materialsService;

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询材料出/入库
     *
     * @param id 主键
     * @return 材料出/入库
     */
    @Override
    public MatMaterialsInventoryVo queryById(Long id) {
        MatMaterialsInventory materialsInventory = this.getById(id);
        if (materialsInventory == null) {
            throw new ServiceException("材料出/入库信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(materialsInventory);
    }

    /**
     * 分页查询材料出/入库列表
     *
     * @param req 查询条件
     * @return 材料出/入库分页列表
     */
    @Override
    public TableDataInfo<MatMaterialsInventoryVo> queryPageList(MatMaterialsInventoryQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<MatMaterialsInventory> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的材料出/入库列表
     *
     * @param req 查询条件
     * @return 材料出/入库列表
     */
    @Override
    public List<MatMaterialsInventoryVo> queryList(MatMaterialsInventoryQueryReq req) {
        LambdaQueryWrapper<MatMaterialsInventory> lqw = this.buildQueryWrapper(req);
        List<MatMaterialsInventory> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增材料出/入库
     *
     * @param req 材料出/入库
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(MatMaterialsInventoryCreateReq req) {
        // 将实体类和 DTO 进行转换
        MatMaterialsInventory materialsInventory = new MatMaterialsInventory();
        BeanUtils.copyProperties(req, materialsInventory);
        // 数据校验
        validEntityBeforeSave(materialsInventory, true);
        // 获取最后一次库存数量
        MatMaterialsInventory lastMaterialsInventory = this.getOne(Wrappers.<MatMaterialsInventory>lambdaQuery()
            .eq(MatMaterialsInventory::getMaterialsId, req.getMaterialsId())
            .eq(MatMaterialsInventory::getProjectId, req.getProjectId())
            .orderByDesc(MatMaterialsInventory::getCreateTime)
            .last("limit 1"));
        if (lastMaterialsInventory != null) {
            if (MatMaterialsInventoryOutPutEnum.OUT.getValue().equals(req.getOutPut())) {
                long left = lastMaterialsInventory.getResidue() - req.getNumber();
                if (left < 0) {
                    throw new ServiceException("库存不足", HttpStatus.BAD_REQUEST);
                }
                materialsInventory.setResidue(left);
            } else {
                materialsInventory.setResidue(lastMaterialsInventory.getResidue() + req.getNumber());
            }
        } else {
            if (MatMaterialsInventoryOutPutEnum.OUT.getValue().equals(req.getOutPut())) {
                throw new ServiceException("库存不足", HttpStatus.BAD_REQUEST);
            } else {
                materialsInventory.setResidue(req.getNumber());
            }
        }
        // 操作数据库
        boolean save = this.save(materialsInventory);
        if (!save) {
            throw new ServiceException("新增材料出/入库失败，数据库异常", HttpStatus.ERROR);
        }
        return materialsInventory.getId();
    }

    /**
     * 修改材料出/入库
     *
     * @param req 材料出/入库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MatMaterialsInventoryUpdateReq req) {
        // 将实体类和 DTO 进行转换
        MatMaterialsInventory materialsInventory = new MatMaterialsInventory();
        BeanUtils.copyProperties(req, materialsInventory);
        // 数据校验
        validEntityBeforeSave(materialsInventory, false);
        // 判断是否存在
        MatMaterialsInventory oldBusMaterialsInventory = this.getById(materialsInventory.getId());
        if (oldBusMaterialsInventory == null) {
            throw new ServiceException("修改材料出/入库失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(materialsInventory);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MatMaterialsInventory entity, Boolean create) {
        Long materialsId = entity.getMaterialsId();
        Long projectId = entity.getProjectId();
        String outPut = entity.getOutPut();
        Long number = entity.getNumber();
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (create) {
            if (number == null) {
                throw new ServiceException("出/入库数量不能为空", HttpStatus.BAD_REQUEST);
            }
            if (materialsId == null) {
                throw new ServiceException("材料信息 id 不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isEmpty(outPut)) {
                throw new ServiceException("出入库状态不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (materialsService.getById(materialsId) == null) {
            throw new ServiceException("对应材料信息不存在", HttpStatus.BAD_REQUEST);
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除材料出/入库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        List<MatMaterialsInventory> materialsInventoryList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = materialsInventoryList.stream().map(MatMaterialsInventory::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
        }
        // 判断对应数据是否都存在
        if (materialsInventoryList.size() != ids.size()) {
            throw new ServiceException("删除材料出/入库失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取材料出/入库视图对象
     *
     * @param materialsInventory 材料出/入库对象
     * @return 材料出/入库视图对象
     */
    @Override
    public MatMaterialsInventoryVo getVo(MatMaterialsInventory materialsInventory) {
        // 对象转封装类
        MatMaterialsInventoryVo materialsInventoryVo = new MatMaterialsInventoryVo();
        if (materialsInventory == null) {
            return materialsInventoryVo;
        }
        BeanUtils.copyProperties(materialsInventory, materialsInventoryVo);
        // 关联查询材料信息
        Long materialsId = materialsInventory.getMaterialsId();
        if (materialsId != null) {
            materialsInventoryVo.setMaterialsName(materialsService.queryById(materialsId).getMaterialsName());
        }
        return materialsInventoryVo;
    }

    /**
     * 构建查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<MatMaterialsInventory> buildQueryWrapper(MatMaterialsInventoryQueryReq req) {
        LambdaQueryWrapper<MatMaterialsInventory> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        Long materialsId = req.getMaterialsId();
        String materialsName = req.getMaterialsName();
        Long projectId = req.getProjectId();
        String outPut = req.getOutPut();
        Long number = req.getNumber();
        Date outPutTime = req.getOutPutTime();
        Long residue = req.getResidue();
        String operator = req.getOperator();
        String disposition = req.getDisposition();
        String recipient = req.getRecipient();
        String shipper = req.getShipper();
        String remark = req.getRemark();
        // 联表查询
        if (StringUtils.isNotBlank(materialsName)) {
            LambdaQueryWrapper<MatMaterials> materialsQueryWrapper = Wrappers.lambdaQuery(MatMaterials.class)
                .select(MatMaterials::getId)
                .like(MatMaterials::getMaterialsName, materialsName);
            List<Long> materialsIdList = materialsService.listObjs(materialsQueryWrapper, obj -> (Long) obj);
            lqw.in(MatMaterialsInventory::getMaterialsId, materialsIdList);
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(operator), MatMaterialsInventory::getOperator, operator);
        lqw.like(StringUtils.isNotBlank(remark), MatMaterialsInventory::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(disposition), MatMaterialsInventory::getDisposition, disposition);
        lqw.like(StringUtils.isNotBlank(recipient), MatMaterialsInventory::getRecipient, recipient);
        lqw.like(StringUtils.isNotBlank(shipper), MatMaterialsInventory::getShipper, shipper);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), MatMaterialsInventory::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), MatMaterialsInventory::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(materialsId), MatMaterialsInventory::getMaterialsId, materialsId);
        lqw.eq(ObjectUtils.isNotEmpty(number), MatMaterialsInventory::getNumber, number);
        lqw.eq(ObjectUtils.isNotEmpty(outPutTime), MatMaterialsInventory::getOutPutTime, outPutTime);
        lqw.eq(ObjectUtils.isNotEmpty(residue), MatMaterialsInventory::getResidue, residue);
        lqw.eq(ObjectUtils.isNotEmpty(outPut), MatMaterialsInventory::getOutPut, outPut);
        // 排序
        lqw.orderByDesc(MatMaterialsInventory::getCreateTime);
        return lqw;
    }

    /**
     * 获取材料出/入库分页对象视图
     *
     * @param materialsInventoryPage 材料出/入库分页对象
     * @return 材料出/入库分页对象视图
     */
    @Override
    public Page<MatMaterialsInventoryVo> getVoPage(Page<MatMaterialsInventory> materialsInventoryPage) {
        List<MatMaterialsInventory> materialsInventoryList = materialsInventoryPage.getRecords();
        Page<MatMaterialsInventoryVo> materialsInventoryVoPage = new Page<>(
            materialsInventoryPage.getCurrent(),
            materialsInventoryPage.getSize(),
            materialsInventoryPage.getTotal());
        if (CollUtil.isEmpty(materialsInventoryList)) {
            return materialsInventoryVoPage;
        }
        // 获取材料id列表
        Set<Long> materialsIdList = materialsInventoryList.stream().map(MatMaterialsInventory::getMaterialsId).collect(Collectors.toSet());
        Map<Long, List<MatMaterials>> materialsIdBusMaterialsMap = materialsService.listByIds(materialsIdList).stream()
            .collect(Collectors.groupingBy(MatMaterials::getId));
        // 对象列表 => 封装对象列表
        List<MatMaterialsInventoryVo> materialsInventoryVoList = materialsInventoryList.stream().map(materialsInventory -> {
            MatMaterialsInventoryVo materialsInventoryVo = new MatMaterialsInventoryVo();
            BeanUtils.copyProperties(materialsInventory, materialsInventoryVo);
            // 关联查询材料信息
            Long materialsId = materialsInventory.getMaterialsId();
            String materialsName = null;
            if (materialsIdBusMaterialsMap.containsKey(materialsId)) {
                materialsName = materialsIdBusMaterialsMap.get(materialsId).get(0).getMaterialsName();
            }
            materialsInventoryVo.setMaterialsName(materialsName);
            return materialsInventoryVo;
        }).toList();
        materialsInventoryVoPage.setRecords(materialsInventoryVoList);
        return materialsInventoryVoPage;
    }
}
