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.conditions.query.QueryWrapper;
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.BusMaterials;
import org.dromara.materials.domain.BusMaterialsInventory;
import org.dromara.materials.domain.req.materialsinventory.MaterialsInventoryCreateReq;
import org.dromara.materials.domain.req.materialsinventory.MaterialsInventoryQueryReq;
import org.dromara.materials.domain.req.materialsinventory.MaterialsInventoryUpdateReq;
import org.dromara.materials.domain.vo.BusMaterialsInventoryVo;
import org.dromara.materials.mapper.BusMaterialsInventoryMapper;
import org.dromara.materials.service.IBusMaterialsInventoryService;
import org.dromara.materials.service.IBusMaterialsService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 材料出/入库Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@Service
public class BusMaterialsInventoryServiceImpl extends ServiceImpl<BusMaterialsInventoryMapper, BusMaterialsInventory>
    implements IBusMaterialsInventoryService {

    @Resource
    private BusMaterialsInventoryMapper baseMapper;

    @Resource
    private IBusMaterialsService materialsService;

    @Resource
    private IBusProjectService projectService;

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

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

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

    /**
     * 新增材料出/入库
     *
     * @param req 材料出/入库
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(MaterialsInventoryCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusMaterialsInventory materialsInventory = new BusMaterialsInventory();
        BeanUtils.copyProperties(req, materialsInventory);
        // 数据校验
        validEntityBeforeSave(materialsInventory);
        // 操作数据库
        boolean save = this.save(materialsInventory);
        if (!save) {
            throw new ServiceException("新增材料出/入库失败，数据库异常", HttpStatus.ERROR);
        }
        return materialsInventory.getId();
    }

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

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

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

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

    /**
     * 构建查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusMaterialsInventory> buildQuery(MaterialsInventoryQueryReq req) {
        LambdaQueryWrapper<BusMaterialsInventory> 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)) {
            QueryWrapper<BusMaterials> materialsQueryWrapper = new QueryWrapper<>();
            materialsQueryWrapper.select("id");
            materialsQueryWrapper.like("materials_name", materialsName);
            List<Long> materialsIdList = materialsService.listObjs(materialsQueryWrapper, obj -> (Long) obj);
            lqw.in(BusMaterialsInventory::getMaterialsId, materialsIdList);
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(operator), BusMaterialsInventory::getOperator, operator);
        lqw.like(StringUtils.isNotBlank(remark), BusMaterialsInventory::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(disposition), BusMaterialsInventory::getDisposition, disposition);
        lqw.like(StringUtils.isNotBlank(recipient), BusMaterialsInventory::getRecipient, recipient);
        lqw.like(StringUtils.isNotBlank(shipper), BusMaterialsInventory::getShipper, shipper);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusMaterialsInventory::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusMaterialsInventory::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(materialsId), BusMaterialsInventory::getMaterialsId, materialsId);
        lqw.eq(ObjectUtils.isNotEmpty(number), BusMaterialsInventory::getNumber, number);
        lqw.eq(ObjectUtils.isNotEmpty(outPutTime), BusMaterialsInventory::getOutPutTime, outPutTime);
        lqw.eq(ObjectUtils.isNotEmpty(residue), BusMaterialsInventory::getResidue, residue);
        lqw.eq(ObjectUtils.isNotEmpty(outPut), BusMaterialsInventory::getOutPut, outPut);
        return lqw;
    }

    /**
     * 获取材料出/入库分页对象视图
     *
     * @param materialsInventoryPage 材料出/入库分页对象
     * @return 材料出/入库分页对象视图
     */
    @Override
    public Page<BusMaterialsInventoryVo> getVoPage(Page<BusMaterialsInventory> materialsInventoryPage) {
        List<BusMaterialsInventory> materialsInventoryList = materialsInventoryPage.getRecords();
        Page<BusMaterialsInventoryVo> materialsInventoryVoPage = new Page<>(
            materialsInventoryPage.getCurrent(),
            materialsInventoryPage.getSize(),
            materialsInventoryPage.getTotal());
        if (CollUtil.isEmpty(materialsInventoryList)) {
            return materialsInventoryVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusMaterialsInventoryVo> materialsInventoryVoList = materialsInventoryList.stream().map(this::getVo).toList();
        materialsInventoryVoPage.setRecords(materialsInventoryVoList);
        return materialsInventoryVoPage;
    }
}
