package com.jeesharp.business.modules.setting.service.impl;

import com.jeesharp.business.modules.common.enums.DisabledEnabledEnum;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.setting.entity.CmsHomeBanner;
import com.jeesharp.business.modules.setting.enums.HomeBannerPlatformEnum;
import com.jeesharp.business.modules.setting.enums.HomeBannerPositionEnum;

import com.jeesharp.business.modules.setting.mapper.HomeBannerMapper;
import com.jeesharp.business.modules.setting.service.HomeBannerService;
import com.jeesharp.business.modules.setting.vo.HomeBannerQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 首页轮播领域服务实现。
 *
 * @author jeesharp
 * @since 2026-05-08
 */
@Service
@Transactional(readOnly = true)
public class HomeBannerServiceImpl extends CrudService<HomeBannerMapper, CmsHomeBanner, HomeBannerQueryVO> implements HomeBannerService {

    @Override
    @Transactional(readOnly = false)
    public void createHomeBanner(CmsHomeBanner entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateHomeBanner(CmsHomeBanner entity) {
        update(entity);
    }

    @Override
    public List<CmsHomeBanner> listEnabledForPortal(String platform, String bannerPosition) {
        if (platform == null || platform.isBlank()) {
            return List.of();
        }
        String p = platform.trim();
        String pos = bannerPosition != null && !bannerPosition.isBlank()
            ? bannerPosition.trim()
            : HomeBannerPositionEnum.HOME.getValue();
        LambdaQueryWrapper<CmsHomeBanner> w = new LambdaQueryWrapper<>();
        w.eq(CmsHomeBanner::getDelFlag, "0");
        w.eq(CmsHomeBanner::getStatus, DisabledEnabledEnum.ENABLED.getValue());
        w.and(q -> q.eq(CmsHomeBanner::getPlatform, HomeBannerPlatformEnum.ALL.getValue()).or().eq(CmsHomeBanner::getPlatform, p));
        // 首页：兼容升级前 banner_position 为空、或与 HOME 语义一致的历史数据
        if (HomeBannerPositionEnum.HOME.getValue().equalsIgnoreCase(pos)) {
            w.and(q -> q.eq(CmsHomeBanner::getBannerPosition, HomeBannerPositionEnum.HOME.getValue())
                .or()
                .isNull(CmsHomeBanner::getBannerPosition)
                .or()
                .eq(CmsHomeBanner::getBannerPosition, ""));
        } else {
            w.eq(CmsHomeBanner::getBannerPosition, pos);
        }
        w.orderByDesc(CmsHomeBanner::getSortOrder);
        w.orderByDesc(CmsHomeBanner::getCreateDate);
        return list(w);
    }
}
