package com.quantgroup.asset.distribution.service.newrule.common;

import com.quantgroup.asset.distribution.constant.CommonConstants;
import com.quantgroup.asset.distribution.service.feature.IFeatureService;
import com.quantgroup.asset.distribution.service.feature.bo.IdCardInfo;
import com.quantgroup.asset.distribution.service.newrule.pojo.enums.IdCardExpireEnum;
import com.quantgroup.asset.distribution.service.newrule.pojo.enums.SpecialRuleEnum;
import com.quantgroup.asset.distribution.service.newrule.pojo.funds.RuleParam;
import com.quantgroup.asset.distribution.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author shihuajun
 * @date 2021/9/6 20:04
 * @ describing
 */
@Slf4j
@Component("commonIdCardVerifyImpl")
public class IdCardVerifyImpl extends AbstractProductRuleVerifyImpl{

    private static final Integer YEAR = 365;

    @Resource
    private IFeatureService featureService;

    @Override
    public boolean pass(RuleParam param) {
        IdCardInfo idCardInfo = featureService.getIdCardInfo(param.getUuid());
        String validDateEnd = idCardInfo.getValid_date_end();
        if (StringUtils.isBlank(validDateEnd)){
            throw new RuntimeException("从第三方服务获取的身份证valid_date_end结束日期有问题");
        }
        if (IdCardExpireEnum.CURRENT.equals(param.getCardExpireEnum())){
            return DateUtil.between(idCardInfo.getValid_date_begin(),validDateEnd);
        }else if (IdCardExpireEnum.EXPIRE_BIG_ONE.equals(param.getCardExpireEnum())){
            return calcTermValidity(validDateEnd) >= 1;
        }else if (IdCardExpireEnum.EXPIRE_BIG_LOAN.equals(param.getCardExpireEnum())){
            String dateEnd = validDateEnd.substring(0,4) + CommonConstants.HORIZONTAL_LINE +
                    validDateEnd.substring(4,6) + CommonConstants.HORIZONTAL_LINE + validDateEnd.substring(6,8);
            int monthDiff = DateUtil.getMonthDiff(DateUtil.getDay(), dateEnd);
            return monthDiff > Integer.parseInt(param.getAuditResponce().getTerm());
        }
        return false;
    }

    @Override
    public SpecialRuleEnum specialRuleName() {
        return SpecialRuleEnum.ID_CARD_VERIFY;
    }

    private int calcTermValidity(String data){
        Date date = new Date(Integer.parseInt(data.substring(0,4)) - 1900 ,
                Integer.parseInt(data.substring(4,6)) - 1,
                Integer.parseInt(data.substring(6,8)));
        int days = DateUtil.getDays(date);
        return days / YEAR;
    }
}
