package cn.quantgroup.xyqb.event;

import cn.quantgroup.xyqb.entity.Contact;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.UserRegisterParam;
import cn.quantgroup.xyqb.repository.IContactRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 注册成功后, 保存联系人
 *
 * @author ag
 */
@Component
public class ContactRegisteredEventListener implements ApplicationListener<RegisterEvent> {

    @Autowired
    private IContactRepository contactRepository;

    @Override
    public void onApplicationEvent(RegisterEvent event) {
        UserRegisterParam userRegisterParam = event.getUserRegisterParam();
        List<Contact> contactList = userRegisterParam.getContactList();
        User user = userRegisterParam.getUser();
        if (CollectionUtils.isEmpty(contactList)) {
            return;
        }

        contactList.forEach(contact -> contact.setUserId(user.getId()));

        contactRepository.save(contactList);
    }
}
