package org.dromara.resource.junziqian.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.dromara.resource.junziqian.common.bean.sign.JzqSign;
import org.dromara.resource.junziqian.common.http.HttpClientUtils;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.IdentityHashMap;
import java.util.Map;
@Slf4j
@Component
public class JzqUtils {
    @Value("${junziqian.Services_URL}")
    private String servicesUrl;

    @Value("${junziqian.AppSecret}")
    private String appSecret;

    @Value("${junziqian.AppKey}")
    private String appKey;
    //请求的body内参数
    Map<String, Object> bodyParams;

    @Before
    public void initParams() {
        Assert.assertTrue("APP_KEY不能为空", StringUtils.isNotBlank(appKey));
        Assert.assertTrue("APP_SECRET不能为空", StringUtils.isNotBlank(appSecret));
        log.warn("测试前请确认APP_KEY，APP_SECRET，LOCAL_URL等配置是否正确");
        log.info("APP_KEY:" + appKey);
        log.info("APP_SECRET:" + appSecret);
        log.info("SERVICE_URL:" + servicesUrl);
        long ts = System.currentTimeMillis();
        String nonce = DigestUtils.md5Hex(System.currentTimeMillis() + "");
        String sign = DigestUtils.sha256Hex("nonce" + nonce + "ts" + ts + "app_key" + appKey + "app_secret" + appSecret);
        bodyParams = new IdentityHashMap<>();
        bodyParams.put("ts", ts);
        bodyParams.put("app_key", appKey);
        bodyParams.put("sign", sign);
        bodyParams.put("nonce", nonce);//这只只是为了生成一个随机值
    }

