//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.hand.app.esignHclc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hand.app.esign.service.ISignInfoService;
import com.hand.app.esign.utils.AlgorithmHelper;
import com.hand.app.esignHclc.dto.SignInfoHclc;
import com.hand.app.esignHclc.dto.SignInfoHclcFace;
import com.hand.app.esignHclc.service.ISignInfoHclcFaceService;
import com.hand.app.esignHclc.service.ISignInfoHclcService;
import com.hand.app.esignHclc.utils.SignHclcUtils;
import com.hand.hap.core.IRequest;
import com.hand.hap.intergration.dto.HapInterfaceHeader;
import com.hand.hap.intergration.service.IHapInterfaceHeaderService;
import com.hand.hap.system.service.impl.BaseServiceImpl;
import hls.support.core.wechat.formbean.AttachmentInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.CharsetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SignInfoHclcServiceImpl extends BaseServiceImpl<SignInfoHclc> implements ISignInfoHclcService {
    @Value("${tsign.project.id}")
    private String projectId;
    @Value("${tsign.project.secret}")
    private String projectSecret;
    @Value("${tsign.api.notifyUrl}")
    private String notifyUrl;
    @Value("${tsign.face.api.appId}")
    private String appId;
    @Value("${tsign.face.api.secret}")
    private String secret;
    @Value("${wx.apiKey}")
    private String apiKey;
    @Value("${wx.image.path}")
    private String imagePath;
    private CloseableHttpClient httpClient;
    public static final String RESULT_ERROR = "-1";
    public static final String indivSysName = "HCLC_FACE_API";
    public static final String tokenApiName = "getToken";
    public static final String indivApiName = "indivAuthUrl";
    public static final String downLoadSysName = "wxgzh_hitachics";
    public static final String downLoadApiName = "media_download";
    public static final String upLoadSysName = "HCL_UPLOAD_FILE";
    public static final String upLoadApiName = "upload";
    public static final String signatureSysName = "HCLC_ELECTRONIC_SIGNATURE";
    public static final String accountsApiName = "outerAccounts";
    private static final String HASH_ALGORITHM = "HmacSHA256";
    @Autowired
    IHapInterfaceHeaderService headerService;
    @Autowired
    private ISignInfoHclcFaceService signInfoHclcFaceService;
    @Autowired
    private ISignInfoService ISignInfoService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public SignInfoHclcServiceImpl() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public Map<String, Object> getIndividualFaceUrl(IRequest iRequest, SignInfoHclc info) {
        Map<String, Object> map = new HashMap();
        if (Objects.isNull(info.getOpenId())) {
            this.logger.error("关键参数openid不存在，调用失败!");
            ((Map)map).put("success", "false");
            ((Map)map).put("message", "关键参数openid不存在，调用失败!");
            return (Map)map;
        } else {
            SignInfoHclc signInfoHclc = (SignInfoHclc)this.mapper.selectByPrimaryKey(info);
            if (Objects.isNull(signInfoHclc)) {
                info.setFaceauthStatus("NEW");
                info.setCtitype(1L);
                info.setBindFlag("0");
                signInfoHclc = (SignInfoHclc)this.insertSelective(iRequest, info);
            } else {
                if (signInfoHclc.getFaceauthStatus().equalsIgnoreCase("SUCCESS")) {
                    ((Map)map).put("success", "false");
                    ((Map)map).put("message", "人脸核身认证已完成，无需重复验证！");
                    return (Map)map;
                }

                signInfoHclc.setIdNo(info.getIdNo());
                signInfoHclc.setName(info.getName());
                signInfoHclc.setRedirectUrl(info.getRedirectUrl());
                signInfoHclc = (SignInfoHclc)this.updateByPrimaryKey(iRequest, signInfoHclc);
            }

            String tokenApiUrl = this.getApiUrl("HCLC_FACE_API", "getToken");
            this.logger.debug("upload url: {}", tokenApiUrl);
            SignHclcUtils signHclcUtils = new SignHclcUtils();
            signInfoHclc = SignHclcUtils.initProject(signInfoHclc, this.appId, this.secret, this.notifyUrl);
            String token = signHclcUtils.getFaceApiToken(tokenApiUrl, signInfoHclc.getAppId(), signInfoHclc.getSecret());
            if (Objects.nonNull(token)) {
                map = this.getFaceUrlHttp(iRequest, signInfoHclc, token);
            } else {
                ((Map)map).put("code", "1");
                ((Map)map).put("message", "获取鉴权Token失败，请检查！");
            }

            return (Map)map;
        }
    }

    public String getApiUrl(String sysName, String apiName) {
        HapInterfaceHeader headerAndLineDTO = this.headerService.getHeaderAndLine(sysName, apiName);
        if (headerAndLineDTO == null) {
            this.logger.debug("headerAndLineDTO is null， apiName:{}, sysName:{}", apiName, sysName);
            return null;
        } else {
            return headerAndLineDTO.getDomainUrl() + headerAndLineDTO.getIftUrl();
        }
    }

    public Map<String, Object> getFaceUrlHttp(IRequest iRequest, SignInfoHclc info, String token) {
        Map<String, Object> map = new HashMap();
        String faceApiurl = this.getApiUrl("HCLC_FACE_API", "indivAuthUrl");
        this.logger.debug("upload url: {}", faceApiurl);
        SignInfoHclcFace signInfoHclcFace = new SignInfoHclcFace();
        signInfoHclcFace.setOpenId(info.getOpenId());
        signInfoHclcFace.setAuthStatus("NEW");
        signInfoHclcFace.setAuthType("1");
        signInfoHclcFace = (SignInfoHclcFace)this.signInfoHclcFaceService.insertSelective(iRequest, signInfoHclcFace);
        JSONObject json1 = new JSONObject();
        json1.put("contextId", signInfoHclcFace.getFaceauthId());
        json1.put("notifyUrl", info.getNotifyUrl());
        json1.put("redirectUrl", info.getRedirectUrl());
        JSONObject json2 = new JSONObject();
        json2.put("name", info.getName());
        json2.put("certNo", info.getIdNo());
        json2.put("mobileNo", info.getMobile());
        JSONObject result = new JSONObject();
        result.put("authType", "PSN_FACEAUTH_BYURL");
        result.put("contextInfo", json1);
        result.put("indivInfo", json2);
        JSONObject json = new JSONObject(result);
        String param = json.toString();
        Map<String, String> headInfo = new HashMap();
        headInfo.put("X-Tsign-Open-App-Id", info.getAppId());
        headInfo.put("X-Tsign-Open-Token", token);

        try {
            SignHclcUtils signHclcUtils1 = new SignHclcUtils();
            String stringResult = signHclcUtils1.postString(faceApiurl, param, headInfo);
            net.sf.json.JSONObject jsonResult = net.sf.json.JSONObject.fromObject(stringResult);
            if (jsonResult.get("code").toString().equalsIgnoreCase("0")) {
                net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(jsonResult.get("data"));
                signInfoHclcFace.setFlowId(data.getString("flowId"));
                signInfoHclcFace.setUrl(data.getString("url"));
                signInfoHclcFace.setShortLink(data.getString("shortLink"));
                map.put("code", "0");
                map.put("url", data.getString("url"));
                map.put("message", "获取url成功！");
            } else {
                map.put("code", "2");
                map.put("message", "获取人脸核身认证地址失败，请检查！");
            }

            signInfoHclcFace.setReturnCode(jsonResult.get("code").toString());
            signInfoHclcFace.setReturnMessage(jsonResult.get("message").toString());
        } catch (Exception var17) {
            map.put("code", "3");
            map.put("message", "访问e签宝人脸核身地址失败，请检查！");
            signInfoHclcFace.setReturnCode("3");
            signInfoHclcFace.setReturnMessage(var17.getMessage());
        }

        this.signInfoHclcFaceService.updateByPrimaryKey(iRequest, signInfoHclcFace);
        return map;
    }

    public JSONObject uploadHlsFromWx(IRequest iRequest, AttachmentInfo attachmentInfo) {
        JSONObject json = null;
        if (Objects.isNull(attachmentInfo.getMediaId())) {
            this.logger.error("upload attachment failed, attachmentInfo:{} 关键参数mediaId不存在，调用失败!", JSON.toJSONString(attachmentInfo));
            json.put("code", "3");
            json.put("message", "关键参数mediaId不存在，调用失败");
            return json;
        } else {
            SignInfoHclc signInfoHclc = new SignInfoHclc();
            signInfoHclc.setOpenId(attachmentInfo.getOpenId());
            signInfoHclc.setMediaId(attachmentInfo.getMediaId());
            signInfoHclc = (SignInfoHclc)this.updateByPrimaryKeySelective(iRequest, signInfoHclc);

            try {
                String tomcatPath = this.imagePath;
                AttachmentInfo downloadInfo = new AttachmentInfo();
                downloadInfo.setUploadSysName("wxgzh_hitachics");
                downloadInfo.setUploadApiName("media_download");
                downloadInfo.setMediaId(attachmentInfo.getMediaId());
                tomcatPath = this.downloadFile(downloadInfo, tomcatPath);
                if (!tomcatPath.equalsIgnoreCase("-1")) {
                    SignHclcUtils signHclcUtils = new SignHclcUtils();
                    json = signHclcUtils.idcard(tomcatPath);
                    json.put("code", "0");
                    attachmentInfo.setUserId("admin");
                    attachmentInfo.setUploadSysName("HCL_UPLOAD_FILE");
                    attachmentInfo.setUploadApiName("upload");
                    attachmentInfo.setPkValue(attachmentInfo.getOpenId());
                    String attchmentId = this.uploadFile(tomcatPath, attachmentInfo);
                    if (Objects.nonNull(attchmentId)) {
                        signInfoHclc.setAttachmentId(attchmentId);
                        this.updateByPrimaryKeySelective(iRequest, signInfoHclc);
                    }

                    json.put("attchmentId", attchmentId);
                } else {
                    json.put("code", "1");
                    json.put("message", "获取服务器图片失败,OCR识别失败");
                }

                return json;
            } catch (Exception var9) {
                this.logger.error("upload attachment failed, attachmentInfo:{}", JSON.toJSONString(attachmentInfo), var9);
                json.put("code", "2");
                json.put("message", var9.getMessage());
                return json;
            }
        }
    }

    public String downloadFile(AttachmentInfo info, String filePath) throws IOException {
        JSONObject parameters = new JSONObject();
        parameters.put("apiKey", this.apiKey);
        parameters.put("mediaId", info.getMediaId());
        String url = this.getApiUrl(info.getUploadSysName(), info.getUploadApiName());
        this.logger.debug("upload url: {}", url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept", "application/json");
        StringEntity se = new StringEntity(parameters.toString(), "utf-8");
        se.setContentType("text/json");
        httpPost.setEntity(se);

        try {
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            filePath = filePath + File.separator + info.getFileName();
            OutputStream outputStream = new FileOutputStream(filePath);
            int len = true;
            byte[] bytes = new byte[1024];

            int len;
            while((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return filePath;
        } catch (IOException var13) {
            this.logger.error("获取服务器图片失败，msg:{}", var13.getMessage());
            var13.printStackTrace();
            return "-1";
        }
    }

    public String uploadFile(String filePath, AttachmentInfo info) {
        this.logger.debug("params,filePath:{}, attachmentInfo:{}", filePath, JSON.toJSONString(info));
        if (filePath != null && info != null && !StringUtils.isBlank(info.getPkValue()) && !StringUtils.isBlank(info.getSourceType())) {
            String url = this.getApiUrl(info.getUploadSysName(), info.getUploadApiName());
            this.logger.debug("upload url: {}", url);
            HttpPost httpPost = new HttpPost(url);
            StringBody pkValue = new StringBody(info.getPkValue(), ContentType.MULTIPART_FORM_DATA);
            StringBody userId = new StringBody(info.getUserId(), ContentType.MULTIPART_FORM_DATA);
            StringBody sourceType = new StringBody(info.getSourceType(), ContentType.MULTIPART_FORM_DATA);
            ContentType pdfType = ContentType.create("image/jpeg", Consts.UTF_8);

            try {
                File file = new File(filePath);
                HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart("pkvalue", pkValue).addPart("user_id", userId).addPart("source_type", sourceType).addBinaryBody("file", file, pdfType, info.getFileName()).setCharset(CharsetUtils.get("utf-8")).build();
                httpPost.setEntity(entity);
                CloseableHttpResponse response = this.httpClient.execute(httpPost);
                InputStream content = response.getEntity().getContent();
                String result = IOUtils.toString(content);
                return StringUtils.equals("-1", result) ? null : result;
            } catch (IOException var14) {
                this.logger.error("upload attachment failed, attachmentInfo:{}", JSON.toJSONString(info), var14);
                return null;
            }
        } else {
            return null;
        }
    }

    public Map<String, Object> addPersonAccount(IRequest iRequest, String openId) {
        Map<String, Object> map = new HashMap();
        SignInfoHclc signInfoHclc = new SignInfoHclc();
        signInfoHclc.setOpenId(openId);
        signInfoHclc = (SignInfoHclc)this.mapper.selectByPrimaryKey(signInfoHclc);
        if (Objects.nonNull(signInfoHclc.getAccountId())) {
            this.logger.debug("e签宝用户 accountId: {} 已创建，无需重复创建！", signInfoHclc.getAccountId());
            map.put("code", "1");
            map.put("message", "e签宝用户已创建，无需重复创建！");
            return map;
        } else {
            JSONObject result = new JSONObject();
            result.put("cardNo", "");
            result.put("contactsEmail", "");
            result.put("contactsMobile", signInfoHclc.getMobile());
            result.put("licenseNumber", signInfoHclc.getIdNo());
            result.put("licenseType", "IDCard");
            result.put("loginEmail", "");
            result.put("loginMobile", signInfoHclc.getMobile());
            result.put("name", signInfoHclc.getName());
            result.put("uniqueId", signInfoHclc.getOpenId());
            JSONObject json = new JSONObject(result);
            String param = json.toString();
            AlgorithmHelper algorithmHelper = new AlgorithmHelper();
            String EncryptedString = AlgorithmHelper.getXtimevaleSignature(param, this.projectSecret, "HmacSHA256", "UTF-8");
            Map<String, String> headInfo = new HashMap();
            headInfo.put("x-timevale-project-id", this.projectId);
            headInfo.put("x-timevale-signature", EncryptedString);

            try {
                String url = this.getApiUrl("HCLC_ELECTRONIC_SIGNATURE", "outerAccounts");
                this.logger.debug("upload url: {}", url);
                SignHclcUtils signHclcUtils1 = new SignHclcUtils();
                String stringResult = signHclcUtils1.postString(url, param, headInfo);
                net.sf.json.JSONObject jsonResult = net.sf.json.JSONObject.fromObject(stringResult);
                if (jsonResult.get("errCode").toString().equalsIgnoreCase("0")) {
                    net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(jsonResult.get("data"));
                    signInfoHclc.setAccountId(data.getString("accountId"));
                    map.put("code", "0");
                    map.put("message", "用户创建成功！");
                } else {
                    this.logger.error("create person account failed, errCode:{} ,msg:{}", jsonResult.get("errCode").toString(), jsonResult.get("msg").toString());
                    map.put("code", jsonResult.get("errCode").toString());
                    map.put("message", jsonResult.get("msg").toString());
                }

                signInfoHclc.setCreateCode(jsonResult.get("code").toString());
                signInfoHclc.setCreateMessage(jsonResult.get("message").toString());
            } catch (Exception var16) {
                this.logger.error("create person account failed, msg:{}", var16.getMessage());
                map.put("code", "2");
                map.put("message", "用户创建成功失败，请检查！" + var16.getMessage());
                signInfoHclc.setCreateCode("2");
                signInfoHclc.setCreateMessage(var16.getMessage());
            }

            this.updateByPrimaryKey(iRequest, signInfoHclc);
            return map;
        }
    }
}
