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 org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
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.BusProjectNews;
import org.dromara.system.domain.dto.projectnews.BusProjectNewsCreateReq;
import org.dromara.system.domain.dto.projectnews.BusProjectNewsGisReq;
import org.dromara.system.domain.dto.projectnews.BusProjectNewsQueryReq;
import org.dromara.system.domain.dto.projectnews.BusProjectNewsUpdateReq;
import org.dromara.system.domain.vo.projectnews.BusProjectNewsGisVo;
import org.dromara.system.domain.vo.projectnews.BusProjectNewsVo;
import org.dromara.system.mapper.BusProjectNewsMapper;
import org.dromara.system.service.IBusProjectNewsService;
import org.dromara.system.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 项目新闻Service业务层处理
 *
 * @author lilemy
 * @date 2025-04-28
 */
@Service
public class BusProjectNewsServiceImpl extends ServiceImpl<BusProjectNewsMapper, BusProjectNews>
    implements IBusProjectNewsService {

    @Resource
    private IBusProjectService projectService;

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

    /**
     * 分页查询项目新闻列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 项目新闻分页列表
     */
    @Override
    public TableDataInfo<BusProjectNewsVo> queryPageList(BusProjectNewsQueryReq req, PageQuery pageQuery) {
        Page<BusProjectNews> projectNewsPage = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(projectNewsPage));
    }

    /**
     * 查询符合条件的项目新闻列表
     *
     * @param req 查询条件
     * @return 项目新闻列表
     */
    @Override
    public List<BusProjectNewsVo> queryList(BusProjectNewsQueryReq req) {
        LambdaQueryWrapper<BusProjectNews> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 查询大屏项目新闻列表
     *
     * @param req 列表查询条件
     * @return 大屏项目新闻列表
     */
    @Override
    public List<BusProjectNewsGisVo> queryGisList(BusProjectNewsGisReq req) {
        Long projectId = req.getProjectId();
        if (projectId == null || projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        List<BusProjectNews> projectNewsList = this.lambdaQuery()
            .select(BusProjectNews::getId, BusProjectNews::getTitle)
            .eq(BusProjectNews::getProjectId, projectId)
            .list();
        return projectNewsList.stream().map(projectNews -> {
            BusProjectNewsGisVo projectNewsGisResp = new BusProjectNewsGisVo();
            BeanUtils.copyProperties(projectNews, projectNewsGisResp);
            projectNewsGisResp.setShow(false);
            return projectNewsGisResp;
        }).toList();
    }

    /**
     * 根据项目id查询项目新闻列表
     *
     * @param projectId 项目id
     * @return 项目新闻列表
     */
    @Override
    public List<BusProjectNewsVo> queryListByProject(Long projectId) {
        List<BusProjectNews> list = this.lambdaQuery()
            .eq(BusProjectNews::getProjectId, projectId)
            .list();
        return this.getVoList(list);
    }

    /**
     * 新增项目新闻
     *
     * @param req 项目新闻
     * @return 新增项目新闻id
     */
    @Override
    public Long insertByBo(BusProjectNewsCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectNews projectNews = new BusProjectNews();
        BeanUtils.copyProperties(req, projectNews);
        // 数据校验
        validEntityBeforeSave(projectNews, true);
        // 操作数据库
        boolean save = this.save(projectNews);
        if (!save) {
            throw new ServiceException("新增项目新闻存储失败，数据库异常", HttpStatus.ERROR);
        }
        return projectNews.getId();
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProjectNews entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
    }

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

    /**
     * 获取项目新闻存储视图对象
     *
     * @param projectNews 项目新闻存储对象
     * @return 项目新闻存储视图对象
     */
    @Override
    public BusProjectNewsVo getVo(BusProjectNews projectNews) {
        // 对象转封装类
        BusProjectNewsVo projectNewsVo = new BusProjectNewsVo();
        if (projectNews == null) {
            return projectNewsVo;
        }
        BeanUtils.copyProperties(projectNews, projectNewsVo);
        return projectNewsVo;
    }

    /**
     * 获取项目新闻存储查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProjectNews> buildQueryWrapper(BusProjectNewsQueryReq req) {
        LambdaQueryWrapper<BusProjectNews> lqw = new LambdaQueryWrapper<>();
        Long projectId = req.getProjectId();
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusProjectNews::getProjectId, projectId);
        return lqw;
    }

    /**
     * 获取项目新闻存储分页对象视图
     *
     * @param projectNewsPage 项目新闻存储分页对象
     * @return 项目新闻存储分页对象视图
     */
    @Override
    public Page<BusProjectNewsVo> getVoPage(Page<BusProjectNews> projectNewsPage) {
        List<BusProjectNews> projectNewsList = projectNewsPage.getRecords();
        Page<BusProjectNewsVo> projectNewsVoPage = new Page<>(
            projectNewsPage.getCurrent(),
            projectNewsPage.getSize(),
            projectNewsPage.getTotal());
        if (CollUtil.isEmpty(projectNewsList)) {
            return projectNewsVoPage;
        }
        List<BusProjectNewsVo> projectNewsVoList = projectNewsList.stream().map(this::getVo).toList();
        projectNewsVoPage.setRecords(projectNewsVoList);
        return projectNewsVoPage;
    }

    /**
     * 获取项目新闻存储列表视图对象
     *
     * @param projectNewsList 项目新闻存储列表对象
     * @return 项目新闻存储列表视图对象
     */
    @Override
    public List<BusProjectNewsVo> getVoList(List<BusProjectNews> projectNewsList) {
        return projectNewsList.stream().map(this::getVo).toList();
    }

}
