package com.inkasso.factoring.common.util;

import com.alibaba.fastjson.JSONObject;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.electronicSignature.entity.FddSignData;

import java.io.File;
import java.util.HashMap;
import java.util.List;

;
;

/**
 * 电子签章工具类
 *
 * @author fengxuan
 * @email xuan.feng@changan-inkasso.com
 * @date 2021/7/7 15:17
 */
public class ElectronicSignatureUtil {


    private static HttpClientUtil INSTANCE = HttpClientUtil.getInstance();

    private static final String SOURCE = "factoringTradeOnline";

    private static final String PREFIX = "trade";


    /**
     * 电子签章账号注册
     *
     * @param accountType 账号类型 1：个人，2：公司
     * @param openId      账号唯一标识
     * @return
     */
    public static String registerAccount(String openId, String accountType) {
        HashMap<String, String> map = new HashMap<>();
        map.put("source", SOURCE);
        map.put("openId", openId);
        map.put("accountType", accountType);
        String result = INSTANCE.sendHttpPost(ElectronicSignatureConstant.REGISTER_ACCOUNT_URL, map);
        JSONObject json = (JSONObject) JSONObject.parse(result);
        if (!"200".equals(json.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, json.getString("msg"));
        }
        return json.getString("data");
    }


    /**
     * 获取认证地址
     *
     * @param accountType 账号类型 1：个人，2：公司
     * @param customerId  客户编号 电子签章账号注册返回值
     * @param returnUrl   跳转地址 可为null
     * @return
     */
    public static String getAuthUrl(String accountType, String customerId, String returnUrl) {
        String authUrl = ElectronicSignatureConstant.AUTH_URL + "?customerId=" + customerId + "&accountType=" + accountType + "&returnUrl=" + returnUrl + "&source=" + SOURCE;
        String authResult = INSTANCE.sendHttpsGet(authUrl);
        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
        if (!"200".equals(authJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, authJson.getString("msg"));
        }
        return authResult;
    }


