package org.dromara.machinery.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.machinery.domain.BusMachinery;
import org.dromara.machinery.domain.req.machinery.MachineryCreateReq;
import org.dromara.machinery.domain.req.machinery.MachineryQueryReq;
import org.dromara.machinery.domain.req.machinery.MachineryUpdateReq;
import org.dromara.machinery.domain.vo.BusMachineryVo;
import org.dromara.machinery.mapper.BusMachineryMapper;
import org.dromara.machinery.service.IBusMachineryService;
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.Collection;
import java.util.List;

/**
 * 机械Service业务层处理
 *
 * @author lcj
 * @date 2025-03-07
 */
@Service
public class BusMachineryServiceImpl extends ServiceImpl<BusMachineryMapper, BusMachinery>
    implements IBusMachineryService {

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询机械
     *
     * @param id 主键
     * @return 机械
     */
    @Override
    public BusMachineryVo queryById(Long id) {
        BusMachinery machinery = this.getById(id);
        if (machinery == null) {
            throw new ServiceException("机械信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(machinery);
    }

    /**
     * 分页查询机械列表
     *
     * @param req 查询条件
     * @return 机械分页列表
     */
    @Override
    public Page<BusMachineryVo> queryPageList(MachineryQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusMachinery> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getVoPage(result);
    }

    /**
     * 查询符合条件的机械列表
     *
     * @param req 查询条件
     * @return 机械列表
     */
    @Override
    public List<BusMachineryVo> queryList(MachineryQueryReq req) {
        QueryWrapper<BusMachinery> queryWrapper = this.getQueryWrapper(req);
        List<BusMachinery> list = this.list(queryWrapper);
        return list.stream().map(this::getVo).toList();
    }

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMachinery entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        String machineryName = entity.getMachineryName();
        if (StrUtil.isBlank(machineryName)) {
            throw new ServiceException("机械名称不能为空", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除机械信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取机械视图对象
     *
     * @param machinery 机械对象
     * @return 机械视图对象
     */
    @Override
    public BusMachineryVo getVo(BusMachinery machinery) {
        // 对象转封装类
        BusMachineryVo machineryVo = new BusMachineryVo();
        if (machinery == null) {
            return machineryVo;
        }
        BeanUtils.copyProperties(machinery, machineryVo);
        return machineryVo;
    }

    /**
     * 获取机械查询条件封装
     *
     * @param req 机械查询条件
     * @return 机械查询条件封装
     */
    @Override
    public QueryWrapper<BusMachinery> getQueryWrapper(MachineryQueryReq req) {
        QueryWrapper<BusMachinery> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        String machineryName = req.getMachineryName();
        String machineryNumber = req.getMachineryNumber();
        Long projectId = req.getProjectId();
        Long number = req.getNumber();
        String principal = req.getPrincipal();
        String remark = req.getRemark();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(machineryName), "machinery_name", machineryName);
        queryWrapper.like(StringUtils.isNotBlank(principal), "principal", principal);
        queryWrapper.like(StringUtils.isNotBlank(machineryNumber), "machinery_number", machineryNumber);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(number), "number", number);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取机械分页对象视图
     *
     * @param machineryPage 机械分页对象
     * @return 机械分页对象视图
     */
    @Override
    public Page<BusMachineryVo> getVoPage(Page<BusMachinery> machineryPage) {
        List<BusMachinery> machineryList = machineryPage.getRecords();
        Page<BusMachineryVo> machineryVoPage = new Page<>(
            machineryPage.getCurrent(),
            machineryPage.getSize(),
            machineryPage.getTotal());
        if (CollUtil.isEmpty(machineryList)) {
            return machineryVoPage;
        }
        List<BusMachineryVo> machineryVoList = machineryList.stream().map(this::getVo).toList();
        machineryVoPage.setRecords(machineryVoList);
        return machineryVoPage;
    }
}
