package com.kmall.manager.manager.faceid;

import com.kmall.common.constant.Dict;
import com.kmall.common.utils.JacksonUtils;
import com.kmall.common.utils.MD5Sign;
import com.kmall.common.utils.ResponseData;
import com.kmall.manager.dto.FaceIdRequestDto;
import com.kmall.manager.manager.common.OkHttpUtilss;
import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


/**
 * @author huangyq
 * @version 1.0
 * 2019-11-27 14:30
 */
public class FaceCheckUtil {
    private static Logger loggger = LoggerFactory.getLogger(FaceCheckUtil.class);

    public static ResponseData checkLivenessRecognition(FaceIdRequestDto faceIdRequestDto){
        Map<String,String> sParaTemp = new TreeMap<String, String>();
        sParaTemp.put("idCard", faceIdRequestDto.getIdCard());
        sParaTemp.put("name", faceIdRequestDto.getName());
        sParaTemp.put("videoBase64", faceIdRequestDto.getVideoBase64());
        sParaTemp.put("livenessType", faceIdRequestDto.getLivenessType());
        if(!faceIdRequestDto.getLivenessType().equalsIgnoreCase(Dict.livenessType.item_SILENT.getItem())){
            sParaTemp.put("validateData", faceIdRequestDto.getValidateData());
        }
        sParaTemp.put("merchId", faceIdRequestDto.getMerchId());
        sParaTemp.put("merchName", faceIdRequestDto.getMerchName());
        sParaTemp.put("thirdPartyMerchCode", faceIdRequestDto.getThirdPartyMerchCode());
        sParaTemp.put("thirdPartyMerchName", faceIdRequestDto.getThirdPartyMerchName());
        String params = JacksonUtils.toJson(sParaTemp);

        Map map = new HashMap();
        map.put("data", params);
        map.put("timestamp", System.currentTimeMillis()/1000);
        map.put("merchId", faceIdRequestDto.getMerchId());
        String md5Salt = OmsMerchPropertiesBuilder.instance().getMd5Salt();

        String si = MD5Sign.sign(map, md5Salt);
        map.put("sign",si);
        String requestData = JacksonUtils.toJson(map);
        String response = buildRequestPost(requestData);
        ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
        return responseData;
    }

    private static String buildRequestPost(String requestData){
        String url = OmsMerchPropertiesBuilder.instance().getLivenessRecognitionUrl();
        // 同步访问,返回结果字符串
        Request request = OkHttpUtilss.buildRequest(url,requestData);
        // 同步访问,返回结果字符串
        String response = null;
        try {
            response = OkHttpUtilss.post(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}
