package com.mortals.xhx.module.notice.service.impl;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.notice.dao.NoticeDao;
import com.mortals.xhx.module.notice.model.NoticeEntity;
import com.mortals.xhx.module.notice.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import com.mortals.xhx.module.notice.model.NoticeRoomEntity;
import com.mortals.xhx.module.notice.model.NoticeRoomQuery;
import com.mortals.xhx.module.notice.service.NoticeRoomService;
import org.springframework.util.ObjectUtils;
import java.util.Date;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* NoticeService
* 通知公告 service实现
*
* @author zxfei
* @date 2023-09-04
*/
@Service("noticeService")
@Slf4j
public class NoticeServiceImpl extends AbstractCRUDServiceImpl<NoticeDao, NoticeEntity, Long> implements NoticeService {
    @Autowired
    private NoticeRoomService noticeRoomService;
    
    @Override
    protected void saveAfter(NoticeEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getNoticeRoomList())){
            entity.getNoticeRoomList().stream().peek(item->{
                item.setNoticeId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
            }).count();
            noticeRoomService.save(entity.getNoticeRoomList());
        }
        super.saveAfter(entity, context);
    }

    @Override
    protected void updateAfter(NoticeEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getNoticeRoomList())){
            Long[] noticeRoomIds = noticeRoomService.find(new NoticeRoomQuery().noticeId(entity.getId())).stream().map(NoticeRoomEntity::getId).toArray(Long[]::new);
            noticeRoomService.remove(noticeRoomIds,context);
            entity.getNoticeRoomList().stream().peek(item ->{
                item.setNoticeId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
                item.setUpdateUserId(this.getContextUserId(context));
                item.setUpdateTime(new Date());
            }).count();
            noticeRoomService.save(entity.getNoticeRoomList());
        }
        super.updateAfter(entity, context);
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        List<NoticeRoomEntity> noticeRoomlist = noticeRoomService.find(new NoticeRoomQuery().noticeIdList(Arrays.asList(ids)));
        noticeRoomService.removeList(noticeRoomlist,context);
        super.removeAfter(ids, context, result);
    }
}