package cn.quantgroup.xyqb.event;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.model.session.SessionValue;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CacheEvictPhoneNoUpdateEventListener implements ApplicationListener<PhoneNoUpdateEvent> {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISessionService sessionService;

    @Override
    public void onApplicationEvent(PhoneNoUpdateEvent event) {
        String oldPhoneNo = event.getOldPhoneNo();
        User user = event.getUser();

        userService.userCacheEvict(user.getUuid(), oldPhoneNo);

        List<SessionStruct> sessionStructList = sessionService.findByUserId(user.getId());

        sessionStructList = sessionStructList.stream().filter(Objects::nonNull).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(sessionStructList)) {
            return;
        }

        for (SessionStruct sessionStruct : sessionStructList) {
            SessionValue values = sessionStruct.getValues();
            User sessionUser = values.getUser();
            //修改 session 中的手机号
            sessionUser.setPhoneNo(user.getPhoneNo());
            values.setUser(sessionUser);
        }
        sessionService.persistSession(sessionStructList);

    }
}
