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.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.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.IBusMachineryDetailService;
import org.dromara.machinery.service.IBusMachineryService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
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;

    @Lazy
    @Resource
    private IBusMachineryDetailService machineryDetailService;

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

    /**
     * 查询符合条件的机械列表
     *
     * @param req 查询条件
     * @return 机械列表
     */
    @Override
    public List<BusMachineryVo> queryList(MachineryQueryReq req) {
        LambdaQueryWrapper<BusMachinery> lqw = this.buildQuery(req);
        List<BusMachinery> list = this.list(lqw);
        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) {
        // 做一些数据校验,如唯一约束
        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);
        }
        // 判断用户是否对项目下的内容有操作权限
        Long userId = LoginHelper.getUserId();
        projectService.validAuth(projectId, userId);
    }

    /**
     * 校验并批量删除机械信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusMachinery> machineryList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = machineryList.stream().map(BusMachinery::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
            // 判断是否还存在机械详情信息
            QueryWrapper<BusMachineryDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("machinery_id", ids);
            if (machineryDetailService.count(queryWrapper) > 0) {
                throw new ServiceException("删除机械失败，机械存在机械详情信息", HttpStatus.BAD_REQUEST);
            }
        }
        if (machineryList.size() != ids.size()) {
            throw new ServiceException("删除机械失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        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 LambdaQueryWrapper<BusMachinery> buildQuery(MachineryQueryReq req) {
        LambdaQueryWrapper<BusMachinery> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        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();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(machineryName), BusMachinery::getMachineryName, machineryName);
        lqw.like(StringUtils.isNotBlank(principal), BusMachinery::getPrincipal, principal);
        lqw.like(StringUtils.isNotBlank(machineryNumber), BusMachinery::getMachineryNumber, machineryNumber);
        lqw.like(StringUtils.isNotBlank(remark), BusMachinery::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusMachinery::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusMachinery::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(number), BusMachinery::getNumber, number);
        return lqw;
    }

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