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

import cn.quantgroup.tech.util.TechEnvironment;
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.feature.bo.IdCardInfo;
import com.quantgroup.asset.distribution.service.httpclient.IHttpService;
import com.quantgroup.asset.distribution.util.JacksonUtil;
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.*;
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;

    @Value("${auth.https}")
    private String authUrl;

    @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;
    }

    @Override
    public IdCardInfo getIdCardInfo(String uuid) {
        if (StringUtils.isBlank(uuid)){
            throw new RuntimeException("获取身份证信息参数为空");
        }
        //todo remove
        if (!TechEnvironment.isPro()) {
            IdCardInfo info = new IdCardInfo();
            info.setValid_date_begin("20170901");
            info.setValid_date_end("20370901");
            return info;
        }
        Map<String,String> map = new HashMap<>();
        map.put("uuid", uuid);
        String responce = httpService.post(authUrl.concat("/auth-center/ex/phone/getOcrReturnResult.json"), map);
        List<IdCardInfo> idCardInfoList = JacksonUtil.deserializeList(responce, IdCardInfo.class);
        Optional<IdCardInfo> cardInfo = idCardInfoList.stream().filter(d -> d.getSide().equals("back")).findFirst();
        if (!cardInfo.isPresent()){
            throw new RuntimeException("调用第三方服务返回有问题");
        }
        return cardInfo.get();
    }
}
