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 lombok.RequiredArgsConstructor;
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.BusMaterials;
import org.dromara.materials.domain.req.materials.MaterialsCreateReq;
import org.dromara.materials.domain.req.materials.MaterialsQueryReq;
import org.dromara.materials.domain.req.materials.MaterialsUpdateReq;
import org.dromara.materials.domain.vo.BusMaterialsVo;
import org.dromara.materials.mapper.BusMaterialsMapper;
import org.dromara.materials.service.IBusCompanyService;
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.List;

/**
 * 材料名称Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@RequiredArgsConstructor
@Service
public class BusMaterialsServiceImpl extends ServiceImpl<BusMaterialsMapper, BusMaterials>
    implements IBusMaterialsService {

    @Resource
    private BusMaterialsMapper baseMapper;

    @Resource
    private IBusCompanyService companyService;

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询材料名称
     *
     * @param id 主键
     * @return 材料名称
     */
    @Override
    public BusMaterialsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询材料名称列表
     *
     * @param req 查询条件
     * @return 材料名称分页列表
     */
    @Override
    public Page<BusMaterialsVo> queryPageList(MaterialsQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusMaterials> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getMaterialsVoPage(result);
    }

    /**
     * 查询符合条件的材料名称列表
     *
     * @param req 查询条件
     * @return 材料名称列表
     */
    @Override
    public List<BusMaterialsVo> queryList(MaterialsQueryReq req) {
        QueryWrapper<BusMaterials> queryWrapper = this.getQueryWrapper(req);
        return baseMapper.selectVoList(queryWrapper);
    }

    /**
     * 新增材料名称
     *
     * @param req 材料名称
     * @return 新增材料信息id
     */
    @Override
    public Long insertByBo(MaterialsCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusMaterials materials = new BusMaterials();
        BeanUtils.copyProperties(req, materials);
        // 数据校验
        validEntityBeforeSave(materials);
        // 写入数据库
        boolean save = this.save(materials);
        if (!save) {
            throw new ServiceException("新增材料信息失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return materials.getId();
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMaterials entity) {
        // TODO 做一些数据校验,如唯一约束
        String materialsName = entity.getMaterialsName();
        Long companyId = entity.getCompanyId();
        Long projectId = entity.getProjectId();
        if (StringUtils.isEmpty(materialsName)) {
            throw new ServiceException("请填写材料名称", HttpStatus.BAD_REQUEST);
        }
        if (companyId == null) {
            throw new ServiceException("请填写公司ID", HttpStatus.BAD_REQUEST);
        }
        if (companyService.getById(companyId) == 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);
        }
    }

    /**
     * 校验并批量删除材料名称信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取材料视图
     *
     * @param Materials 材料
     * @return 材料视图
     */
    @Override
    public BusMaterialsVo getBusMaterialsVo(BusMaterials Materials) {
        // 对象转封装类
        BusMaterialsVo materialsVo = new BusMaterialsVo();
        if (Materials == null) {
            return materialsVo;
        }
        BeanUtils.copyProperties(Materials, materialsVo);
        // 关联查询项目信息
        Long companyId = Materials.getCompanyId();
        if (companyId != null) {
            materialsVo.setCompanyVo(companyService.queryById(companyId));
        }
        return materialsVo;
    }

    /**
     * 构建查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public QueryWrapper<BusMaterials> getQueryWrapper(MaterialsQueryReq req) {
        QueryWrapper<BusMaterials> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        String materialsName = req.getMaterialsName();
        Long companyId = req.getCompanyId();
        Long projectId = req.getProjectId();
        String usePart = req.getUsePart();
        String weightId = req.getWeightId();
        String remark = req.getRemark();
        String quantityCount = req.getQuantityCount();
        Long status = req.getStatus();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(materialsName), "materials_name", materialsName);
        queryWrapper.like(StringUtils.isNotBlank(usePart), "use_part", usePart);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        queryWrapper.like(StringUtils.isNotBlank(weightId), "weight_id", weightId);
        queryWrapper.like(StringUtils.isNotBlank(quantityCount), "quantity_count", quantityCount);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(companyId), "company_id", companyId);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取材料分页对象视图
     *
     * @param materialsPage 材料分页对象
     * @return 材料分页对象视图
     */
    @Override
    public Page<BusMaterialsVo> getMaterialsVoPage(Page<BusMaterials> materialsPage) {
        // 获取材料数据
        List<BusMaterials> materialsList = materialsPage.getRecords();
        // 添加分页信息
        Page<BusMaterialsVo> materialsVoPage = new Page<>(materialsPage.getCurrent(), materialsPage.getSize(), materialsPage.getTotal());
        if (CollUtil.isEmpty(materialsList)) {
            return materialsVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusMaterialsVo> materialsVoList = materialsList.stream().map(this::getBusMaterialsVo).toList();
        materialsVoPage.setRecords(materialsVoList);
        return materialsVoPage;
    }
}
