package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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.system.domain.BusProjectFile;
import org.dromara.system.domain.dto.projectfile.BusProjectFileQueryReq;
import org.dromara.system.domain.dto.projectfile.BusProjectFileUpdateReq;
import org.dromara.system.domain.vo.projectfile.BusProjectFileVo;
import org.dromara.system.mapper.BusProjectFileMapper;
import org.dromara.system.service.IBusProjectFileService;
import org.dromara.system.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 项目文件存储Service业务层处理
 *
 * @author lilemy
 * @date 2025-04-23
 */
@Slf4j
@Service
public class BusProjectFileServiceImpl extends ServiceImpl<BusProjectFileMapper, BusProjectFile>
    implements IBusProjectFileService {

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询项目文件存储
     *
     * @param id 主键
     * @return 项目文件存储
     */
    @Override
    public BusProjectFileVo queryById(Long id) {
        BusProjectFile projectFile = this.getById(id);
        if (projectFile == null) {
            throw new ServiceException("对应项目文件存储信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(projectFile);
    }

    /**
     * 分页查询项目文件存储列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 项目文件存储分页列表
     */
    @Override
    public TableDataInfo<BusProjectFileVo> queryPageList(BusProjectFileQueryReq req, PageQuery pageQuery) {
        Page<BusProjectFile> projectFilePage = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(projectFilePage));
    }

    /**
     * 查询符合条件的项目文件存储列表
     *
     * @param req 查询条件
     * @return 项目文件存储列表
     */
    @Override
    public List<BusProjectFileVo> queryList(BusProjectFileQueryReq req) {
        LambdaQueryWrapper<BusProjectFile> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 修改项目文件存储
     *
     * @param req 项目文件存储
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BusProjectFileUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectFile projectFile = new BusProjectFile();
        BeanUtils.copyProperties(req, projectFile);
        // 数据校验
        validEntityBeforeSave(projectFile);
        // 判断是否存在
        BusProjectFile oldProjectFile = this.getById(projectFile.getId());
        if (oldProjectFile == null) {
            throw new ServiceException("修改项目文件存储失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        boolean update = this.updateById(projectFile);
        if (!update) {
            throw new ServiceException("修改项目文件存储失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

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

    /**
     * 校验并批量删除项目文件存储信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusProjectFile> projectFileList = this.listByIds(ids);
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = projectFileList.stream().map(BusProjectFile::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取项目文件存储视图对象
     *
     * @param projectFile 项目文件存储对象
     * @return 项目文件存储视图对象
     */
    @Override
    public BusProjectFileVo getVo(BusProjectFile projectFile) {
        // 对象转封装类
        BusProjectFileVo projectFileVo = new BusProjectFileVo();
        if (projectFile == null) {
            return projectFileVo;
        }
        BeanUtils.copyProperties(projectFile, projectFileVo);
        return projectFileVo;
    }

    /**
     * 获取项目文件存储查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProjectFile> buildQueryWrapper(BusProjectFileQueryReq req) {
        LambdaQueryWrapper<BusProjectFile> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        String fileType = req.getFileType();
        String fileName = req.getFileName();
        lqw.like(StringUtils.isNotBlank(fileName), BusProjectFile::getFileName, fileName);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusProjectFile::getProjectId, projectId);
        lqw.eq(StringUtils.isNotBlank(fileType), BusProjectFile::getFileType, fileType);
        return lqw;
    }

    /**
     * 获取项目文件存储分页对象视图
     *
     * @param projectFilePage 项目文件存储分页对象
     * @return 项目文件存储分页对象视图
     */
    @Override
    public Page<BusProjectFileVo> getVoPage(Page<BusProjectFile> projectFilePage) {
        List<BusProjectFile> projectFileList = projectFilePage.getRecords();
        Page<BusProjectFileVo> projectFileVoPage = new Page<>(
            projectFilePage.getCurrent(),
            projectFilePage.getSize(),
            projectFilePage.getTotal());
        if (CollUtil.isEmpty(projectFileList)) {
            return projectFileVoPage;
        }
        List<BusProjectFileVo> projectFileVoList = projectFileList.stream().map(this::getVo).toList();
        projectFileVoPage.setRecords(projectFileVoList);
        return projectFileVoPage;
    }
}