    //个人信息二要素校验
    public String userValid(String name ,String identityCard){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/userValid";
        params.put("name",name);
        params.put("identityCard",identityCard);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //身份证识别
    public String ocrIdentity(String file, Integer front){
        initParams();
        // 将文件对象放入参数中
        Map<String, Object> params = bodyParams;
        // 解码 Base64 字符串为字节数组
        byte[] fileBytes = Base64.getDecoder().decode(file);

        // 创建临时文件
        File tempFile = null;
        try {
            Path tempFilePath = Files.createTempFile("ocrIdentity", ".jpg");
            tempFile = tempFilePath.toFile();

            // 将字节数组写入临时文件
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(fileBytes);
            }



            String url = servicesUrl + "/v2/ocr/ocrIdentity";


            params.put("file", tempFile);
            params.put("front", front);

            // 发送 HTTP 请求
            return HttpClientUtils.init().getPost(url, null, params, true);
        } catch (IOException e) {
            log.error("文件处理失败: " + e.getMessage(), e);
            throw new RuntimeException("文件处理失败", e);
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    //银行卡识别
    public String ocrBank(File file){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/ocr/ocrBank";
        params.put("file",file);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //营业执照识别
    public ResultInfo ocrBusinessLic(File file){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/ocr/ocrBusinessLic";
        params.put("file",file);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //H5人脸识别
    public String startH5Face(String orderNo,String name,String identityCard,String backUrl,Integer startFrom){
        initParams();
        log.info("startH5Face:"+orderNo+","+name+","+identityCard+","+backUrl+","+startFrom+"$$$$$$$$$$$$$");
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/startH5Face";
        params.put("orderNo",orderNo);
        params.put("name",name);
        params.put("identityCard",identityCard);
        params.put("backUrl",backUrl);
        params.put("startFrom",startFrom);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //银行三要素认证
    public String bankThreeVerify(String name ,String identityCard,String cardNo){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/bankThreeVerify";
        params.put("name",name);
        params.put("identityCard",identityCard);
        params.put("cardNo",cardNo);
        return  HttpClientUtils.init().getPost(url,null,params,true);
    }

    //银行四要素认证
    public String bankFourVerify(String name,String identityCard,String cardNo,String mobilePhone){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/bankThreeVerify";
        params.put("name",name);
        params.put("identityCard",identityCard);
        params.put("cardNo",cardNo);
        params.put("mobilePhone",mobilePhone);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //运营商三要素校验
    public ResultInfo operatorsThreeVerify(String name ,String identityCard,String mobile){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/operatorsThreeVerify";
        params.put("name",name);
        params.put("identityCard",identityCard);
        params.put("mobile",mobile);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //企业基本信息核验
    public ResultInfo enterpriseInfoMatch(String enterpriseName,String identityNo,String legalPersonName){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/enterpriseInfoMatch";
        params.put("enterpriseName",enterpriseName);
        params.put("identityNo",identityNo);
        params.put("legalPersonName",legalPersonName);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //企业工商四要素核验
    public ResultInfo entFourVerify(String entName,String bizLic,String name,String identityCard){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/auth/entFourVerify";
        params.put("entName",entName);
        params.put("bizLic",bizLic);
        params.put("name",name);
        params.put("identityCard",identityCard);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //手写对比度
    public ResultInfo ocrPic(String file,String text){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/ocr/ocrPic";
        params.put("file",file);
        if (!ObjectUtils.isEmpty(text)){
            params.put("text",text);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //获取签约链接
    public String link(String applyNo,String fullName,String identityCard,int identityType){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/link";
        params.put("applyNo",applyNo);
        params.put("fullName",fullName);
        params.put("identityCard",identityCard);
        params.put("identityType",identityType);

        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //获取签约链接(短连接)
    public ResultInfo linkNew(String applyNo,String fullName,String identityCard,int identityType,int viewMode,int useCustomDomain,String backUrl){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/linkNew";
        params.put("applyNo",applyNo);
        params.put("fullName",fullName);
        params.put("identityCard",identityCard);
        params.put("identityType",identityType);
        if (!ObjectUtils.isEmpty(viewMode)){
            params.put("viewMode",viewMode);
        }
        if (!ObjectUtils.isEmpty(useCustomDomain)){
            params.put("useCustomDomain",useCustomDomain);
        }
        if (!ObjectUtils.isEmpty(backUrl)){
            params.put("backUrl",backUrl);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //短信验证码
    public ResultInfo smsVerify(String target){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/ocr/ocrPic";
        params.put("target",target);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //企业实名认证上传
    public ResultInfo organizationCreate(String emailOrMobile, String name, int organizationType, int identificationType,
                                     String organizationRegNo, String organizationRegImg, String legalName,
                                     String legalIdentityCard, String legalMobile, String legalIdentityFrontImg,
                                     String legalIdentityBackImg, String signImg, String address, String authorizeName,
                                     String authorizeCard, String authorizeMobilePhone, String organizationCode,
                                     String organizationCodeImg, String taxCertificateImg, String signApplication,
                                     String notifyUrl){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/user/organizationCreate";
        params.put("emailOrMobile",emailOrMobile);
        params.put("name",name);
        params.put("organizationType",organizationType);
        params.put("identificationType",identificationType);
        params.put("organizationRegNo",organizationRegNo);
        params.put("organizationRegImg",organizationRegImg);
        params.put("legalName",legalName);
        if(!ObjectUtils.isEmpty(legalIdentityCard)){
            params.put("legalIdentityCard",legalIdentityCard);
        }
        if(!ObjectUtils.isEmpty(legalMobile)){
            params.put("legalMobile",legalMobile);
        }
        if(!ObjectUtils.isEmpty(legalIdentityFrontImg)){
            params.put("legalIdentityFrontImg",legalIdentityFrontImg);
        }
        if(!ObjectUtils.isEmpty(legalIdentityBackImg)){
            params.put("legalIdentityBackImg",legalIdentityBackImg);
        }
        if(!ObjectUtils.isEmpty(signImg)){
            params.put("signImg",signImg);
        }
        if(!ObjectUtils.isEmpty(address)){
            params.put("address",address);
        }
        if(!ObjectUtils.isEmpty(authorizeName)){
            params.put("authorizeName",authorizeName);
        }
        if(!ObjectUtils.isEmpty(authorizeCard)){
            params.put("authorizeCard",authorizeCard);
        }
        if(!ObjectUtils.isEmpty(authorizeMobilePhone)){
            params.put("authorizeMobilePhone",authorizeMobilePhone);
        }
        if(!ObjectUtils.isEmpty(organizationCode)){
            params.put("organizationCode",organizationCode);
        }
        if(!ObjectUtils.isEmpty(organizationCodeImg)){
            params.put("organizationCodeImg",organizationCodeImg);
        }
        if(!ObjectUtils.isEmpty(taxCertificateImg)){
            params.put("taxCertificateImg",taxCertificateImg);
        }
        if(!ObjectUtils.isEmpty(signApplication)){
            params.put("signApplication",signApplication);
        }
        if (!ObjectUtils.isEmpty(notifyUrl)){
            params.put("notifyUrl",notifyUrl);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //企业实名认证重传
    public ResultInfo  organizationReapply(String emailOrMobile, String name, int organizationType, int identificationType,
                                       String organizationRegNo, byte[] organizationRegImg, String legalName,
                                       String legalIdentityCard, String legalMobile, byte[] legalIdentityFrontImg,
                                       byte[] legalIdentityBackImg, byte[] signImg, String address,
                                       String authorizeName, String authorizeCard, String authorizeMobilePhone,
                                       String organizationCode, byte[] organizationCodeImg, byte[] taxCertificateImg,
                                       byte[] signApplication){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/user/organizationReapply";
        params.put("emailOrMobile",emailOrMobile);
        params.put("name",name);
        params.put("organizationType",organizationType);
        params.put("identificationType",identificationType);
        params.put("organizationRegNo",organizationRegNo);
        params.put("organizationRegImg",organizationRegImg);
        params.put("legalName",legalName);
        if(!ObjectUtils.isEmpty(legalIdentityCard)){
            params.put("legalIdentityCard",legalIdentityCard);
        }
        if(!ObjectUtils.isEmpty(legalMobile)){
            params.put("legalMobile",legalMobile);
        }
        if(!ObjectUtils.isEmpty(legalIdentityFrontImg)){
            params.put("legalIdentityFrontImg",legalIdentityFrontImg);
        }
        if(!ObjectUtils.isEmpty(legalIdentityBackImg)){
            params.put("legalIdentityBackImg",legalIdentityBackImg);
        }
        if(!ObjectUtils.isEmpty(signImg)){
            params.put("signImg",signImg);
        }
        if(!ObjectUtils.isEmpty(address)){
            params.put("address",address);
        }
        if(!ObjectUtils.isEmpty(authorizeName)){
            params.put("authorizeName",authorizeName);
        }
        if(!ObjectUtils.isEmpty(authorizeCard)){
            params.put("authorizeCard",authorizeCard);
        }
        if(!ObjectUtils.isEmpty(authorizeMobilePhone)){
            params.put("authorizeMobilePhone",authorizeMobilePhone);
        }
        if(!ObjectUtils.isEmpty(organizationCode)){
            params.put("organizationCode",organizationCode);
        }
        if(!ObjectUtils.isEmpty(organizationCodeImg)){
            params.put("organizationCodeImg",organizationCodeImg);
        }
        if(!ObjectUtils.isEmpty(taxCertificateImg)){
            params.put("taxCertificateImg",taxCertificateImg);
        }
        if(!ObjectUtils.isEmpty(signApplication)){
            params.put("signApplication",signApplication);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);

    }
    //SaaS_API发起 文件上传
    public ResultInfo link(File file){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/multiFile/applySign/link";
        params.put("file",file);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //SaaS_API 文件发起
    public ResultInfo link(File file,File attachFile,String backUrl,JSONArray signatories){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/multiFile/applySign/link";
        params.put("file",file);
        if(ObjectUtils.isEmpty(attachFile)){
            params.put("attachFile",attachFile);
        }
        if(!ObjectUtils.isEmpty(backUrl)){
            params.put("backUrl",backUrl);
        }
        if(!ObjectUtils.isEmpty(signatories)){
            params.put("signatories",signatories);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //获取合同编号
    public ResultInfo applyNo(String fileKey){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/multiFile/applySign/applyNo";
        params.put("fileKey",fileKey);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //SaaS文件下载
    public ResultInfo link(String fileKey,String applyNo){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/multiFile/applySign/download/link";
        params.put("fileKey",fileKey);
        params.put("applyNo",applyNo);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //发送签约提醒
    public ResultInfo sendSigningReminder(String applyNo,String businessNo,String fullName,String identityCard,int idenntityType,int signNotifyType,String customizeName){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/notify";
        params.put("applyNo",applyNo);
        params.put("businessNo",businessNo);
        params.put("fullName",fullName);
        params.put("identityCard",identityCard);
        params.put("idenntityType",idenntityType);
        params.put("signNotifyType",signNotifyType);
        if(!ObjectUtils.isEmpty(customizeName)){
            params.put("customizeName",customizeName);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    // 签约发起-模板类API
    public String applySign(JzqSign request) {
        initParams();
        Map<String, Object> params = bodyParams;



        String url = servicesUrl + "/v2/sign/applySign";
        params.put("contractName", request.getContractName());

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(request.getSignatories().get(0));
        jsonArray.add(request.getSignatories().get(1));

        params.put("signatories", jsonArray.toString());
        params.put("serverCa", request.getServerCa());
        params.put("dealType", request.getDealType());
        params.put("templateNo", request.getTemplateNo());
        if (!ObjectUtils.isEmpty(request.getTemplateParams())) {
            params.put("templateParams", request.getTemplateParams());
        }
        params.put("fileType", request.getFileType());
        if (!ObjectUtils.isEmpty(request.getAddPage())) {
            params.put("addPage", request.getAddPage());
        }
        if (!ObjectUtils.isEmpty(request.getPositionType())) {
            params.put("positionType", request.getPositionType());
        }
        if (!ObjectUtils.isEmpty(request.getFaceThreshold())) {
            params.put("faceThreshold", request.getFaceThreshold());
        }
//        if (!ObjectUtils.isEmpty(request.getOrderFlag())) {
//            params.put("orderFlag", request.getOrderFlag());
//        }
//        if (!ObjectUtils.isEmpty(request.getSequenceInfo())) {
//            params.put("sequenceInfo", request.getSequenceInfo());
//        }
        if (!ObjectUtils.isEmpty(request.getNotifyUrl())) {
            params.put("notifyUrl", request.getNotifyUrl());
        }
//        if (!ObjectUtils.isEmpty(request.getNoEbqSign())) {
//            params.put("noEbqSign", request.getNoEbqSign());
//        }
//        if (!ObjectUtils.isEmpty(request.getAttachFiles())) {
//            params.put("attachFiles", request.getAttachFiles());
//        }
//        if (!ObjectUtils.isEmpty(request.getNeedQifengSign())) {
//            params.put("needQifengSign", request.getNeedQifengSign());
//        }
//        if (!ObjectUtils.isEmpty(request.getNoBorderSign())) {
//            params.put("noBorderSign", request.getNoBorderSign());
//        }

        return HttpClientUtils.init().getPost(url, null, params, true);
    }
    //撤销签约合同
    public ResultInfo cancel(String applyNo){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/cancel";
        params.put("applyNo",applyNo);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //撤销批量签约发起
    public ResultInfo batchSignCancel(String businessNo,int part,String applyNo){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/batchSignCancel";
        params.put("businessNo",businessNo);
        if(!ObjectUtils.isEmpty(part)){
            params.put("part",part);
        }
        if(!ObjectUtils.isEmpty(applyNo)){
            params.put("applyNo",applyNo);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //签约状态查询
    public ResultInfo status(String applyNo,String fullName,String identityCard,String identityType){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/status";
        params.put("applyNo",applyNo);
        if(!ObjectUtils.isEmpty(fullName)){
            params.put("fullName",fullName);
        }
        if(!ObjectUtils.isEmpty(identityCard)){
            params.put("identityCard",identityCard);
        }
        if(!ObjectUtils.isEmpty(identityType)){
            params.put("identityType",identityType);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //签约状态及时间查询
    public ResultInfo info(String applyNo,String fullName,String identityCard,int identityType,Integer showAll){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/info";
        params.put("applyNo",applyNo);
        params.put("fullName",fullName);
        params.put("identityCard",identityCard);
        params.put("identityType",identityType);
        if(!ObjectUtils.isEmpty(showAll)){
            params.put("showAll",showAll);
        }
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }
    //创建或修改合同模板
    public ResultInfo oper(Long templateId){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/tmpl/oper";
        params.put("templateId",templateId);
        String result = HttpClientUtils.init().getPost(url,null,params,true);
        return JSON.parseObject(result,ResultInfo.class);
    }

    //企业认证实名上传
    public String organizationCreate(String emailOrMobile,String name,Integer organizationType,Integer identificationType,String organizationRegNo,
                                     File organizationRegImg,String legalName,String legalIdentityCard,String legalMobile){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/user/organizationCreate";
        params.put("emailOrMobile",emailOrMobile);
        params.put("name",name);
        params.put("organizationType",organizationType);
        params.put("identificationType",identificationType);
        params.put("organizationRegNo",organizationRegNo);
        params.put("organizationRegImg",organizationRegImg);
        params.put("legalName",legalName);
        params.put("legalIdentityCard",legalIdentityCard);
        params.put("legalMobile",legalMobile);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }

    //个人证书申请资料上传
    public String cloudCertiPerInfo(String fullName,String identityCard,File idenFront,File idenReverse){

        log.info(idenFront.toString());




        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/user/cloudCertiPerInfo";
        params.put("fullName",fullName);
        params.put("identityCard",identityCard);
        params.put("idenFront",idenFront);
        params.put("idenReverse",idenReverse);
        return HttpClientUtils.init().getPost(url,null,params,true);

    }


    //文件下载
    public String linkFile(String applyNo){
        initParams();
        Map<String, Object> params=bodyParams;
        String url = servicesUrl+"/v2/sign/linkFile";
        params.put("applyNo",applyNo);
        return HttpClientUtils.init().getPost(url,null,params,true);
    }
}
