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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.setting.entity.OperationPopup;
import com.jeesharp.business.modules.setting.enums.OperationPopupStatusEnum;
import com.jeesharp.business.modules.setting.mapper.OperationPopupMapper;
import com.jeesharp.business.modules.setting.service.OperationPopupService;
import com.jeesharp.business.modules.setting.vo.OperationPopupQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 运营弹窗领域服务实现。
 *
 * @author jeesharp
 * @since 2026-05-13
 */
@Service
@Transactional(readOnly = true)
public class OperationPopupServiceImpl extends CrudService<OperationPopupMapper, OperationPopup, OperationPopupQueryVO>
        implements OperationPopupService {

    private static final String PLATFORM_WECHAT_MINI = "WECHAT_MINI";

    @Override
    public List<OperationPopup> listActiveForWechatMiniHome() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<OperationPopup> w = new LambdaQueryWrapper<>();
        w.eq(OperationPopup::getPlatform, PLATFORM_WECHAT_MINI);
        w.eq(OperationPopup::getStatus, OperationPopupStatusEnum.ENABLED.getValue());
        w.and(
                q -> q.isNull(OperationPopup::getDisplayBegin)
                        .or()
                        .le(OperationPopup::getDisplayBegin, now));
        w.and(
                q -> q.isNull(OperationPopup::getDisplayEnd)
                        .or()
                        .ge(OperationPopup::getDisplayEnd, now));
        w.orderByAsc(OperationPopup::getSortOrder).orderByDesc(OperationPopup::getUpdateDate);
        return this.list(w);
    }

    @Override
    @Transactional(readOnly = false)
    public void createPopup(OperationPopup entity) {
        if (entity.getStatus() == null) {
            entity.setStatus(OperationPopupStatusEnum.ENABLED.getValue());
        }
        if (entity.getSortOrder() == null) {
            entity.setSortOrder(0);
        }
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updatePopup(OperationPopup entity) {
        update(entity);
    }

}