    /**
     * 合同上传
     *
     * @param contractId 合同编号
     * @param docTitle   合同标题
     */
    public static void uploadContract(String contractId, String docTitle, File file) {
        HashMap<String, String> map = new HashMap<>();
        map.put("contractId", contractId);
        map.put("docTitle", docTitle);
        String leaseBackResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.UPLOAD_CONTRACT_URL, map, file);
        JSONObject leaseBackJson = (JSONObject) JSONObject.parse(leaseBackResult);
        if (!"200".equals(leaseBackJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, leaseBackJson.getString("msg"));
        }
    }

    /**
     * 合同下载
     *
     * @param contractId 合同编号
     */
    public static String downloadContract(String contractId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("contractId", contractId);
        String result = INSTANCE.sendHttpPost(ElectronicSignatureConstant.DOWNLOAD_CONTRACT_URL, map);
        JSONObject json = (JSONObject) JSONObject.parse(result);
        if (!"200".equals(json.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, json.getString("msg"));
        }
        return json.getString("data");
    }

    /**
     * 合同归档
     *
     * @param contractId 合同编号
     */
    public static String contractFiled(String contractId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("contractId", contractId);
        String result = INSTANCE.sendHttpPost(ElectronicSignatureConstant.FILED_CONTRACT_URL, map);
        JSONObject json = (JSONObject) JSONObject.parse(result);
        if (!"200".equals(json.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, json.getString("msg"));
        }
        return json.getString("data");
    }

    /**
     * 电子文件签署线上出证
     *
     * @param contractNum 电子合同编号
     */
    public static String complianceContractReport(String contractNum) {
        HashMap<String, String> map = new HashMap<>();
        map.put("contractNum", contractNum);
        String result = INSTANCE.sendHttpPost(ElectronicSignatureConstant.COMPLIANCE_CONTRACT_REPORT_URL, map);
        JSONObject json = (JSONObject) JSONObject.parse(result);
        if (!"200".equals(json.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, json.getString("msg"));
        }
        return json.getString("data");
    }


    /**
     * 批量手动签署
     *
     * @param customerId      客户编号
     * @param fddSignDataList 签章数据集合
     * @param batchTitle      批量请求标题
     * @return
     */
    public static String manualBatchSign(String customerId, List<FddSignData> fddSignDataList, String batchTitle) {
        HashMap<String, String> map = new HashMap<>();
        map.put("businessCode", SOURCE);
        map.put("batchId", String.valueOf(System.currentTimeMillis()));
        map.put("batchTitle", batchTitle);
        map.put("customerId", customerId);
        if (fddSignDataList != null && !fddSignDataList.isEmpty()) {
            for (int i = 0; i < fddSignDataList.size(); i++) {
                map.put("signDataList[" + i + "].contractId", fddSignDataList.get(i).getContractId());
                map.put("signDataList[" + i + "].signKeyword", fddSignDataList.get(i).getSignKeyword());
                map.put("signDataList[" + i + "].transactionId", fddSignDataList.get(i).getTransactionId());
            }
        }
        String signResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.SIGN_URL, map);
        JSONObject signJson = (JSONObject) JSONObject.parse(signResult);
        if (!"200".equals(signJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, signJson.getString("msg"));
        }
        return signJson.getString("data");
    }

    /**
     * 批量手动签署
     *
     * @param customerId      客户编号
     * @param fddSignDataList 签章数据集合
     * @param batchTitle      批量请求标题
     * @return
     */
    public static String batchSignUrlSearchLocation(String customerId, List<FddSignData> fddSignDataList, String batchTitle) {
        HashMap<String, String> map = new HashMap<>();
        map.put("businessCode", SOURCE);
        map.put("batchId", String.valueOf(System.currentTimeMillis()));
        map.put("batchTitle", batchTitle);
        map.put("customerId", customerId);
        if (fddSignDataList != null && !fddSignDataList.isEmpty()) {
            for (int i = 0; i < fddSignDataList.size(); i++) {
                map.put("signDataList[" + i + "].contractId", fddSignDataList.get(i).getContractId());
                map.put("signDataList[" + i + "].searchLocation", fddSignDataList.get(i).getSearchLocation());
                map.put("signDataList[" + i + "].transactionId", fddSignDataList.get(i).getTransactionId());
            }
        }
        String signResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.SEARCH_LOCATION_SIGN_URL, map);
        JSONObject signJson = (JSONObject) JSONObject.parse(signResult);
        if (!"200".equals(signJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, signJson.getString("msg"));
        }
        return signJson.getString("data");
    }


    /**
     * 自动签署
     *
     * @param transactionId 交易号
     * @param contractId    合同编号
     * @param customerId    客户编号
     * @param docTitle      文档标题
     * @param signKeyword   关键字
     * @return
     */
    public static Boolean autoSign(String transactionId, String contractId, String customerId, String docTitle, String signKeyword) {
        HashMap<String, String> map = new HashMap<>();
        map.put("businessCode", SOURCE);
        map.put("transactionId", transactionId);
        map.put("contractId", contractId);
        map.put("customerId", customerId);
        map.put("docTitle", docTitle);
        map.put("signKeyword", signKeyword);
        String signResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.AUTO_SIGN_URL, map);
        JSONObject signJson = (JSONObject) JSONObject.parse(signResult);
        if (!"200".equals(signJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, signJson.getString("msg"));
        }
        return true;
    }

    /**
     * 授权自动签署
     *
     * @param transactionId 交易号
     * @param contractId    合同编号
     * @param customerId    客户编号 电子签章账号注册返回值
     * @return
     */
    public static String beforeAutoSign(String transactionId, String contractId, String customerId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("businessCode", SOURCE);
        map.put("transactionId", transactionId);
        map.put("contractId", contractId);
        map.put("customerId", customerId);
        String signResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.BEFORE_AUTO_SIGN_URL, map);
        JSONObject signJson = (JSONObject) JSONObject.parse(signResult);
        if (!"200".equals(signJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, signJson.getString("msg"));
        }
        return signJson.getString("data");
    }

    /**
     * 生成短连接
     *
     * @param expireTime 过期时间，单位：分钟
     * @param sourceUrl  原URL
     * @return
     */
    public static String shortUrl(String expireTime, String sourceUrl) {
        HashMap<String, String> map = new HashMap<>();
        map.put("expireTime", expireTime);
        map.put("sourceUrl", sourceUrl);
        String urlResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.SHORT_URL, map);
        JSONObject urlJson = (JSONObject) JSONObject.parse(urlResult);
        if (!"200".equals(urlJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, urlJson.getString("msg"));
        }
        return urlJson.getString("data");
    }

    /**
     * 获取认证状态
     */
    public static String getAuthInfo(String customId, String authenticationType) {
        String authResult = INSTANCE.sendHttpsGet(ElectronicSignatureConstant.AUTH_INFO + "?customId="
                + customId + "&authenticationType=" + authenticationType);
        return authResult;
    }

    /**
     * 获取认证信息
     */
    public static String getAuthInfoDetail(String customId, String authenticationType) {
        String authResult = INSTANCE.sendHttpsGet(ElectronicSignatureConstant.AUTH_INFO_DETAIL + "?customId="
                + customId + "&authenticationType=" + authenticationType);
        return authResult;
    }

    /**
     * 获取签署状态
     */
    public static String getSignInfo(String customId, String contractId, String transtationId) {
        String signResult = INSTANCE.sendHttpsGet(ElectronicSignatureConstant.SIGN_INFO + "?customId=" + customId +
                "&contractId=" + contractId + "&transationId=" + transtationId);
        return signResult;
    }


    /**
     * 带名称和身份证号注册（企业也一样 信息一换就能用）
     *
     * @param customerId  客户编号
     * @param accountType 客户类型 1 个人 2 公司
     * @param name        名称
     * @param cardNo      证件号  统一社会信用代码
     * @param phone       电话
     * @return
     */
    public static String getAuthUrlPersonal(String customerId, String accountType, String name, String cardNo, String phone) {
        HashMap<String, String> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("accountType", accountType);
        map.put("name", name);
        map.put("cardNo", cardNo);
        map.put("phone", phone);
        String authResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.AUTH_URL_V3, map);
        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
        if (!"200".equals(authJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, authJson.getString("msg"));
        }
        return authResult;
    }

    /**
     * 带名称和身份证号注册 人脸识别方案
     *
     * @param customerId  客户编号
     * @param accountType 客户类型 1 个人
     * @param name        名称
     * @param phone       电话
     * @return
     */
    public static String getAuthUrlPersonalFace(String customerId, String accountType, String name, String phone) {
        HashMap<String, String> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("accountType", accountType);
        map.put("name", name);
        map.put("phone", phone);
        String authResult = INSTANCE.sendHttpPost(ElectronicSignatureConstant.AUTH_URL_V3_FACE_RECOGNITION, map);
        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
        if (!"200".equals(authJson.get("code"))) {
            throw new ValidatorException(CodeUtil.FAIL, authJson.getString("msg"));
        }
        return authResult;
    }

    /**
     * 删除中间服务的authInfo的认证信息
     *
     * @param socialCreditCode
     */
    public static String removeAuthInfo(String socialCreditCode) {
        String url = ElectronicSignatureConstant.REMOVE_AUTH_INFO + "?code=" + socialCreditCode;
        String authResult = INSTANCE.sendHttpsGet(url);
        return authResult;
    }
}
