package com.quantgroup.asset.distribution.service.feature.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import com.quantgroup.asset.distribution.exception.QGPreconditions;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.service.feature.IFeatureService;
import com.quantgroup.asset.distribution.service.httpclient.IHttpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author : Hyuk
 * @description : FeatureServiceImpl
 * @date : 2020/7/15 5:47 下午
 */
@Slf4j
@Service
public class FeatureServiceImpl implements IFeatureService {

    @Value("${rule.engine.url}")
    private String ruleEngineURL;

    @Autowired
    private IHttpService httpService;

    @Override
    public Map<String, Object> getFeatureData(Set<String> keys, AssetForm assetForm, int type) {
        if (CollectionUtils.isEmpty(keys)) { return MapUtils.EMPTY_MAP; }
        Stopwatch stopwatch = Stopwatch.createStarted();
        String result = httpService.post(ruleEngineURL + "/feature/get", new HashMap<String, String>(){{
            put("uuid", assetForm.getUuid());
            put("bizChannel", assetForm.getBizChannel());
            put("bizNo", assetForm.getBizNo());
            put("bizType", assetForm.getBizType());
            put("keys", StringUtils.join(keys, ","));
            put("method", "0");
            put("type", type + "");
            put("exData", assetForm.getExData());
        }});
        JSONObject resultJSON = null;
        QGPreconditions.checkArgument(StringUtils.isNotEmpty(result) && (resultJSON = JSON.parseObject(result)).getInteger("code") == 0, QGExceptionType.GET_DEC_ATTRIBUTE_VALUE_ERROR, assetForm.getUuid(), JSON.toJSONString(keys));
        Map<String, Object > data = resultJSON.getJSONObject("body");
        log.info("决策特征属性获取完成, uuid : {}, assetNo : {}, bizChannel : {}, bizNo : {}, bizType : {}, type : {}, data : {}, 耗时 : {}", assetForm.getUuid(), assetForm.getAssetNo(), assetForm.getBizChannel(), assetForm.getBizNo(), assetForm.getBizType(), type, JSON.toJSONString(data), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
        return data;
    }
}
