package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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 com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.domain.dto.mediaPropaganda.MediaPropagandaAddRequest;
import com.ruoyi.web.domain.dto.mediaPropaganda.MediaPropagandaEditRequest;
import com.ruoyi.web.domain.dto.mediaPropaganda.MediaPropagandaQueryRequest;
import com.ruoyi.web.domain.entity.MediaPropaganda;
import com.ruoyi.web.domain.vo.MediaPropagandaVO;
import com.ruoyi.web.mapper.MediaPropagandaMapper;
import com.ruoyi.web.service.MediaPropagandaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 媒体宣传内容收集服务实现类
 */
@Slf4j
@Service
public class MediaPropagandaServiceImpl extends ServiceImpl<MediaPropagandaMapper, MediaPropaganda>
        implements MediaPropagandaService {

    @Override
    public Integer addMediaPropaganda(MediaPropagandaAddRequest mediaPropagandaAddRequest) {
        if (mediaPropagandaAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }

        try {
            // 1. 将请求对象转换为实体对象
            MediaPropaganda mediaPropaganda = new MediaPropaganda();
            BeanUtil.copyProperties(mediaPropagandaAddRequest, mediaPropaganda);

            // 2. 设置创建时间
            mediaPropaganda.setCreateTime(new Date());

            // 3. 数据校验
            validMediaPropaganda(mediaPropaganda, BusinessType.INSERT);

            // 4. 保存到数据库
            this.save(mediaPropaganda);
            return mediaPropaganda.getId();
        } catch (Exception e) {
            log.error("添加媒体宣传内容失败", e);
            throw new ServiceException("添加媒体宣传内容失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteMediaPropaganda(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("ID不能为空或ID异常");
        }

        try {
            // 分割ID字符串为列表
            List<Long> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(StrUtil::isNotBlank)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            if (idList.isEmpty()) {
                throw new ServiceException("ID格式异常");
            }

            // 构建删除条件
            QueryWrapper<MediaPropaganda> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", idList);

            // 执行删除（返回是否删除成功）
            return remove(queryWrapper);
        } catch (NumberFormatException e) {
            log.error("删除媒体宣传内容失败，ID格式错误", e);
            throw new ServiceException("ID格式错误");
        } catch (Exception e) {
            log.error("删除媒体宣传内容失败", e);
            throw new ServiceException("删除媒体宣传内容失败: " + e.getMessage());
        }
    }

    @Override
    public void editMediaPropaganda(MediaPropagandaEditRequest mediaPropagandaEditRequest) {
        if (mediaPropagandaEditRequest == null) {
            throw new ServiceException("请求参数为空");
        }

        try {
            // 1. 检查记录是否存在
            Integer id = mediaPropagandaEditRequest.getId();
            if (id == null || id <= 0) {
                throw new ServiceException("ID不能为空或无效");
            }

            MediaPropaganda existingMediaPropaganda = this.getById(id);
            if (existingMediaPropaganda == null) {
                throw new ServiceException("未找到对应的媒体宣传内容记录");
            }

            // 2. 将请求对象转换为实体对象
            MediaPropaganda mediaPropaganda = new MediaPropaganda();
            BeanUtil.copyProperties(mediaPropagandaEditRequest, mediaPropaganda);

            // 3. 设置更新时间
            mediaPropaganda.setUpdateTime(new Date());

            // 4. 数据校验
            validMediaPropaganda(mediaPropaganda, BusinessType.UPDATE);

            // 5. 更新到数据库
            this.updateById(mediaPropaganda);
        } catch (Exception e) {
            log.error("修改媒体宣传内容失败", e);
            throw new ServiceException("修改媒体宣传内容失败: " + e.getMessage());
        }
    }

    @Override
    public MediaPropagandaVO getMediaPropagandaById(int id) {
        if (id <= 0) {
            throw new ServiceException("ID不能为空或无效");
        }

        try {
            MediaPropaganda mediaPropaganda = this.getById(id);
            if (mediaPropaganda == null) {
                return null;
            }
            return getMediaPropagandaVO(mediaPropaganda);
        } catch (Exception e) {
            log.error("获取媒体宣传内容详情失败", e);
            throw new ServiceException("获取媒体宣传内容详情失败: " + e.getMessage());
        }
    }

    @Override
    public MediaPropagandaVO getMediaPropagandaVO(MediaPropaganda mediaPropaganda) {
        if (mediaPropaganda == null) {
            return null;
        }

        try {
            MediaPropagandaVO mediaPropagandaVO = new MediaPropagandaVO();
            BeanUtil.copyProperties(mediaPropaganda, mediaPropagandaVO);
            return mediaPropagandaVO;
        } catch (Exception e) {
            log.error("转换媒体宣传内容VO失败", e);
            throw new ServiceException("转换媒体宣传内容VO失败: " + e.getMessage());
        }
    }

    @Override
    public Page<MediaPropagandaVO> getListMediaPropagandaByPage(MediaPropagandaQueryRequest mediaPropagandaQueryRequest) {
        if (mediaPropagandaQueryRequest == null) {
            throw new ServiceException("查询参数为空");
        }

        try {
            // 1. 构建查询条件
            QueryWrapper<MediaPropaganda> queryWrapper = getQueryWrapper(mediaPropagandaQueryRequest);

            // 2. 执行分页查询
            Page<MediaPropaganda> page = new Page<>(mediaPropagandaQueryRequest.getPageNum(), mediaPropagandaQueryRequest.getPageSize());
            Page<MediaPropaganda> mediaPropagandaPage = this.page(page, queryWrapper);

            // 3. 转换为VO
            Page<MediaPropagandaVO> voPage = new Page<>();
            BeanUtil.copyProperties(mediaPropagandaPage, voPage);

            List<MediaPropagandaVO> voList = mediaPropagandaPage.getRecords().stream()
                    .map(this::getMediaPropagandaVO)
                    .collect(Collectors.toList());
            voPage.setRecords(voList);

            return voPage;
        } catch (Exception e) {
            log.error("分页查询媒体宣传内容失败", e);
            throw new ServiceException("分页查询媒体宣传内容失败: " + e.getMessage());
        }
    }

    @Override
    public QueryWrapper<MediaPropaganda> getQueryWrapper(MediaPropagandaQueryRequest mediaPropagandaQueryRequest) {
        QueryWrapper<MediaPropaganda> queryWrapper = new QueryWrapper<>();
        Date extractStartTime = mediaPropagandaQueryRequest.getExtractStartTime();
        Date extractEndTime = mediaPropagandaQueryRequest.getExtractEndTime();
        Date publishStartTime = mediaPropagandaQueryRequest.getPublishStartTime();
        Date publishEndTime = mediaPropagandaQueryRequest.getPublishEndTime();
        String keyword = mediaPropagandaQueryRequest.getKeyword();
        String sortField = mediaPropagandaQueryRequest.getSortField();
        String sortOrder = mediaPropagandaQueryRequest.getSortOrder();

        // 关键词搜索（标题或内容）
        if (StrUtil.isNotBlank(mediaPropagandaQueryRequest.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like("title", keyword)
                    .or()
                    .like("content", keyword)
            );
        }

        // 摘录日期范围查询
        if (ObjectUtil.isNotNull(mediaPropagandaQueryRequest.getExtractStartTime())) {
            queryWrapper.ge("extract_date", extractStartTime);
        }
        if (ObjectUtil.isNotNull(mediaPropagandaQueryRequest.getExtractEndTime())) {
            queryWrapper.le("extract_date", extractEndTime);
        }

        // 发布日期范围查询
        if (ObjectUtil.isNotNull(mediaPropagandaQueryRequest.getPublishStartTime())) {
            queryWrapper.ge("publish_date", publishStartTime);
        }
        if (ObjectUtil.isNotNull(mediaPropagandaQueryRequest.getPublishEndTime())) {
            queryWrapper.le("publish_date", publishEndTime);
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);


        return queryWrapper;
    }

    /**
     * 数据校验
     *
     * @param mediaPropaganda 媒体宣传内容实体
     * @param type            业务类型
     */
    public void validMediaPropaganda(MediaPropaganda mediaPropaganda, BusinessType type) {
        if (mediaPropaganda == null) {
            throw new ServiceException("媒体宣传内容数据不能为空");
        }
        Integer id = mediaPropaganda.getId();
        String title = mediaPropaganda.getTitle();
        String mediaPropagandaType = mediaPropaganda.getType();
        String content = mediaPropaganda.getContent();
        Date extractDate = mediaPropaganda.getExtractDate();
        Date publishDate = mediaPropaganda.getPublishDate();
        String source = mediaPropaganda.getSource();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(title)) {
            throw new ServiceException("标题不能为空");
        }
        if (StrUtil.isBlank(mediaPropagandaType)) {
            throw new ServiceException("类型不能为空");
        }
        if (StrUtil.isBlank(content)) {
            throw new ServiceException("内容不能为空");
        }
        if (ObjectUtil.isEmpty(extractDate)) {
            throw new ServiceException("摘录日期不能为空");
        }
        if (ObjectUtil.isEmpty(publishDate)) {
            throw new ServiceException("发布日期不能为空");
        }
        if (StrUtil.isBlank(source)) {
            throw new ServiceException("来源不能为空");
        }
    }
}




