package cn.quantgroup.xyqb.event;

import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.UserHashMapping;
import cn.quantgroup.xyqb.entity.UserHashPhoneNoIdNoMapping;
import cn.quantgroup.xyqb.repository.IUserHashMappingRepository;
import cn.quantgroup.xyqb.repository.IUserHashPhoneNoIdNoMappingRepository;
import cn.quantgroup.xyqb.util.encrypt.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.PersistenceException;


/**
 * userDetail 更新时, 保存 hashMapping 数据
 */
@Slf4j
@Component
public class UserDetailHashEventListener implements ApplicationListener<UserDetailUpdateEvent> {

    @Autowired
    private IUserHashMappingRepository userHashMappingRepository;
    @Resource
    private IUserHashPhoneNoIdNoMappingRepository userHashPhoneNoIdNoMappingRepository;

    @Override
    public void onApplicationEvent(UserDetailUpdateEvent event) {
        log.info("onApplicationEvent cn.quantgroup.xyqb.event.UserDetailHashEventListener start");
        UserDetail userDetail = event.getUserDetail();

        UserHashMapping userHashMapping = userHashMappingRepository.findByUserId(userDetail.getUserId());

        //如果不存在, 我先保存一下
        if (userHashMapping == null) {
            userHashMapping = new UserHashMapping(userDetail.getUserId());
        }

        //可能存在手机号修改. 搞一下.
        String phoneNo = userDetail.getPhoneNo();
        userHashMapping.setPhoneNoMd5(Md5Util.build(phoneNo));

        //可能存在身份证号修改. 搞一下.
        String idNo = userDetail.getIdNo().toUpperCase();
        userHashMapping.setIdNoMd5(Md5Util.build(idNo));
        try {
            userHashMappingRepository.save(userHashMapping);
        } catch (PersistenceException e) {
        	// 可能与RegisterEvent并发写入问题，暂不优化
            log.warn("保存userHashMapping重复, 无需再保存, userId:{}", userDetail.getUserId());
        }

        UserHashPhoneNoIdNoMapping userHashPhoneNoIdNoMapping = userHashPhoneNoIdNoMappingRepository.findByUserId(userDetail.getUserId());

        //如果不存在, 我先保存一下
        if (userHashPhoneNoIdNoMapping == null) {
            userHashPhoneNoIdNoMapping = new UserHashPhoneNoIdNoMapping(userDetail.getUserId());
        }

        //可能存在手机号、身份证号修改. 搞一下.
        String phoneNoIdNoMd5 = (userDetail.getPhoneNo() + userDetail.getIdNo()).toUpperCase();
        userHashPhoneNoIdNoMapping.setPhoneNoIdNoMd5(Md5Util.build(phoneNoIdNoMd5));

        try {
            userHashPhoneNoIdNoMappingRepository.save(userHashPhoneNoIdNoMapping);
        } catch (PersistenceException e) {
            log.error("保存userHashPhoneNoIdNoMapping重复, 无需再保存, userId:{}", userDetail.getUserId());
        }
    }
}
