package org.dromara.machinery.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.machinery.domain.BusMachinery;
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.dromara.project.service.IBusProjectService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
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;

    @Resource
    private IBusProjectService projectService;

    @Resource
    private ISysOssService ossService;

    /**
     * 查询机械详情
     *
     * @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       查询条件
     * @param pageQuery 分页参数
     * @return 机械详情分页列表
     */
    @Override
    public TableDataInfo<BusMachineryDetailVo> queryPageList(MachineryDetailQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusMachineryDetail> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的机械详情列表
     *
     * @param req 查询条件
     * @return 机械详情列表
     */
    @Override
    public List<BusMachineryDetailVo> queryList(MachineryDetailQueryReq req) {
        LambdaQueryWrapper<BusMachineryDetail> lqw = this.buildQuery(req);
        List<BusMachineryDetail> list = this.list(lqw);
        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) {
        // 做一些数据校验,如唯一约束
        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);
        }
        String type = entity.getType();
        if (StringUtils.isEmpty(type)) {
            throw new ServiceException("请选择入场/出场", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除机械详情信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusMachineryDetail> machineryDetailList = this.listByIds(ids);
        // 做一些业务上的校验,判断是否需要校验
        if (isValid) {
            // 获取机械id列表
            List<Long> machineryIdList = machineryDetailList.stream().map(BusMachineryDetail::getMachineryId).toList();
            List<BusMachinery> machineryList = machineryService.listByIds(machineryIdList);
            // 获取对应项目id列表
            List<Long> projectIdList = machineryList.stream().map(BusMachinery::getProjectId).toList();
            projectService.validAuth(projectIdList, userId);
        }
        if (machineryDetailList.size() != ids.size()) {
            throw new ServiceException("删除机械详情失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        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);
        // 获取图片信息
        String picture = machineryDetail.getPicture();
        if (StringUtils.isNotEmpty(picture)) {
            List<Long> picList = Arrays.stream(picture.split(","))
                .map(Long::parseLong)
                .toList();
            List<SysOssVo> pictureList = ossService.listByIds(picList);
            machineryDetailVo.setPictureList(pictureList);
        }
        return machineryDetailVo;
    }

    /**
     * 获取机械详情查询条件封装
     *
     * @param req 机械详情查询条件
     * @return 机械详情查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusMachineryDetail> buildQuery(MachineryDetailQueryReq req) {
        LambdaQueryWrapper<BusMachineryDetail> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String checkoutNumber = req.getCheckoutNumber();
        String checkoutUnit = req.getCheckoutUnit();
        String checkoutDate = req.getCheckoutDate();
        String status = req.getStatus();
        String type = req.getType();
        Date entryTime = req.getEntryTime();
        String remark = req.getRemark();
        Long machineryId = req.getMachineryId();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(checkoutNumber), BusMachineryDetail::getCheckoutNumber, checkoutNumber);
        lqw.like(StringUtils.isNotBlank(checkoutUnit), BusMachineryDetail::getCheckoutUnit, checkoutUnit);
        lqw.like(StringUtils.isNotBlank(checkoutDate), BusMachineryDetail::getCheckoutDate, checkoutDate);
        lqw.like(StringUtils.isNotBlank(remark), BusMachineryDetail::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusMachineryDetail::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(status), BusMachineryDetail::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(type), BusMachineryDetail::getType, type);
        lqw.eq(ObjectUtils.isNotEmpty(entryTime), BusMachineryDetail::getEntryTime, entryTime);
        lqw.eq(ObjectUtils.isNotEmpty(machineryId), BusMachineryDetail::getMachineryId, machineryId);
        return lqw;
    }

    /**
     * 获取机械详情分页对象视图
     *
     * @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;
    }
}
