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.update.LambdaUpdateWrapper;
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.EqpMachinery;
import org.dromara.machinery.domain.EqpMachineryDetail;
import org.dromara.machinery.domain.enums.EqpMachineryDetailTypeEnum;
import org.dromara.machinery.domain.dto.machinerydetail.EqpMachineryDetailCreateReq;
import org.dromara.machinery.domain.dto.machinerydetail.EqpMachineryDetailQueryReq;
import org.dromara.machinery.domain.dto.machinerydetail.EqpMachineryDetailUpdateReq;
import org.dromara.machinery.domain.vo.machinerydetail.EqpMachineryDetailVo;
import org.dromara.machinery.mapper.EqpMachineryDetailMapper;
import org.dromara.machinery.service.IEqpMachineryDetailService;
import org.dromara.machinery.service.IEqpMachineryService;
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 EqpMachineryDetailServiceImpl extends ServiceImpl<EqpMachineryDetailMapper, EqpMachineryDetail>
    implements IEqpMachineryDetailService {

    @Resource
    private IEqpMachineryService machineryService;

    @Resource
    private IBusProjectService projectService;

    @Resource
    private ISysOssService ossService;

    /**
     * 查询机械详情
     *
     * @param id 主键
     * @return 机械详情
     */
    @Override
    public EqpMachineryDetailVo queryById(Long id) {
        EqpMachineryDetail 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<EqpMachineryDetailVo> queryPageList(EqpMachineryDetailQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<EqpMachineryDetail> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的机械详情列表
     *
     * @param req 查询条件
     * @return 机械详情列表
     */
    @Override
    public List<EqpMachineryDetailVo> queryList(EqpMachineryDetailQueryReq req) {
        LambdaQueryWrapper<EqpMachineryDetail> lqw = this.buildQueryWrapper(req);
        List<EqpMachineryDetail> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增机械详情
     *
     * @param req 机械详情
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(EqpMachineryDetailCreateReq req) {
        // 将实体类和 DTO 进行转换
        EqpMachineryDetail machineryDetail = new EqpMachineryDetail();
        BeanUtils.copyProperties(req, machineryDetail);
        // 数据校验
        req.setType(EqpMachineryDetailTypeEnum.PUT.getValue());
        validEntityBeforeSave(machineryDetail);
        // 判断是否存在
        Long count = this.lambdaQuery()
            .eq(EqpMachineryDetail::getCheckoutNumber, req.getCheckoutNumber())
            .count();
        if (count > 0) {
            throw new ServiceException("该编号机械已存在", HttpStatus.BAD_REQUEST);
        }
        // 操作数据库
        boolean save = this.save(machineryDetail);
        if (!save) {
            throw new ServiceException("新增机械详情失败，数据库异常", HttpStatus.ERROR);
        }
        // 修改机械数量
        LambdaUpdateWrapper<EqpMachinery> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(EqpMachinery::getId, machineryDetail.getMachineryId());
        lqw.setSql("number = number + 1");
        boolean update = machineryService.update(lqw);
        if (!update) {
            throw new ServiceException("修改机械数量失败，数据库异常", HttpStatus.ERROR);
        }
        return machineryDetail.getId();
    }

    /**
     * 修改机械详情
     *
     * @param req 机械详情
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(EqpMachineryDetailUpdateReq req) {
        // 将实体类和 DTO 进行转换
        EqpMachineryDetail machineryDetail = new EqpMachineryDetail();
        BeanUtils.copyProperties(req, machineryDetail);
        // 数据校验
        validEntityBeforeSave(machineryDetail);
        // 判断是否存在
        EqpMachineryDetail oldMachineryDetail = this.getById(machineryDetail.getId());
        if (oldMachineryDetail == null) {
            throw new ServiceException("修改机械详情失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        String type = req.getType();
        Long machineryId = machineryDetail.getMachineryId();
        if (!type.equals(oldMachineryDetail.getType())) {
            if (EqpMachineryDetailTypeEnum.PUT.getValue().equals(type)) {
                LambdaUpdateWrapper<EqpMachinery> lqw = new LambdaUpdateWrapper<>();
                lqw.eq(EqpMachinery::getId, machineryId);
                lqw.setSql("number = number + 1");
                boolean update = machineryService.update(lqw);
                if (!update) {
                    throw new ServiceException("修改机械数量失败，数据库异常", HttpStatus.ERROR);
                }
            } else if (EqpMachineryDetailTypeEnum.OUT.getValue().equals(type)) {
                LambdaUpdateWrapper<EqpMachinery> lqw = new LambdaUpdateWrapper<>();
                lqw.eq(EqpMachinery::getId, machineryId);
                lqw.setSql("number = number - 1");
                boolean update = machineryService.update(lqw);
                if (!update) {
                    throw new ServiceException("修改机械数量失败，数据库异常", HttpStatus.ERROR);
                }
            }
        }
        // 操作数据库
        return this.updateById(machineryDetail);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EqpMachineryDetail 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);
        }
    }

    /**
     * 校验并批量删除机械详情信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<EqpMachineryDetail> machineryDetailList = this.listByIds(ids);
        // 做一些业务上的校验,判断是否需要校验
        if (isValid) {
            // 获取机械id列表
            List<Long> machineryIdList = machineryDetailList.stream().map(EqpMachineryDetail::getMachineryId).toList();
            List<EqpMachinery> machineryList = machineryService.listByIds(machineryIdList);
            // 获取对应项目id列表
            List<Long> projectIdList = machineryList.stream().map(EqpMachinery::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 EqpMachineryDetailVo getVo(EqpMachineryDetail machineryDetail) {
        // 对象转封装类
        EqpMachineryDetailVo machineryDetailVo = new EqpMachineryDetailVo();
        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<EqpMachineryDetail> buildQueryWrapper(EqpMachineryDetailQueryReq req) {
        LambdaQueryWrapper<EqpMachineryDetail> 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), EqpMachineryDetail::getCheckoutNumber, checkoutNumber);
        lqw.like(StringUtils.isNotBlank(checkoutUnit), EqpMachineryDetail::getCheckoutUnit, checkoutUnit);
        lqw.like(StringUtils.isNotBlank(checkoutDate), EqpMachineryDetail::getCheckoutDate, checkoutDate);
        lqw.like(StringUtils.isNotBlank(remark), EqpMachineryDetail::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), EqpMachineryDetail::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(status), EqpMachineryDetail::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(type), EqpMachineryDetail::getType, type);
        lqw.eq(ObjectUtils.isNotEmpty(entryTime), EqpMachineryDetail::getEntryTime, entryTime);
        lqw.eq(ObjectUtils.isNotEmpty(machineryId), EqpMachineryDetail::getMachineryId, machineryId);
        return lqw;
    }

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