package com.ichangzuo.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ichangzuo.system.mapper.NoticeMapper;
import com.ichangzuo.system.model.entity.Notice;
import com.ichangzuo.system.model.query.NoticePageQuery;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> {
    public IPage<Notice> listPage(NoticePageQuery queryParams) {
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<Notice> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Notice> lqw = new LambdaQueryWrapper<>();
        Integer state = queryParams.getState();
        if(state!=null) {
            lqw.eq(Notice::getState, state);
        }

        lqw.orderByDesc(Notice::getNoticeId);

        return baseMapper.selectPage(page, lqw);
    }

    public boolean saveNotice(Notice notice){
        Integer id = notice.getNoticeId();
        if(id==null){
            notice.setReleaseTime((int) (System.currentTimeMillis()/1000));
        }

        return saveOrUpdate(notice);
    }

    public boolean setByIds(String idsStr, Integer set){
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "消息号列表为空");
        List<Integer> ids = Arrays.stream(idsStr.split(","))
                .map(Integer::parseInt)
                .toList();
        Integer now = (int) (System.currentTimeMillis()/1000);
        boolean result = true;

        for(Integer id: ids){
            result = update(new LambdaUpdateWrapper<Notice>()
                    .eq(Notice::getNoticeId, id)
                    .set(Notice::getState, set)
                    .set(set==0 ? Notice::getReleaseTime : Notice::getShieldTime, now));

            if(!result) break;
        }
        return result;
    }
}
