package org.xyzh.news.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.dto.resource.TbResourceRecommend;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.news.mapper.ResourceRecommendMapper;
import org.xyzh.api.news.recommend.ResourceRecommendService;

/**
 * @description 资源推荐服务实现类
 * @filename NCResourceRecommendServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class NCResourceRecommendServiceImpl implements ResourceRecommendService {

    private static final Logger logger = LoggerFactory.getLogger(NCResourceRecommendServiceImpl.class);

    @Autowired
    private ResourceRecommendMapper resourceRecommendMapper;

    @Override
    public ResultDomain<TbResourceRecommend> getRecommendList() {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            List<TbResourceRecommend> list = resourceRecommendMapper.selectResourceRecommends(new TbResourceRecommend());
            resultDomain.success("获取推荐列表成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取推荐列表异常: {}", e.getMessage(), e);
            resultDomain.fail("获取推荐列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceRecommend> addRecommend(TbResourceRecommend recommend) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (recommend == null || !StringUtils.hasText(recommend.getResourceID())) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 检查资源是否已被推荐
            List<TbResourceRecommend> existingList = resourceRecommendMapper.selectByResourceId(recommend.getResourceID());
            if (existingList != null && !existingList.isEmpty()) {
                resultDomain.fail("该资源已被推荐");
                return resultDomain;
            }

            // 设置默认值
            if (recommend.getID() == null) {
                recommend.setID(IDUtils.generateID());
            }
            
            recommend.setCreateTime(new Date());
            recommend.setUpdateTime(new Date());
            recommend.setDeleted(false);

            // 如果没有设置排序号，默认为最大排序号+1
            if (recommend.getOrderNum() == null) {
                recommend.setOrderNum(0);
            }

            // 插入数据库
            int result = resourceRecommendMapper.insertResourceRecommend(recommend);
            if (result > 0) {
                logger.info("添加推荐成功: {}", recommend.getResourceID());
                resultDomain.success("添加推荐成功", recommend);
                return resultDomain;
            } else {
                resultDomain.fail("添加推荐失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("添加推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("添加推荐失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceRecommend> updateRecommend(TbResourceRecommend recommend) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (recommend == null || !StringUtils.hasText(recommend.getID())) {
                resultDomain.fail("推荐ID不能为空");
                return resultDomain;
            }

            // 检查推荐是否存在
            TbResourceRecommend existing = resourceRecommendMapper.selectById(recommend.getID());
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("推荐不存在");
                return resultDomain;
            }

            // 更新时间
            recommend.setUpdateTime(new Date());

            // 更新数据库
            int result = resourceRecommendMapper.updateResourceRecommend(recommend);
            if (result > 0) {
                logger.info("更新推荐成功: {}", recommend.getID());
                // 重新查询返回完整数据
                TbResourceRecommend updated = resourceRecommendMapper.selectById(recommend.getID());
                resultDomain.success("更新推荐成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新推荐失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("更新推荐失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteRecommend(String resourceID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询推荐
            List<TbResourceRecommend> recommendList = resourceRecommendMapper.selectByResourceId(resourceID);
            if (recommendList == null || recommendList.isEmpty()) {
                resultDomain.fail("推荐不存在");
                return resultDomain;
            }

            // 物理删除
            TbResourceRecommend recommend = recommendList.get(0);
            int result = resourceRecommendMapper.deleteResourceRecommend(recommend);
            if (result > 0) {
                logger.info("删除推荐成功: {}", resourceID);
                resultDomain.success("删除推荐成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("删除推荐失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("删除推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("删除推荐失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> removeRecommend(String resourceID) {
        return deleteRecommend(resourceID);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceRecommend> batchAddRecommends(List<String> resourceIDs, String reason) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (resourceIDs == null || resourceIDs.isEmpty()) {
                resultDomain.fail("资源ID列表不能为空");
                return resultDomain;
            }

            List<TbResourceRecommend> recommendList = new ArrayList<>();
            Date now = new Date();

            for (String resourceID : resourceIDs) {
                if (!StringUtils.hasText(resourceID)) {
                    continue;
                }

                // 检查是否已推荐
                List<TbResourceRecommend> existingList = resourceRecommendMapper.selectByResourceId(resourceID);
                if (existingList != null && !existingList.isEmpty()) {
                    continue;
                }

                TbResourceRecommend recommend = new TbResourceRecommend();
                recommend.setID(IDUtils.generateID());
                recommend.setResourceID(resourceID);
                recommend.setReason(reason);
                recommend.setOrderNum(0);
                recommend.setCreateTime(now);
                recommend.setUpdateTime(now);
                recommend.setDeleted(false);

                recommendList.add(recommend);
            }

            if (recommendList.isEmpty()) {
                resultDomain.fail("没有可添加的推荐资源");
                return resultDomain;
            }

            // 批量插入
            int result = resourceRecommendMapper.batchInsertResourceRecommends(recommendList);
            if (result > 0) {
                logger.info("批量添加推荐成功，数量: {}", result);
                resultDomain.success("批量添加推荐成功", recommendList);
                return resultDomain;
            } else {
                resultDomain.fail("批量添加推荐失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("批量添加推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("批量添加推荐失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> batchRemoveRecommends(List<String> resourceIDs) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (resourceIDs == null || resourceIDs.isEmpty()) {
                resultDomain.fail("资源ID列表不能为空");
                return resultDomain;
            }

            List<String> recommendIDs = new ArrayList<>();
            for (String resourceID : resourceIDs) {
                if (!StringUtils.hasText(resourceID)) {
                    continue;
                }

                List<TbResourceRecommend> recommendList = resourceRecommendMapper.selectByResourceId(resourceID);
                if (recommendList != null && !recommendList.isEmpty()) {
                    for (TbResourceRecommend recommend : recommendList) {
                        recommendIDs.add(recommend.getID());
                    }
                }
            }

            if (recommendIDs.isEmpty()) {
                resultDomain.fail("没有可移除的推荐");
                return resultDomain;
            }

            // 批量删除
            int result = resourceRecommendMapper.batchDeleteResourceRecommends(recommendIDs);
            if (result > 0) {
                logger.info("批量移除推荐成功，数量: {}", result);
                resultDomain.success("批量移除推荐成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("批量移除推荐失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("批量移除推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("批量移除推荐失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResourceRecommend> getRecommendDetail(String recommendID) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(recommendID)) {
                resultDomain.fail("推荐ID不能为空");
                return resultDomain;
            }

            // 查询推荐
            TbResourceRecommend recommend = resourceRecommendMapper.selectByRecommendId(recommendID);
            if (recommend == null || recommend.getDeleted()) {
                resultDomain.fail("推荐不存在");
                return resultDomain;
            }

            resultDomain.success("获取推荐详情成功", recommend);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取推荐详情异常: {}", e.getMessage(), e);
            resultDomain.fail("获取推荐详情失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> isResourceRecommended(String resourceID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询推荐
            List<TbResourceRecommend> recommendList = resourceRecommendMapper.selectByResourceId(resourceID);
            boolean isRecommended = recommendList != null && !recommendList.isEmpty();

            resultDomain.success("检查成功", isRecommended);
            return resultDomain;
        } catch (Exception e) {
            logger.error("检查资源是否推荐异常: {}", e.getMessage(), e);
            resultDomain.fail("检查失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceRecommend> updateRecommendOrder(String resourceID, Integer orderNum) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }
            if (orderNum == null) {
                resultDomain.fail("排序号不能为空");
                return resultDomain;
            }

            // 查询推荐
            List<TbResourceRecommend> recommendList = resourceRecommendMapper.selectByResourceId(resourceID);
            if (recommendList == null || recommendList.isEmpty()) {
                resultDomain.fail("推荐不存在");
                return resultDomain;
            }

            TbResourceRecommend recommend = recommendList.get(0);
            recommend.setOrderNum(orderNum);
            recommend.setUpdateTime(new Date());

            // 更新数据库
            int result = resourceRecommendMapper.updateResourceRecommend(recommend);
            if (result > 0) {
                logger.info("更新推荐排序成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResourceRecommend updated = resourceRecommendMapper.selectById(recommend.getID());
                resultDomain.success("更新推荐排序成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新推荐排序失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新推荐排序异常: {}", e.getMessage(), e);
            resultDomain.fail("更新推荐排序失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceRecommend> updateRecommendReason(String resourceID, String reason) {
        ResultDomain<TbResourceRecommend> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询推荐
            List<TbResourceRecommend> recommendList = resourceRecommendMapper.selectByResourceId(resourceID);
            if (recommendList == null || recommendList.isEmpty()) {
                resultDomain.fail("推荐不存在");
                return resultDomain;
            }

            TbResourceRecommend recommend = recommendList.get(0);
            recommend.setReason(reason);
            recommend.setUpdateTime(new Date());

            // 更新数据库
            int result = resourceRecommendMapper.updateResourceRecommend(recommend);
            if (result > 0) {
                logger.info("更新推荐理由成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResourceRecommend updated = resourceRecommendMapper.selectById(recommend.getID());
                resultDomain.success("更新推荐理由成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新推荐理由失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新推荐理由异常: {}", e.getMessage(), e);
            resultDomain.fail("更新推荐理由失败: " + e.getMessage());
            return resultDomain;
        }
    }
}
