package org.wfc.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.core.utils.MessageUtils;
import org.wfc.common.security.utils.SecurityUtils;
import org.wfc.user.api.domain.UUser;
import org.wfc.user.api.domain.UKyc;
import org.wfc.user.domain.vo.UKycUserVo;
import org.wfc.user.mapper.UKycMapper;
import org.wfc.user.service.IUKycService;
import org.wfc.user.service.IUUserService;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

/**
 * <p>
 * 用户平台-KYC表 服务实现类
 * </p>
 *
 * @author sys
 * @since 2025-01-08
 */
@Service
public class UKycServiceImpl extends ServiceImpl<UKycMapper, UKyc> implements IUKycService {

    private static final Logger logger = LoggerFactory.getLogger(UKycServiceImpl.class);

    @Autowired
    private UKycMapper  uKycMapper;

    @Autowired
    private IUUserService uUserService;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    // @Override
    // public List<UKycUserVo> selectKycByUserId(Long userId) {
    //     return this.baseMapper.selectKycByUserId(userId);
    // }

    @Override
    public List<UKycUserVo> selectKycByUserId() {
        LoginUser<Object> loginUser = SecurityUtils.getLoginUser();
        return this.uKycMapper.selectKycByUserId(loginUser.getUserid());
    }

    @Override
    public int isExistUserKyc(Long userId) {
        return this.uKycMapper.isExistUserKyc(userId);
    }
    
    @Override
    public int insertUserKyc(UKyc uKyc) {
        logger.debug("uKyc: {}", uKyc);
        LoginUser<Object> loginUser = SecurityUtils.getLoginUser();

        if (uKyc.getUserId() == null) {
            uKyc.setUserId(loginUser.getUserid());
        } else {       
            if (!loginUser.getUserid().equals(uKyc.getUserId())) {
                logger.error("The kyc user(userId={}) is not the logged in user(userId={})", 
                        uKyc.getUserId(), loginUser.getUserid());
                return 0;
            }
        }
        updateUserByKyc(uKyc);
        if (this.uKycMapper.isExistUserKyc(uKyc.getUserId()) == 0) {
            return this.uKycMapper.insertUserKyc(uKyc);
        } else {
            return this.uKycMapper.updateUserKyc(uKyc);
        }
    } 

    @Override
    public int updateUserKyc(UKyc uKyc) {
        LoginUser<Object> loginUser = SecurityUtils.getLoginUser();

        if (uKyc.getUserId() == null) {
            uKyc.setUserId(loginUser.getUserid());
        } else {
            if (!loginUser.getUserid().equals(uKyc.getUserId())) {
                logger.error("The kyc user(userId={}) is not the logged in user(userId={})",
                        uKyc.getUserId(), loginUser.getUserid());
                return 0;
            }
        }
        updateUserByKyc(uKyc);  
        return this.uKycMapper.updateUserKyc(uKyc);
    }       

    /**
     * Updates the user information based on the KYC details.
     * 
     * @param uKyc the KYC details
     * @return the number of rows affected by the update
     * @throws IllegalArgumentException if the birthDate is null or in an invalid format
     */
    private int updateUserByKyc(UKyc uKyc) {
        UUser uUser = uUserService.selectUserById(uKyc.getUserId());
        
        uUser.setFullName(uKyc.getRealName());

        if (uKyc.getBirthDate() == null) {
            throw new IllegalArgumentException(MessageUtils.message("user.kyc.birthdate.not.blank"));
        }
        // Parse birthDate and calculate age
        try {
            LocalDate birthDate = LocalDate.parse(uKyc.getBirthDate(), DATE_FORMATTER);
            uUser.setAge(calculateAge(birthDate));
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException(MessageUtils.message("user.kyc.birthdate.not.valid"));
        }
        return uUserService.updateUser(uUser);
    }

    private int calculateAge(LocalDate birthDate) {
        if (birthDate == null) {
            return 0;
        }
        return Period.between(birthDate, LocalDate.now()).getYears();
    }       
}
