package com.dgtly.wxportal.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgtly.system.domain.CustomersExt;
import com.dgtly.system.domain.ESignCorpAuthParam;
import com.dgtly.system.domain.EsignCorpAuthSignRecord;
import com.dgtly.system.domain.Result;
import com.dgtly.system.util.HttpUtil;
import com.dgtly.system.util.ResultUtil;
import com.dgtly.wxportal.domain.EReceivingNote;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ICustomersExtService;
import com.dgtly.system.service.IEsignCorpAuthSignRecordService;
import com.dgtly.wxportal.domain.ESignUpPDFModal;
import com.dgtly.wxportal.domain.OrderFile;
import com.dgtly.wxportal.domain.OrderSelfNote;
import com.dgtly.wxportal.service.IEReceivingNoteService;
import com.dgtly.system.service.ISysUserService;
import com.dgtly.wxportal.config.ESignConfig;
import com.dgtly.wxportal.service.ESignService;
import com.dgtly.wxportal.utils.ESign.ESignHttpUtil;
import com.dgtly.wxportal.utils.ESign.ESignUploadUtil;
import com.dgtly.wxportal.utils.ESign.ESignUrl;
import com.dgtly.wxportal.utils.pdf.PDFSelfUtil;
import com.dgtly.wxportal.utils.pdf.PDFUtil;
import com.dgtly.wxportal.utils.pdf.Watermark;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangDing
 * @version 1.0
 * @descption: TODO
 * @company 神州数码通用软件（洛阳）有限公司
 * @copyright (c) 2019 LuoYang DGT Co'Ltd Inc. All rights reserved.
 * @date 2020-10-10 11:27
 * @since JDK1.8
 */
@Service
public class ESignServiceImpl implements ESignService {


    private static final Logger log = LoggerFactory.getLogger(ESignServiceImpl.class);

    @Autowired
    private ESignHttpUtil eSignHttpUtil;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICustomersExtService customersExtService;
    @Autowired
    private ESignConfig eSignConfig;
    @Autowired
    private IEReceivingNoteService iMetaHanaSalesOrderService;
    @Autowired
    private IEsignCorpAuthSignRecordService esignCorpAuthSignRecordService;


