package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.HomeBanner;
import com.zhentao.mapper.HomeBannerMapper;
import com.zhentao.service.HomeBannerService;
import com.zhentao.vo.HomeBannerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页轮播图服务实现类
 */
@Service
public class HomeBannerServiceImpl implements HomeBannerService {
    
    @Autowired
    private HomeBannerMapper homeBannerMapper;
    
    /**
     * 获取启用中的轮播图列表
     */
    @Override
    public List<HomeBannerVO> getActiveBanners() {
        LocalDateTime now = LocalDateTime.now();
        
        // 查询启用状态的轮播图，并在有效时间范围内
        QueryWrapper<HomeBanner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                    .and(wrapper -> wrapper
                        .isNull("start_time")
                        .or()
                        .le("start_time", now))
                    .and(wrapper -> wrapper
                        .isNull("end_time")
                        .or()
                        .ge("end_time", now))
                    .orderByAsc("sort_order");
        
        List<HomeBanner> bannerList = homeBannerMapper.selectList(queryWrapper);
        
        // 转换为VO
        return bannerList.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    /**
     * 转换为VO
     */
    private HomeBannerVO convertToVO(HomeBanner banner) {
        HomeBannerVO vo = new HomeBannerVO();
        vo.setId(banner.getBannerId());
        vo.setName(banner.getTitle());
        vo.setSubtitle(banner.getSubtitle());
        vo.setCoverImage(banner.getImageUrl());
        vo.setTargetId(banner.getTargetId());
        vo.setLinkUrl(banner.getLinkUrl());
        vo.setSortOrder(banner.getSortOrder());
        
        // 转换类型
        String type = "";
        switch (banner.getBannerType()) {
            case 1:
                type = "activity";
                break;
            case 2:
                type = "course";
                break;
            case 3:
                type = "case";
                break;
            case 4:
                type = "link";
                break;
            default:
                type = "activity";
        }
        vo.setType(type);
        
        return vo;
    }
}


