//
// 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.JSONObject;
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.IOrganSignInfoHclcService;
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.service.IHapInterfaceHeaderService;
import com.hand.hap.system.service.impl.BaseServiceImpl;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
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 OrganSignInfoHclcServiceImpl extends BaseServiceImpl<SignInfoHclc> implements IOrganSignInfoHclcService {
    @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;
    @Autowired
    private ISignInfoHclcFaceService signInfoHclcFaceService;
    @Autowired
    private ISignInfoHclcService iSignInfoHclcService;
    public static final String indivSysName = "HCLC_FACE_API";
    public static final String tokenApiName = "getToken";
    public static final String orgApiName = "orgAuthUrl";
    public static final String signatureSysName = "HCLC_ELECTRONIC_SIGNATURE";
    public static final String organsApiName = "outerAccounts";
    private static final String HASH_ALGORITHM = "HmacSHA256";
    @Autowired
    IHapInterfaceHeaderService headerService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public OrganSignInfoHclcServiceImpl() {
    }

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

                signInfoHclc.setIdNo(info.getIdNo());
                signInfoHclc.setName(info.getName());
                signInfoHclc.setLegalIdNo(info.getLegalIdNo());
                signInfoHclc.setLegalName(info.getLegalName());
                signInfoHclc.setAgentType(info.getAgentType());
                signInfoHclc.setRedirectUrl(info.getRedirectUrl());
                signInfoHclc = (SignInfoHclc)this.updateByPrimaryKey(iRequest, signInfoHclc);
            }

            String tokenApiUrl = this.iSignInfoHclcService.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)) {
                mapOrgan = this.getOrgAuthUrlHttp(iRequest, signInfoHclc, token);
                if (((Map)mapOrgan).get("code").toString().equalsIgnoreCase("0") && !signInfoHclc.getFaceauthStatus().equalsIgnoreCase("SUCCESS")) {
                    new HashMap();
                    SignInfoHclc signInfo = new SignInfoHclc();
                    signInfo = SignHclcUtils.initProject(signInfo, this.appId, this.secret, this.notifyUrl);
                    signInfo.setOpenId(signInfoHclc.getOpenId());
                    signInfo.setIdNo(signInfoHclc.getLegalIdNo());
                    signInfo.setName(signInfoHclc.getLegalName());
                    signInfo.setRedirectUrl(((Map)mapOrgan).get("url").toString());
                    Map<String, Object> mapFace = this.iSignInfoHclcService.getFaceUrlHttp(iRequest, signInfo, token);
                    if (!mapFace.get("code").toString().equalsIgnoreCase("0")) {
                        return mapFace;
                    }

                    ((Map)mapOrgan).put("url", mapFace.get("url"));
                }
            } else {
                ((Map)mapOrgan).put("code", "1");
                ((Map)mapOrgan).put("message", "获取鉴权Token失败，请检查！");
            }

            return (Map)mapOrgan;
        }
    }

    public Map<String, Object> getOrgAuthUrlHttp(IRequest iRequest, SignInfoHclc info, String token) {
        SignInfoHclcFace signInfoHclcFace = new SignInfoHclcFace();
        signInfoHclcFace.setOpenId(info.getOpenId());
        signInfoHclcFace.setAuthStatus("NEW");
        signInfoHclcFace.setAuthType("2");
        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("certType", "ORGANIZATION_USC_CODE");
        json2.put("legalRepCertNo", info.getLegalIdNo());
        json2.put("egalRepCertType", "INDIVIDUAL_CH_IDCARD");
        json2.put("legalRepName", info.getLegalName());
        json2.put("legalRepNationality", "");
        json2.put("operatorType", info.getAgentType());
        json2.put("verifyType", "2");
        JSONObject result = new JSONObject();
        result.put("authType", "ORG_BANK_TRANSFER");
        result.put("contextInfo", json1);
        result.put("orgEntity", 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);
        HashMap map = new HashMap();

        try {
            String url = this.iSignInfoHclcService.getApiUrl("HCLC_FACE_API", "orgAuthUrl");
            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("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());
            this.signInfoHclcFaceService.updateByPrimaryKey(iRequest, signInfoHclcFace);
            return map;
        } 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 Map<String, Object> addOrgansAccount(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("agentAccountId", "");
            result.put("agentUniqueId", signInfoHclc.getAgentIdNo());
            result.put("cardNo", "");
            result.put("email", "");
            result.put("legalLicenseNumber", signInfoHclc.getLegalIdNo());
            result.put("legalLicenseType", "IDCard");
            result.put("legalMobile", "");
            result.put("legalName", signInfoHclc.getLegalName());
            result.put("licenseNumber", signInfoHclc.getIdNo());
            result.put("licenseType", "SOCNO");
            result.put("organizeName", signInfoHclc.getName());
            result.put("organizeNo", 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.iSignInfoHclcService.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("organizeId"));
                    map.put("code", "0");
                    map.put("message", "用户创建成功！");
                } else {
                    this.logger.error("create organs 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 organs 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;
        }
    }
}
