package org.dromara.materials.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.CommonConstant;
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.core.utils.sql.SqlUtil;
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 Page<BusMaterialsInventoryVo> queryPageList(MaterialsInventoryQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusMaterialsInventory> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getVoPage(result);
    }

    /**
     * 查询符合条件的材料出/入库列表
     *
     * @param req 查询条件
     * @return 材料出/入库列表
     */
    @Override
    public List<BusMaterialsInventoryVo> queryList(MaterialsInventoryQueryReq req) {
        QueryWrapper<BusMaterialsInventory> queryWrapper = this.getQueryWrapper(req);
        List<BusMaterialsInventory> list = this.list(queryWrapper);
        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) {
        // TODO 做一些数据校验,如唯一约束
        Long materialsId = entity.getMaterialsId();
        Long projectId = entity.getProjectId();
        Long 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 (outPut == null) {
            throw new ServiceException("出入库状态不能为空", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除材料出/入库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        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 QueryWrapper<BusMaterialsInventory> getQueryWrapper(MaterialsInventoryQueryReq req) {
        QueryWrapper<BusMaterialsInventory> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        Long materialsId = req.getMaterialsId();
        Long projectId = req.getProjectId();
        Long 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();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(operator), "operator", operator);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        queryWrapper.like(StringUtils.isNotBlank(disposition), "disposition", disposition);
        queryWrapper.like(StringUtils.isNotBlank(recipient), recipient, recipient);
        queryWrapper.like(StringUtils.isNotBlank(shipper), shipper, shipper);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(materialsId), "materials_id", materialsId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(number), "number", number);
        queryWrapper.eq(ObjectUtils.isNotEmpty(outPutTime), "out_put_time", outPutTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(residue), "residue", residue);
        queryWrapper.eq(ObjectUtils.isNotEmpty(outPut), "out_put", outPut);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取材料出/入库分页对象视图
     *
     * @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;
    }
}
