package cn.quantgroup.xyqb.event;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.UserRegisterParam;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.util.ValidationUtil;

@Slf4j
@Component
public class DetailRegisteredEventListener implements ApplicationListener<RegisterEvent> {

    @Resource
    private IIdCardService idCardService;
    @Resource
    private IUserDetailService userDetailService;

    @Override
    public void onApplicationEvent(RegisterEvent event) {
        UserRegisterParam userRegisterParam = event.getUserRegisterParam();
        User user = userRegisterParam.getUser();

        if (StringUtils.isAnyBlank(userRegisterParam.getIdNo(), userRegisterParam.getName()) ||
                !ValidationUtil.validateChinese(userRegisterParam.getName())) {
            return;
        }
        String phoneNo = userRegisterParam.getPhoneNo();
        String name = userRegisterParam.getName();
        String idNo = userRegisterParam.getIdNo();
        IdCardInfo cardInfo = idCardService.getIdCardInfo(idNo);
        if (cardInfo == null || !cardInfo.isValid()) {
            log.info("用户身份证号验证失败,userId:{},idNo:{}", user.getId(), idNo);
            return;
        }
        UserDetail userDetail = new UserDetail();
        userDetail.setIdNo(cardInfo.getIdNo());
        userDetail.setPhoneNo(phoneNo);
        userDetail.setName(name);
        userDetail.setIdType(IdType.ID_CARD);
        userDetail.setUserId(user.getId());
        userDetail.setGender(cardInfo.getGender());
        log.info("DetailRegisteredEventListener saveUserDetail, userId:{}, phoneNo:{}, name:{}", user.getId(), phoneNo, name);
        userDetailService.saveUserDetail(userDetail);
    }
}
