package com.brilliance.isc.common.transaction.newcheck.limmod;

import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.limmod.service.LimmodService;
import com.brilliance.isc.common.limmod.vo.LimgrdVo;
import com.brilliance.isc.common.limmod.vo.LimmodVo;
import com.brilliance.isc.common.transaction.newcheck.AbstractModuleValidator;
import com.brilliance.isc.common.transaction.newcheck.ValidResult;
import com.brilliance.isc.common.transaction.newcheck.Validate;
import com.brilliance.isc.utils.DateUtils;
import com.brilliance.isc.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class LimmodValidator extends AbstractModuleValidator<LimmodVo> {
    @Autowired(required = false)
    private XrtmodService xrtmodService;
    @Autowired(required = false)
    private LimmodService limmodService;

    @Override
    @PostConstruct
    public void register() {
        super.register();
    }

    @Override
    public Map<String, String> validate(LimmodVo vo) {
        Map<String, String> maps = new HashMap<>();
        maps.putAll(super.validate(vo));

        return maps;
    }

    @Validate(path = "limmod.comamt" ,enable = "N")
    public ValidResult checkcomamt(LimmodVo limmodVo) {
//        if (!"1".equals(limmodVo.getLimpts().getQueryFlg())) {
//            return null;
//        }
        if (!limmodService.cL43oPn(limmodVo)||!limmodService.limRegister().needRecalcLimits(limmodVo)) {
            return null;
        }
        //TODO 没有这两个字段
        if ("2".equals(limmodVo.getLimpts().getNonrevflg1())) {
            if (!ObjectUtils.isEmpty(limmodVo.getComamt())) {
                for (LimgrdVo limgrdVo : limmodVo.getLimQueryVo().getLimgrdVoList()) {
                    if ("X".equals(limgrdVo.getFlg())) {
                        //可用额度折人名币
                        BigDecimal kyedu = xrtmodService.amtConvTypes(StringUtils.isEmpty(limgrdVo.getCur())?limgrdVo.getLimcur():limgrdVo.getCur(), limgrdVo.getBalamt(), "M", "CNY", "M", DateUtils.getNowDate());
                        //业务金额折人名币
                        BigDecimal comamt = xrtmodService.amtConvTypes(limmodVo.getCur(), limmodVo.getComamt(), "M", "CNY", "M", DateUtils.getNowDate());

                        if(!"Y".equals(limmodVo.getLmaflg())){
                            continue;
                        }
                        if (comamt.compareTo(kyedu) > 0) {
                            return ValidResult.build(false, "业务金额不能大于产品可用额度");
                        }
                    }
                }
            }
        }

        return null;
    }

}