    @Override
    public ESignUpPDFModal upload(String orderId,String tmsShipNumber,String customerCode,String customerName,String userName) {

        EReceivingNote receivingNote = iMetaHanaSalesOrderService.selectEReceivingNote(orderId,tmsShipNumber,customerCode,customerName,userName);
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    @Override
    public ESignUpPDFModal uploadDriver(OrderFile orderFile) {

        OrderSelfNote receivingNote =new OrderSelfNote();
        receivingNote.setBeentrustName(orderFile.getBeentrustName());
        receivingNote.setOrderCreationTime(orderFile.getRun_time());
        receivingNote.setbId(orderFile.getbId());
        receivingNote.setCarNumber(orderFile.getCarNumber());
        receivingNote.setDeliveryNumber(orderFile.getDeliveryNumber());
        receivingNote.setEntrustName(orderFile.getEntrustName());
        receivingNote.setBelongTo(orderFile.getChainsCode());
        receivingNote.setPhone(orderFile.getPhone());
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatDriverPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    /**
     * @param orderFile
     * @description: 委托签署pdf
     * @param: [orderFile]
     * @return: com.dgtly.wxportal.domain.ESignUpPDFModal
     * @author: njs
     * @date: 2023/3/22 17:42
     */
    @Override
    public ESignUpPDFModal uploadEmpowerByAuth(OrderFile orderFile) {
        OrderSelfNote receivingNote =new OrderSelfNote();
        // 受托人
        receivingNote.setBeentrustName(orderFile.getBeentrustName());
        //委托人
        receivingNote.setEntrustName(orderFile.getEntrustName());
        receivingNote.setBelongTo(orderFile.getChainsCode());
        receivingNote.setCustomerName(orderFile.getChainsName());
        receivingNote.setAuthName(orderFile.getAuthName());
        receivingNote.setBeentrustPost(orderFile.getBeentrustPost());
        receivingNote.setEntrustPost(orderFile.getEntrustPost());
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatEmpowerByAuthPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    @Override
    public String verificationUser() {
        return null;
    }

    @Override
    public SysUser createPersonalAccount(SysUser user) {
        JSONObject json = new JSONObject();
        json.put("thirdPartyUserId",user.getLoginName());
//        json.put("name",user.getUserName());
        json.put("idType","CRED_PSN_CH_IDCARD");
//        json.put("idNumber",user.getIdNumber());
//        json.put("mobile",user.getPhonenumber());
//        json.put("email",user.getEmail());
        JSONObject resule = eSignHttpUtil.doPostGetJson(ESignUrl.CreatePersonalAccount,json);
        user.setAccountId(resule.getJSONObject("data").getString("accountId"));
        int isok = userService.insertPersonalAccount(user);
        if (isok>0){
            return user;
        }else {
            return null;
        }
    }

    @Override
    public CustomersExt createThirdParty(CustomersExt customersExt) {
        JSONObject json = new JSONObject();
        log.info("333333333333：{}", JSON.toJSON(customersExt));
        int isok = 1;
        json.put("thirdPartyUserId",customersExt.getChainsCode());
        json.put("creator",customersExt.getCreator());
//        json.put("name",customersExt.getCustomersName());
//        json.put("idType","CRED_ORG_USCC");
//        json.put("idNumber",customersExt.getIdNumber());
//        json.put("orgLegalIdNumber",customersExt.getOrgLegalidNumber());
//        json.put("orgLegalName",customersExt.getOrgLegalName());
        JSONObject resule = eSignHttpUtil.doPostGetJson(ESignUrl.CreateThirdParty,json);
        customersExt.setOrgId(resule.getJSONObject("data").getString("orgId"));
        isok = customersExtService.insertCustomersExt(customersExt);
        if (isok>0){
            return customersExt;
        }else {
            return null;
        }
    }

    @Override
    public int updatePersonalAccount(SysUser user) {
        JSONObject json = new JSONObject();
        int isok = 0;
        JSONObject resule = null;
        if (user.getUserName()!=null) {
            json.put("name", user.getUserName());
        }
        if (user.getIdNumber()!=null) {
            json.put("idNumber", user.getIdNumber());
        }
        if (user.getPhonenumber()!=null) {
            json.put("mobile", user.getPhonenumber());
        }
        if (user.getEmail()!=null) {
            json.put("email", user.getEmail());
        }
        if (user.getAccountId()!=null) {
            resule  = eSignHttpUtil.doPutGetJson(ESignUrl.updatePersonalAccount, json, user.getAccountId());
            if (resule.getInteger("code")==0){
                isok = 1;
            }
        }

        return isok;
    }

    @Override
    public int updateThirdParty(CustomersExt customersExt) {
        JSONObject json = new JSONObject();
        int isok = 0;
        JSONObject resule = null;
        if (customersExt.getCustomersName()!=null) {
            json.put("name", customersExt.getCustomersName());
        }
        if (customersExt.getIdNumber()!=null) {
            json.put("idNumber", customersExt.getIdNumber());
        }
        if (customersExt.getOrgLegalidNumber()!=null) {
            json.put("orgLegalIdNumber", customersExt.getOrgLegalidNumber());
        }
        if (customersExt.getOrgLegalName()!=null) {
            json.put("orgLegalName", customersExt.getOrgLegalName());
        }
        if (customersExt.getOrgId()!=null) {
            resule  = eSignHttpUtil.doPutGetJson(ESignUrl.updateThirdParty, json, customersExt.getOrgId());
            if (resule.getInteger("code")==0){
                isok = 1;
            }
        }
        return isok;
    }

    @Override
    public String getOrgIdByThirdId(String chainsCode) {
        JSONObject json =null;
        JSONObject jsonObject = eSignHttpUtil.doGetGetJson(ESignUrl.getOrgIdByThirdId, json, chainsCode);
        if (jsonObject!=null) {
            JSONObject result = (JSONObject) jsonObject.get("data");
            return result.get("orgId").toString();
        }else{
            return null;
        }
    }

    @Override
    public JSONObject delOrganizations(String orgId) {
        String url = eSignConfig.getUrl(ESignUrl.delOrgUrl, orgId);
        return JSONObject.parseObject(eSignHttpUtil.doDelete(url, new JSONObject().toJSONString()));
    }

    /**
     * @description: 根据loginName查询E签宝是否存在
     * @param: [loginName]
     * @return: java.lang.String
     * @author: qxm
     * @date: 2020/11/27 14:23
     */
    @Override
    public String getAccountIdByThirdId(String loginName) {
        JSONObject json =null;
        JSONObject jsonObject = eSignHttpUtil.doGetGetJson(ESignUrl.getAccountIdByThirdId, json, loginName);
        if (jsonObject!=null) {
            JSONObject result = (JSONObject)jsonObject.get("data");
            return result.get("accountId").toString();
        }else{
            return null;
        }
    }

    /**
     * 创建收货单pdf文件
     * @param
     * @return
     */
    private ESignUpPDFModal creatPdf(EReceivingNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//            writer.setPageEvent(new Watermark("我是水印"));// 水印
//                writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  收  货  单");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFUtil.generateEPDF(document,receivingNote, true);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 500F;
        Float fosY = 700F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        res.setFilePath(fileUrl);
        return res;
    }
    /**
     * @description: 委托授权签署
     * @param: [receivingNote]
     * @return: com.dgtly.wxportal.domain.ESignUpPDFModal
     * @author: njs
     * @date: 2023/3/22 17:55
     */
    private ESignUpPDFModal creatEmpowerByAuthPdf(OrderSelfNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  授  权  委  托  书");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFSelfUtil.generateByEmpowerByAuthPDF(document,receivingNote, false);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 500F;
        Float fosY = 510F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        res.setFilePath(fileUrl);
        return res;
    }
    /**
     * 创建指派司机pdf文件
     * @param
     * @return
     */
    private ESignUpPDFModal creatDriverPdf(OrderSelfNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//            writer.setPageEvent(new Watermark("我是水印"));// 水印
//                writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  授  权  司  机  货  单");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFSelfUtil.generateEPDF(document,receivingNote, false);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 430F;
        Float fosY = 465F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        //第二个盖章位置
        Float fosX2 = 100F;
        Float fosY2 = 400F;
        res.setX2(fosX2);
        res.setY2(fosY2);
        res.setFilePath(fileUrl);
        return res;
    }


    /**
     * 获取文件上传路径
     * @param filePath
     * @return
     */
    private JSONObject getUpUrl(String filePath,String contentMd5,String contentType,int fileLength){
        File file = new File(filePath);
        String fileName = file.getName();
        JSONObject json = new JSONObject();
        json.put("contentMd5", contentMd5);
        json.put("contentType",contentType);
        json.put("convert2Pdf",false);
        json.put("fileName",fileName);
        json.put("fileSize",fileLength);
        JSONObject result=  eSignHttpUtil.doPostGetJson(ESignUrl.uploadCreateFile,json);
        return result;
    }

    /**
     * 发起企业授权书签署任务
     *
     * <pre>
     * 请求示例：
     * POST https://openapi.esign.cn/v3/org-auth/corp-auth-sign/tasks
     * {
     *   "accountId"           : "机构账号ID",
     *   "transactorAccountId" : "经办人个人账号ID",
     *   "authorizedType"      : 1,
     *   "sendNotice"          : true,
     *   "validDate"           : 20271231,
     *   "notifyUrl"           : "https://your-domain.com/esign/notify",
     *   "redirectUrl"         : "https://your-domain.com/esign/redirect"
     * }
     *
     * 成功响应示例：
     * {
     *   "code"    : 0,
     *   "message" : "成功",
     *   "data"    : {
     *     "taskId"  : "xxx",
     *     "signUrl" : "https://..."
     *   }
     * }
     * </pre>
     *
     * @param param 请求参数
     * @return Result
     */
    @Override
    public Result initiateCorpAuthSign(ESignCorpAuthParam param) throws IOException {
        // 1. 参数基础校验
        if (param == null) {
            return ResultUtil.error(500, "请求参数不能为空");
        }
        if (StringUtils.isBlank(param.getAccountId())) {
            return ResultUtil.error(500, "机构账号ID（accountId）不能为空");
        }
//        if (StringUtils.isBlank(param.getTransactorAccountId())) {
//            return ResultUtil.error(500, "经办人账号ID（transactorAccountId）不能为空");
//        }
        if (param.getValidDate() == null) {
            return ResultUtil.error(500, "授权有效期截止时间（validDate）不能为空");
        }
        // authorizedType=2 时 authorizedAccountId 必传
        if (param.getAuthorizedType() != null && param.getAuthorizedType() == 2
                && StringUtils.isBlank(param.getAuthorizedAccountId())) {
            return ResultUtil.error(500, "授权至经办人模式（authorizedType=2）时，被授权人账号ID（authorizedAccountId）不能为空");
        }

        // 2. 构建请求体
        JSONObject json = new JSONObject();
        json.put("accountId",           param.getAccountId());
        json.put("transactorAccountId", param.getTransactorAccountId());

        if (param.getAuthorizedType() != null) {
            json.put("authorizedType", param.getAuthorizedType());
        }
        if (StringUtils.isNotBlank(param.getAuthorizedAccountId())) {
            json.put("authorizedAccountId", param.getAuthorizedAccountId());
        }
        // sendNotice 默认 true，仅显式传 false 时才覆盖
        if (param.getSendNotice() != null) {
            json.put("sendNotice", param.getSendNotice());
        }
        json.put("validDate", param.getValidDate());

        if (StringUtils.isNotBlank(param.getNotifyUrl())) {
            json.put("notifyUrl", param.getNotifyUrl());
        }
        if (StringUtils.isNotBlank(param.getRedirectUrl())) {
            json.put("redirectUrl", param.getRedirectUrl());
        }
        json.put("sendNotice",false);

        log.info("[ESign] 发起企业授权书签署任务, url={}, accountId={}, transactorAccountId={}",
                ESignUrl.createEsignAuthUrl, param.getAccountId(), param.getTransactorAccountId());

        // 4. 发起 HTTP 请求
        JSONObject responseJson = eSignHttpUtil.doPostGetJson(ESignUrl.createEsignAuthUrl,json);
        log.info("[ESign] 企业授权书签署任务响应, response={}", responseJson);

        // 5. 解析响应
        if (responseJson == null) {
            return ResultUtil.error(500, "e签宝接口返回为空");
        }
        if (responseJson == null) {
            return ResultUtil.error(500, "e签宝接口响应解析失败");
        }

        Integer code = responseJson.getInteger("code");
        String message = responseJson.getString("message");

        if (code == null || code != 0) {
            log.warn("[ESign] 企业授权书签署任务失败, code={}, message={}", code, message);
            return ResultUtil.error(500, "发起企业授权书签署任务失败：" + message);
        }

        // 6. 成功，返回 data（含 taskId / signUrl 等）
        Object data = responseJson.get("data");

        // 7. 将 authId 写入本地签署状态记录表
        try {
            JSONObject dataJson = responseJson.getJSONObject("data");
            String authId = dataJson != null ? dataJson.getString("authId") : null;
            if (StringUtils.isNotBlank(authId)) {
                EsignCorpAuthSignRecord record = new EsignCorpAuthSignRecord();
                record.setAuthId(authId);
                record.setOrgId(param.getAccountId());
                record.setCreator(param.getTransactorAccountId());
                record.setCustomeCode(param.getCustomeCode());
                record.setStatus(1); // 1=进行中
                esignCorpAuthSignRecordService.insertRecord(record);
                log.info("[ESign] 签署状态记录已写入, authId={}, orgId={}, customeCode={}",
                        authId, param.getAccountId(), param.getCustomeCode());
            } else {
                log.warn("[ESign] 发起成功但 data 中未找到 authId，跳过写入签署状态记录, data={}", dataJson);
            }
        } catch (Exception e) {
            // 写入记录失败不影响主流程，仅记录日志
            log.error("[ESign] 写入签署状态记录失败, accountId={}", param.getAccountId(), e);
        }

        return ResultUtil.success(data);
    }

    /**
     * 获取授权流程签署URL
     *
     * <pre>
     * POST /v1/signAuthApi/signUrl
     * 请求参数：
     *   authId      String  是   授权流程ID
     *   needLogin   boolean 否   是否需要登录打开链接，默认 true
     *   clientType  String  否   客户端类型：H5 / PC / ALL（默认 ALL）
     *   redirectUrl String  否   签署完成后跳转页面
     *   appScheme   String  否   AppScheme，用于唤起 App
     *
     * 响应：
     *   code     int    业务码，0 表示成功
     *   message  String 业务信息
     *   data:
     *     shortUrl String 授权流程签署短链接（90天有效）
     *     longUrl  String 授权流程签署长链接（90天有效）
     * </pre>
     */
    @Override
    public Result getSignUrl(String authId, Boolean needLogin, String clientType,
                             String redirectUrl, String appScheme) throws IOException {
        if (StringUtils.isBlank(authId)) {
            return ResultUtil.error(500, "授权流程ID（authId）不能为空");
        }

        // 构建请求体
        JSONObject json = new JSONObject();
        json.put("authId", authId);
        if (needLogin != null) {
            json.put("needLogin", needLogin);
        }
        if (StringUtils.isNotBlank(clientType)) {
            json.put("clientType", clientType.toUpperCase());
        }
        if (StringUtils.isNotBlank(redirectUrl)) {
            json.put("redirectUrl", redirectUrl);
        }
        if (StringUtils.isNotBlank(appScheme)) {
            json.put("appScheme", appScheme);
        }

        log.info("[ESign] 获取授权流程签署URL, authId={}", authId);

        JSONObject responseJson = eSignHttpUtil.doPostGetJson(ESignUrl.getSignUrl, json);
        log.info("[ESign] 获取授权流程签署URL响应, response={}", responseJson);

        if (responseJson == null) {
            return ResultUtil.error(500, "e签宝接口返回为空");
        }

        Integer code = responseJson.getInteger("code");
        String message = responseJson.getString("message");

        if (code == null || code != 0) {
            log.warn("[ESign] 获取授权流程签署URL失败, code={}, message={}", code, message);
            return ResultUtil.error(500, "获取授权流程签署URL失败：" + message);
        }

        Object data = responseJson.get("data");
        return ResultUtil.success(data);
    }

    /**
     * 查询授权结果
     *
     * <pre>
     * GET /v1/signAuthApi/queryAuthResult?authId={authId}
     *
     * 响应 data 字段：
     *   authId             String  授权流程ID
     *   status             int     授权状态：1=进行中 2=授权成功 3=授权失败 4=取消授权
     *   failReason         String  授权说明（授权失败时返回原因）
     *   effectiveStartTime long    授权生效时间（格式 yyyyMMdd）
     *   effectiveEndTime   long    授权失效时间（格式 yyyyMMdd）
     *   authDownloadUrl    String  授权书下载链接（有效期60分钟，仅 status=2 时返回）
     * </pre>
     */
    @Override
    public Result queryAuthResult(String authId,String customeCode) throws IOException {
        EsignCorpAuthSignRecord esignCorpAuthSignRecord =esignCorpAuthSignRecordService.selectByCustomeCode(customeCode);
        if (esignCorpAuthSignRecord == null){
            return ResultUtil.error(500, "e签宝暂未签署授权");
        }else {
            if (StringUtils.isEmpty(authId)){
                authId = esignCorpAuthSignRecord.getAuthId();
            }
        }

        log.info("[ESign] 查询授权结果, authId={}", authId);

        // GET 请求，authId 作为 query 参数拼入 URL（枚举 URL 含 %s 占位符）
        JSONObject responseJson = eSignHttpUtil.doGetGetJson(ESignUrl.queryAuthResult, new JSONObject(), authId);
        log.info("[ESign] 查询授权结果响应, response={}", responseJson);

        if (responseJson == null) {
            return ResultUtil.error(500, "e签宝接口返回为空");
        }

        Integer code = responseJson.getInteger("code");
        String message = responseJson.getString("message");

        if (code == null || code != 0) {
            log.warn("[ESign] 查询授权结果失败, code={}, message={}", code, message);
            return ResultUtil.error(500, "查询授权结果失败：" + message);
        }

        Object data = responseJson.get("data");
        return ResultUtil.success(data);
    }

}
