package org.xyzh.news.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

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.TbBanner;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.news.mapper.BannerMapper;
import org.xyzh.api.news.banner.BannerService;

/**
 * @description 横幅服务实现类
 * @filename NCBannerServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class NCBannerServiceImpl implements BannerService {

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

    @Autowired
    private BannerMapper bannerMapper;

    @Override
    public ResultDomain<TbBanner> getBannerList(Integer status) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            List<TbBanner> list;
            if (status != null) {
                list = bannerMapper.selectByStatus(status);
            } else {
                TbBanner filter = new TbBanner();
                list = bannerMapper.selectBanners(filter);
            }
            resultDomain.success("获取横幅列表成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取横幅列表异常: {}", e.getMessage(), e);
            resultDomain.fail("获取横幅列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbBanner> getBannerById(String bannerID) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(bannerID)) {
                resultDomain.fail("横幅ID不能为空");
                return resultDomain;
            }

            // 查询横幅
            TbBanner banner = bannerMapper.selectByBannerId(bannerID);
            if (banner == null || banner.getDeleted()) {
                resultDomain.fail("横幅不存在");
                return resultDomain;
            }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbBanner> createBanner(TbBanner banner) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (banner == null || !StringUtils.hasText(banner.getTitle())) {
                resultDomain.fail("横幅标题不能为空");
                return resultDomain;
            }
            if (!StringUtils.hasText(banner.getImageUrl())) {
                resultDomain.fail("横幅图片不能为空");
                return resultDomain;
            }

            // 检查标题是否已存在
            int count = bannerMapper.countByTitle(banner.getTitle(), null);
            if (count > 0) {
                resultDomain.fail("横幅标题已存在");
                return resultDomain;
            }

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

            // 设置默认状态和排序号
            if (banner.getStatus() == null) {
                banner.setStatus(1); // 默认启用
            }
            if (banner.getOrderNum() == null) {
                banner.setOrderNum(0);
            }

            // 插入数据库
            int result = bannerMapper.insertBanner(banner);
            if (result > 0) {
                logger.info("创建横幅成功: {}", banner.getTitle());
                resultDomain.success("创建横幅成功", banner);
                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<TbBanner> updateBanner(TbBanner banner) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (banner == null || !StringUtils.hasText(banner.getID())) {
                resultDomain.fail("横幅ID不能为空");
                return resultDomain;
            }

            // 检查横幅是否存在
            TbBanner existing = bannerMapper.selectById(banner.getID());
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("横幅不存在");
                return resultDomain;
            }

            // 如果修改了标题，检查标题是否已被使用
            if (StringUtils.hasText(banner.getTitle()) && !banner.getTitle().equals(existing.getTitle())) {
                int count = bannerMapper.countByTitle(banner.getTitle(), banner.getID());
                if (count > 0) {
                    resultDomain.fail("横幅标题已存在");
                    return resultDomain;
                }
            }

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

            // 更新数据库
            int result = bannerMapper.updateBanner(banner);
            if (result > 0) {
                logger.info("更新横幅成功: {}", banner.getID());
                // 重新查询返回完整数据
                TbBanner updated = bannerMapper.selectById(banner.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> deleteBanner(String bannerID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(bannerID)) {
                resultDomain.fail("横幅ID不能为空");
                return resultDomain;
            }

            // 查询横幅
            TbBanner banner = bannerMapper.selectByBannerId(bannerID);
            if (banner == null || banner.getDeleted()) {
                resultDomain.fail("横幅不存在");
                return resultDomain;
            }

            // 物理删除
            int result = bannerMapper.deleteBanner(banner);
            if (result > 0) {
                logger.info("删除横幅成功: {}", bannerID);
                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<TbBanner> updateBannerStatus(String bannerID, Integer status) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(bannerID)) {
                resultDomain.fail("横幅ID不能为空");
                return resultDomain;
            }
            if (status == null) {
                resultDomain.fail("状态不能为空");
                return resultDomain;
            }

            // 查询横幅
            TbBanner banner = bannerMapper.selectByBannerId(bannerID);
            if (banner == null || banner.getDeleted()) {
                resultDomain.fail("横幅不存在");
                return resultDomain;
            }

            // 更新状态
            banner.setStatus(status);
            banner.setUpdateTime(new Date());

            int result = bannerMapper.updateBanner(banner);
            if (result > 0) {
                logger.info("更新横幅状态成功: {}", bannerID);
                // 重新查询返回完整数据
                TbBanner updated = bannerMapper.selectById(banner.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<TbBanner> updateBannerOrder(String bannerID, Integer orderNum) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(bannerID)) {
                resultDomain.fail("横幅ID不能为空");
                return resultDomain;
            }
            if (orderNum == null) {
                resultDomain.fail("排序号不能为空");
                return resultDomain;
            }

            // 查询横幅
            TbBanner banner = bannerMapper.selectByBannerId(bannerID);
            if (banner == null || banner.getDeleted()) {
                resultDomain.fail("横幅不存在");
                return resultDomain;
            }

            // 更新排序号
            banner.setOrderNum(orderNum);
            banner.setUpdateTime(new Date());

            int result = bannerMapper.updateBanner(banner);
            if (result > 0) {
                logger.info("更新横幅排序成功: {}", bannerID);
                // 重新查询返回完整数据
                TbBanner updated = bannerMapper.selectById(banner.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
    public ResultDomain<TbBanner> getActiveBanners(Integer limit) {
        ResultDomain<TbBanner> resultDomain = new ResultDomain<>();
        try {
            List<TbBanner> list = bannerMapper.selectActiveBanners();
            
            // 如果指定了limit，截取列表
            if (limit != null && limit > 0 && list != null && list.size() > limit) {
                list = list.subList(0, limit);
            }

            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<Boolean> batchUpdateBannerOrder(Map<String, Integer> bannerOrders) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (bannerOrders == null || bannerOrders.isEmpty()) {
                resultDomain.fail("横幅排序信息不能为空");
                return resultDomain;
            }

            Date now = new Date();
            int successCount = 0;

            for (Map.Entry<String, Integer> entry : bannerOrders.entrySet()) {
                String bannerID = entry.getKey();
                Integer orderNum = entry.getValue();

                if (!StringUtils.hasText(bannerID) || orderNum == null) {
                    continue;
                }

                // 查询横幅
                TbBanner banner = bannerMapper.selectByBannerId(bannerID);
                if (banner == null || banner.getDeleted()) {
                    continue;
                }

                // 更新排序号
                banner.setOrderNum(orderNum);
                banner.setUpdateTime(now);

                int result = bannerMapper.updateBanner(banner);
                if (result > 0) {
                    successCount++;
                }
            }

            if (successCount > 0) {
                logger.info("批量更新横幅排序成功，数量: {}", successCount);
                resultDomain.success("批量更新横幅排序成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("批量更新横幅排序失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("批量更新横幅排序异常: {}", e.getMessage(), e);
            resultDomain.fail("批量更新横幅排序失败: " + e.getMessage());
            return resultDomain;
        }
    }
}
