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.BusMachineryDetail;
import org.dromara.machinery.domain.req.machinerydetail.MachineryDetailCreateReq;
import org.dromara.machinery.domain.req.machinerydetail.MachineryDetailQueryReq;
import org.dromara.machinery.domain.req.machinerydetail.MachineryDetailUpdateReq;
import org.dromara.machinery.domain.vo.BusMachineryDetailVo;
import org.dromara.machinery.mapper.BusMachineryDetailMapper;
import org.dromara.machinery.service.IBusMachineryDetailService;
import org.dromara.machinery.service.IBusMachineryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 机械详情Service业务层处理
 *
 * @author lcj
 * @date 2025-03-07
 */
@Service
public class BusMachineryDetailServiceImpl extends ServiceImpl<BusMachineryDetailMapper, BusMachineryDetail>
    implements IBusMachineryDetailService {

    @Resource
    private IBusMachineryService machineryService;

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

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

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

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMachineryDetail entity) {
        // TODO 做一些数据校验,如唯一约束
        Long machineryId = entity.getMachineryId();
        if (machineryId == null) {
            throw new ServiceException("机械 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (machineryService.getById(machineryId) == null) {
            throw new ServiceException("对应机械不存在", HttpStatus.BAD_REQUEST);
        }
        Long type = entity.getType();
        if (type == 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) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取机械详情视图对象
     *
     * @param machineryDetail 机械详情对象
     * @return 机械详情视图对象
     */
    @Override
    public BusMachineryDetailVo getVo(BusMachineryDetail machineryDetail) {// 对象转封装类
        BusMachineryDetailVo machineryDetailVo = new BusMachineryDetailVo();
        if (machineryDetail == null) {
            return machineryDetailVo;
        }
        BeanUtils.copyProperties(machineryDetail, machineryDetailVo);
        return machineryDetailVo;
    }

    /**
     * 获取机械详情查询条件封装
     *
     * @param req 机械详情查询条件
     * @return 机械详情查询条件封装
     */
    @Override
    public QueryWrapper<BusMachineryDetail> getQueryWrapper(MachineryDetailQueryReq req) {
        QueryWrapper<BusMachineryDetail> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        String checkoutNumber = req.getCheckoutNumber();
        String checkoutUnit = req.getCheckoutUnit();
        String checkoutDate = req.getCheckoutDate();
        Long status = req.getStatus();
        Long type = req.getType();
        Date entryTime = req.getEntryTime();
        String remark = req.getRemark();
        Long machineryId = req.getMachineryId();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(checkoutNumber), "checkout_number", checkoutNumber);
        queryWrapper.like(StringUtils.isNotBlank(checkoutUnit), "checkout_unit", checkoutUnit);
        queryWrapper.like(StringUtils.isNotBlank(checkoutDate), "checkout_date", checkoutDate);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(type), "type", type);
        queryWrapper.eq(ObjectUtils.isNotEmpty(entryTime), "entryTime", entryTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(machineryId), "machinery_id", machineryId);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取机械详情分页对象视图
     *
     * @param machineryDetailPage 机械详情分页对象
     * @return 机械详情分页对象视图
     */
    @Override
    public Page<BusMachineryDetailVo> getVoPage(Page<BusMachineryDetail> machineryDetailPage) {
        List<BusMachineryDetail> machineryDetailList = machineryDetailPage.getRecords();
        Page<BusMachineryDetailVo> machineryDetailVoPage = new Page<>(
            machineryDetailPage.getCurrent(),
            machineryDetailPage.getSize(),
            machineryDetailPage.getTotal());
        if (CollUtil.isEmpty(machineryDetailList)) {
            return machineryDetailVoPage;
        }
        List<BusMachineryDetailVo> machineryDetailVoList = machineryDetailList.stream().map(this::getVo).toList();
        machineryDetailVoPage.setRecords(machineryDetailVoList);
        return machineryDetailVoPage;
    }
}
