package com.hzya.frame.seeyon.zxbank.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.mdm.mdmModuleSource.dao.impl.MdmModuleSourceDaoImpl;
import com.hzya.frame.mdm.mdmModuleSource.entity.MdmModuleSourceEntity;
import com.hzya.frame.seeyon.dao.ICtpAttachmentDao;
import com.hzya.frame.seeyon.dao.ICtpFileDao;
import com.hzya.frame.seeyon.entity.CtpAttachmentEntity;
import com.hzya.frame.seeyon.entity.CtpFileEntity;
import com.hzya.frame.seeyon.util.OARestUtil;
import com.hzya.frame.seeyon.util.SM2Util;
import com.hzya.frame.seeyon.zxbank.dao.IZxBankDao;
import com.hzya.frame.seeyon.zxbank.entity.PayState;
import com.hzya.frame.seeyon.zxbank.entity.ZxBankEntity;
import com.hzya.frame.seeyon.zxbank.service.IZxBankService;
import com.hzya.frame.sysnew.application.database.dao.ISysApplicationDatabaseDao;
import com.hzya.frame.sysnew.application.database.entity.SysApplicationDatabaseEntity;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.sysnew.comparison.service.impl.ComparisonServiceImpl;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.service.IIntegrationTaskLivingDetailsService;
import com.hzya.frame.uuid.UUIDLong;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

@Service("ZxBankServiceImpl")
public class ZxBankServiceImpl extends BaseService<ZxBankEntity, String> implements IZxBankService {

    @Autowired
    private MdmModuleSourceDaoImpl mdmModuleSourceDaoImpl;

    @Autowired
    private IZxBankDao zxBankDao;
    @Autowired
    private IIntegrationTaskLivingDetailsService taskLivingDetailsService;
    @Autowired
    private ComparisonServiceImpl comparisonServiceimpl;
    @Autowired
    private ICtpAttachmentDao ctpAttachmentDao;

    @Autowired
    private ISysApplicationDatabaseDao sysApplicationDatabaseDao;

    @Value("${zt.url}")
    private String url;

    @Value("${zx.privateKey:}")
    private String privateKey;

    @Value("${zx.publicKey:}")
    private String publicKey;

    @Autowired
    private ICtpFileDao ctpFileDao;
    @Override
    public JsonResultEntity queryArchives(JSONObject json) {
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        //根据插件分类查询主数据来源表
        List<MdmModuleSourceEntity> list = mdmModuleSourceDaoImpl.MdmModuleSourceentityGroupByType();
        if (CollectionUtils.isEmpty(list)) {
            logger.info("没有类型为插件得数据,无法获取数据");
            return BaseResult.getFailureMessageEntity("数据来源表无插件类型");
        }
        for (MdmModuleSourceEntity mdmModuleSourceEntity : list) {
            String tableName = "";
            List<Object> object=new ArrayList<>();
            List<JSONObject> listAll  = new ArrayList<>();
            try {
                String appTyp = mdmModuleSourceEntity.getAppType();//系统类型  1、致远OA 2、用友U8C 3、用友BIP
                String dbCode = mdmModuleSourceEntity.getDbCode();//数据源编码
                String mdmCode = mdmModuleSourceEntity.getMdmCode();//主数据编码
                switch (appTyp){
                    case "1":
                        switch (mdmCode){
                            case "10048"://杭泰付款单
                                tableName = "mdm_zxbank";
                                listAll = bindingZxBank(jsonObject, mdmModuleSourceEntity, dbCode);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
                //将查询出来的数据进行组装，调用通用方法新增或者更新
                if (null != listAll && listAll.size() > 0) {
                    object = ParametricDocument(listAll, mdmCode, tableName);
                    if (CollectionUtils.isNotEmpty(object)) {
                        for (Object obj : object) {
                            //更新单据视图推送标识，不再抽取
                            JSONObject attributeResult = (JSONObject) JSON.toJSON(obj);
                            if (attributeResult.getString("status").equals("200")) {
                                String resultString = attributeResult.getString("list");
                                if ("10048".equals(mdmCode)) {
                                    JSONArray jsonArray = JSONArray.parseArray(resultString);
                                    if (CollectionUtils.isNotEmpty(jsonArray)) {
                                        for (Object o : jsonArray) {
                                            JSONObject attributeArray = (JSONObject) JSON.toJSON(o);
                                            String mdmZxBank = attributeArray.getString(tableName);
                                            JSONObject jsonObjectCmpApply = JSONObject.parseObject(mdmZxBank);
                                            String pushStatusField = jsonObjectCmpApply.getString("push_status_field");//推送标识字段
                                            String dataId = jsonObjectCmpApply.getString("data_id");//主表id
                                            String documentNo = jsonObjectCmpApply.getString("document_no");
                                            logger.info("=====开始根据单据id:{},单据号：{},更新杭泰表：{}的推送标识", dataId, documentNo, tableName);
                                            ZxBankEntity zxBankEntity = new ZxBankEntity();
                                            zxBankEntity.setTabName(jsonObjectCmpApply.getString("tab_name"));
                                            zxBankEntity.setPushStatusField(pushStatusField);
                                            zxBankEntity.setPushStatus("1");
                                            zxBankEntity.setId(dataId);
                                            zxBankEntity.setDataSourceCode(mdmModuleSourceEntity.getDataSourceCode());
                                            zxBankDao.updatePushStatusZX(zxBankEntity);
                                            //保存业务数据日志
                                            saveTaskLivingDetails(dataId, jsonObjectCmpApply.getString("document_no"), listAll.get(0).toString(), object.toString(), true,"ZxBankPluginInitializer");
                                        }
                                    }
                                }
                            } else {
                                saveTaskLivingDetails(JSONObject.parseObject(listAll.get(0).getString("mdm_zxbank")).getString("data_id"), JSONObject.parseObject(listAll.get(0).getString("mdm_zxbank")).getString("document_no"), listAll.get(0).toString(), JSON.parseObject(JSON.toJSONString(object)).getString("msg"), false,"ZxBankPluginInitializer");
                            }
                        }
                    }
                } else {
                    logger.info("杭泰付款单没有需要同步中信的数据");
                }
            }catch (Exception e){
                logger.info("杭泰付款单同步失败:{}",e.getMessage());
                saveTaskLivingDetails(JSONObject.parseObject(listAll.get(0).getString("mdm_zxbank")).getString("data_id"),JSONObject.parseObject(listAll.get(0).getString("mdm_zxbank")).getString("document_no"),listAll.get(0).toString(),JSON.parseObject(JSON.toJSONString(object)).getString("msg")==null?JSON.parseObject(JSON.toJSONString(object)).getString("list"):JSON.parseObject(JSON.toJSONString(object)).getString("msg"),false,"ZxBankPluginInitializer");
                e.printStackTrace();
            }
        }
        return BaseResult.getSuccessMessageEntity("业务数据同步成功");
    }

    @Override
    public JsonResultEntity queryArchivesResult(JSONObject json) {
        try {
            ZxBankEntity zxBankEntity = json.toJavaObject(ZxBankEntity.class);
            zxBankEntity.setDataSourceCode("HT-OA");
            logger.info("======开始查询中信返回的支付结果=====");
            List<ZxBankEntity> zxBankEntities = zxBankDao.queryResultIsNullZX(zxBankEntity);
            if(CollectionUtils.isEmpty(zxBankEntities)){
                logger.info("=====杭泰付款单中没有已推送并且支付结果为空的数据========");
                return BaseResult.getSuccessMessageEntity("查询成功");
            }
            for (ZxBankEntity bankEntity : zxBankEntities) {
                List<String> list = new ArrayList<>();
                list.add(bankEntity.getDocumentNo());
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("documentNoList",list);
                JSONObject objectData=new JSONObject();
                objectData.put("data",jsonObject);
                logger.info("=======杭泰付款单调用中信支付结果查询请求参数明文为:{}", objectData.toJSONString());
                String encrypt = SM2Util.encrypt(objectData.toJSONString(), publicKey);
                JSONObject jsonData=new JSONObject();
                jsonData.put("data",encrypt);
                //logger.info("=======杭泰付款单调用中信支付结果查询请求参数密文为:{}", jsonData.toJSONString());
                //发送数据
                String result = HttpRequest.post(url).
                        header("appId", "800058").
                        header("apiCode", "8000580001").
                        //header("access_token", tokenBody).
                                header("publicKey", "ZJYALA1PchEI1s2D5vaapO9RZ6CiDFv/pJAV88lRYg0oBwBCe7eDIk+3zDUT+v578prj").
                        header("secretKey", "jcoATYyty05KgDwL4O0xD+Ulq5ExYWkGvZGf2bhKrMaCehb3NIm5DUnJSK/r2SUaj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                        body(jsonData.toJSONString()).
                        execute().
                        body();
                logger.info("========杭泰付款单调用中信支付结果查询返回参数为:{}==========", result);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (!resultJson.getBoolean("flag")) {
                    saveTaskLivingDetails(bankEntity.getDataId(), bankEntity.getDocumentNo(), jsonData.toJSONString(), resultJson.toJSONString(), false,"ZxBankResultPluginInitializer");
                } else {
                    JSONObject attribute = resultJson.getJSONObject("attribute");
                    String data = attribute.getString("data");
                   // logger.info("=======杭泰付款单调用中信支付结果查询返回参数密文为:{}", data);
                    String decrypt = SM2Util.decrypt(data, privateKey);
                    logger.info("=======杭泰付款单调用中信支付结果查询返回参数明文为:{}", decrypt);
                    JSONObject jsonObjectData = JSONObject.parseObject(decrypt);
                    JSONArray jsonArray = jsonObjectData.getJSONArray("list");
                    if(CollectionUtils.isNotEmpty(jsonArray)){
                        for (Object o : jsonArray) {
                            JSONObject jsonObjectList=(JSONObject) JSON.toJSON(o);
                            String documentNo = jsonObjectList.getString("documentNo");//返回的业务单据号
                            String payStatus = jsonObjectList.getString("payStatus");//返回的状态
                            String errorMsg = jsonObjectList.getString("errorMsg");//返回的错误信息
                            logger.info("====付款單查询中信返回的单据号为：{}，返回结果为：{}，错误信息为：{}",documentNo,payStatus,errorMsg);
                            if(documentNo.equals(bankEntity.getDocumentNo())){
                                //修改支付状态
                                bankEntity.setPayResult(PayState.payStateGetValue(payStatus));
                                bankEntity.setDataSourceCode("HT-OA");
                                bankEntity.setId(bankEntity.getDataId());
                                zxBankDao.updateResultStatus(bankEntity);
                                saveTaskLivingDetails(bankEntity.getDataId(), bankEntity.getDocumentNo(), jsonData.toJSONString(), resultJson.toJSONString(), true,"ZxBankResultPluginInitializer");
                            }
                        }
                    }else{
                        logger.info("====查询支付结果返回值中的list为空====");
                    }
                }
            }
            //logger.info("========杭泰付款单查询支付结果执行成功========");
            return BaseResult.getSuccessMessageEntity("支付结果查询成功");
        }catch (Exception e){
            logger.info("=========查询中信返回的支付结果失败:{}=======",e.getMessage());
            e.printStackTrace();
        }
        return BaseResult.getFailureMessageEntity("支付结果查询失败");
    }



    @Override
    public JsonResultEntity queryArchivesElec(JSONObject json) {
        try {
            ZxBankEntity zxBankEntity = json.toJavaObject(ZxBankEntity.class);
            zxBankEntity.setDataSourceCode("HT-OA");
            logger.info("======开始查询中信电子回单=====");
            List<ZxBankEntity> zxBankEntities = zxBankDao.queryElecIsNullZX(zxBankEntity);
            if(CollectionUtils.isEmpty(zxBankEntities)){
                logger.info("=====杭泰付款单中没有已支付并且电子回单为空的数据========");
                return BaseResult.getSuccessMessageEntity("查询成功");
            }
            for (ZxBankEntity bankEntity : zxBankEntities) {
                JSONObject jsonParam=new JSONObject();
                jsonParam.put("companyCode",bankEntity.getCompanyCode());//公司编码
                jsonParam.put("documentNo",bankEntity.getDocumentNo());//单据号
                JSONObject jsonData=new JSONObject();
                jsonData.put("data",jsonParam);
                String params = jsonData.toJSONString();
                logger.info("======杭泰付款单调用中信电子回单查询请求参数明文为:{}========",params);
                String encrypt = SM2Util.encrypt(params, publicKey);
                JSONObject objectData=new JSONObject();
                objectData.put("data",encrypt);
                logger.info("======杭泰付款单调用中信电子回单查询请求参数密文为:{}========",objectData.toJSONString());
                //发送数据
                String result = HttpRequest.post(url).
                        header("appId", "800058").
                        header("apiCode", "8000580002").
                        //header("access_token", tokenBody).
                                header("publicKey", "ZJYALA1PchEI1s2D5vaapO9RZ6CiDFv/pJAV88lRYg0oBwBCe7eDIk+3zDUT+v578prj").
                        header("secretKey", "jcoATYyty05KgDwL4O0xD+Ulq5ExYWkGvZGf2bhKrMaCehb3NIm5DUnJSK/r2SUaj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                        body(objectData.toJSONString()).
                        execute().
                        body();
                logger.info("======杭泰付款单调用中信电子回单查询返回参数为:{}========",result);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (!resultJson.getBoolean("flag")) {
                    saveTaskLivingDetails(bankEntity.getDataId(), bankEntity.getDocumentNo(), params, resultJson.toJSONString(), false,"ZxBankElecPluginInitializer");
                } else {
                    JSONObject attribute = resultJson.getJSONObject("attribute");
                    String data = attribute.getString("data");
                    logger.info("=======杭泰付款单调用中信支付结果查询返回参数密文为:{}", data);
                    String decrypt = SM2Util.decrypt(data, privateKey);
                    JSONObject jsonObjectData = JSONObject.parseObject(decrypt);
                    String billId = jsonObjectData.getString("billId");  //电子回单id  电子回单下载需要
                    logger.info("======中信电子回单返回的电子回单id为:{}====",billId);
                    if(StrUtil.isNotEmpty(billId)){
                        List<String> list=new ArrayList<>();
                        list.add(billId);
                        JSONObject billIds=new JSONObject();
                        billIds.put("billIds",list);
                        JSONObject elecdata=new JSONObject();
                        elecdata.put("data",billIds);
                        logger.info("====调用中信电子回单下载得请求参数明文为：{}=======",elecdata.toJSONString());
                        elecDownlod(elecdata.toJSONString(),bankEntity);
                    }
                }
            }
        }catch (Exception e){
            logger.info("======杭泰付款单查询中信电子回单失败:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    private JsonResultEntity elecDownlod(String params,ZxBankEntity zxBankEntity){
        try {
            String encrypt = SM2Util.encrypt(params, publicKey);
            JSONObject objectData=new JSONObject();
            objectData.put("data",encrypt);
            logger.info("====调用中信电子回单下载得请求参数密文为：{}=======",objectData.toJSONString());
            //因为电子回单下载返回的只有文件流，所以无法在中台上注册接口，只能代码中调用第三方接口
            //将文件流的zip下载到文件夹中，之后解压该文件夹，得到pdf文件，上传OA
            String downloadFolder ="D:\\yongansystem\\zxbank\\pdf\\";
            String destinationFolder ="D:\\yongansystem\\zxbank\\pdf\\";

            URL url = new URL("http://122.9.75.156:9091/access/treasury/hangtai/bill/down");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 写入 JSON 请求体
            try (OutputStream os = connection.getOutputStream();
                 OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
                osw.write(objectData.toJSONString());
                osw.flush();
            }

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取响应头中的 Content-Disposition
                String contentDisposition = connection.getHeaderField("Content-Disposition");
                String fileName = parseFileName(contentDisposition);
                // 拼接指定文件夹和文件名
                File outputFile = new File(downloadFolder, fileName);
                // 确保文件夹存在
                File parentDir = outputFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        logger.info("无法创建目录: {}" , parentDir);
                        return null;
                    }
                }

                // 获取响应的输入流
                try (InputStream inputStream = connection.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    logger.info("文件下载成功，保存路径: {}" ,outputFile.getAbsolutePath());
                    //开始解压得到的zip文件
                    File sourceFolder = new File(outputFile.getAbsolutePath());
                    if (!sourceFolder.exists()) {
                        logger.info("源文件夹不存在或不是一个有效的文件夹");
                        return null;
                    }

                    if (sourceFolder.isFile() && sourceFolder.getName().endsWith(".zip")) {
                        List<File> files = unzipFile(sourceFolder.getAbsolutePath(), destinationFolder);
                        // 上传 PDF 文件
                        for (File pdfFile : files) {
                            logger.info("pdf文件名称为：{}",pdfFile.getName());
                            if (pdfFile.exists()) {
                                logger.info("=====开始上传中信司库回单到杭泰OA======");
                                JSONObject jsonObject = fileUpload(pdfFile);
                                if (jsonObject.getString("fileUrl") != null) {
                                    //表单的附件字段=ctpAttachment的Sub_reference，表单的Summary_id=ctpAttachment的att_reference
                                    String sub_reference = String.valueOf(UUIDLong.longUUID());
                                    zxBankEntity.setReceipt(sub_reference);
                                    zxBankEntity.setDataSourceCode("HT-OA");
                                    zxBankDao.updateElecStatusZX(zxBankEntity);
                                    //根据附件id查询附件信息
                                    CtpFileEntity ctpFileEntity=new CtpFileEntity();
                                    ctpFileEntity.setId(jsonObject.getString("fileUrl"));
                                    ctpFileEntity.setDataSourceCode("HT-OA");
                                    List<CtpFileEntity> query = ctpFileDao.queryCtpFileById(ctpFileEntity);
                                    if(CollectionUtils.isNotEmpty(query)) {
                                        CtpFileEntity ctpFile = query.get(0);
                                        //根据附件id查询附件业务数据
                                        String file_url = jsonObject.getString("fileUrl");
                                        CtpAttachmentEntity ctpAttachmentEntity = new CtpAttachmentEntity();
                                        ctpAttachmentEntity.setFile_url(file_url);
                                        String att_reference = zxBankEntity.getSummaryId();//Summary_id
                                        ctpAttachmentEntity.setSub_reference(sub_reference);
                                        ctpAttachmentEntity.setAtt_reference(att_reference);
                                        ctpAttachmentEntity.setDataSourceCode("HT-OA");
                                        List<CtpAttachmentEntity> ctpAttachmentEntities = ctpAttachmentDao.queryCtpAttachment(ctpAttachmentEntity);
                                        //如果没有查询到数据，就新增附件业务，否则更新
                                        if (ctpAttachmentEntities.size() == 0) {
                                            String category =ctpFile.getCategory();
                                            String type =ctpFile.getType();
                                            String filename =ctpFile.getFilename();
                                            String mime_type =ctpFile.getMime_type();
                                            String attachment_size =ctpFile.getFile_size();
                                            String id = String.valueOf(UUIDLong.longUUID());
                                            ctpAttachmentEntity.setCategory(category);
                                            ctpAttachmentEntity.setFilename(filename);
                                            ctpAttachmentEntity.setType(type);
                                            ctpAttachmentEntity.setMime_type(mime_type);
                                            ctpAttachmentEntity.setAttachment_size(attachment_size);
                                            ctpAttachmentEntity.setId(id);
                                            ctpAttachmentEntity.setCategory("66");
                                            ctpAttachmentEntity.setCreatedate(new Date());
                                            ctpAttachmentEntity.setDataSourceCode("HT-OA");
                                            ctpAttachmentDao.saveCtpAttachment(ctpAttachmentEntity);
                                        } else {
                                            if (ctpAttachmentEntities.size() > 1) {
                                                throw new BaseSystemException("OA附件业务表中查到多条记录");
                                            }
                                            //更新数据到OA附件业务表中
                                            ctpAttachmentDao.updateCtpAttachment(ctpAttachmentEntity);
                                        }
                                        logger.info("=====电子回单执行完毕=======");
                                    }else{
                                        logger.info("========根据附件id:{}没有查询到附件信息======",jsonObject.getString("fileUrl"));
                                    }
                                }
                                pdfFile.delete();
                            }
                        }
                    }
                }
            } else {
                logger.info("请求失败，响应状态码:{} " , responseCode);
            }
            connection.disconnect();
        }catch (Exception e){
            logger.info("=======中信电子回单下载失败：{}======",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public  JSONObject fileUpload(File file) {
        if (null != file) {
            try {
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", file);
                String url = "/seeyon/rest/attachment?token=@token@";//如果后面加上applicationCategory=1&extensions=&firstSave=true，附件业务自动生成一条记录
                url = url.replaceAll("@token@", getToken());
                String result = HttpUtil.post("http://60.204.152.210" + url, paramMap);
                if (StrUtil.isNotBlank(result)) {
                    logger.info("附件上传结果"+result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String atts = jsonObject.get("atts").toString();
                    if (StrUtil.isNotEmpty(atts)) {
                        JSONArray jsonArray = JSONArray.parseArray(atts);
                        JSONObject res = (JSONObject) jsonArray.get(0);
                        String fileUrl =  res.getString("fileUrl");
                        logger.info("附件id:" + fileUrl);
                        return res;
                    }
                }
            }catch (Exception e){
                logger.error("附件上传失败"+e.getMessage());
            }
        }
        return null;
    }

    private  String getToken() {
        //获取oatoken
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userName", "hzyaRest");
        hashMap.put("password", "a5ce21b8-91db-4cec-b3e3-3e44719655fd");
        hashMap.put("loginName","bdmanager");
        String result = HttpUtil.post("http://60.204.152.210" + "/seeyon/rest/token", JSON.toJSONString(hashMap));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (null != jsonObject) {
            logger.info(result);
            logger.info("======token：{}======" + jsonObject.getString("id"));
            return jsonObject.getString("id");
        }
        return null;
    }

    private static String parseFileName(String contentDisposition) {
        if (contentDisposition == null) {
            return "unknown.zip";
        }
        // 匹配 filename*=utf-8'' 后面的文件名
        Pattern pattern = Pattern.compile("filename\\*=utf-8''([^;]+)");
        Matcher matcher = pattern.matcher(contentDisposition);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "unknown.zip";
    }

    private  List<File>  unzipFile(String zipFilePath, String destinationFolderPath) {
        List<File> pdfFiles = new ArrayList<>();
        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File outputFile = new File(destinationFolderPath, entry.getName());
                if (entry.isDirectory()) {
                    outputFile.mkdirs();
                } else {
                    try (InputStream inputStream = zipFile.getInputStream(entry);
                         OutputStream outputStream = new FileOutputStream(outputFile)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                    if (outputFile.getName().endsWith(".pdf")) {
                        pdfFiles.add(outputFile);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pdfFiles;
    }



    private List<JSONObject> bindingZxBank(JSONObject jsonObject, MdmModuleSourceEntity mdmModuleSourceEntity, String dbCode) {
        List<JSONObject> list = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select * from v_hzya_pay where 1=1 and  push_status is null ");
        mdmModuleSourceEntity.setDataSourceCode(dbCode);
        List<HashMap<String, Object>> hashMaps = zxBankDao.queryListByBank(stringBuffer.toString(), mdmModuleSourceEntity);
        int i = 0;
        if (CollectionUtils.isNotEmpty(hashMaps)) {
            for (HashMap<String, Object> hashMap : hashMaps) {
                JSONObject main = new JSONObject();
                JSONObject bank = new JSONObject();
                for (String key : hashMap.keySet()) {
                    bank.put(key.toLowerCase(), hashMap.get(key));
                }
                main.put("mdm_zxbank", bank);
                list.add(main);
            }
        }
        return list;
    }


    private List<Object> ParametricDocument(List<JSONObject>  hashMaps,String mdmCode,String tableName){
        JSONObject jsonObjectUser = new JSONObject();
        List<Object> result=new ArrayList<>();
        try {
            for (JSONObject hashMap : hashMaps) {
                JSONObject main = hashMap.getJSONObject(tableName);
                JSONObject jsonStr = new JSONObject();
                jsonObjectUser.put("data_id", main.get("data_id"));
                jsonObjectUser.put("mdmCode", mdmCode);
                jsonStr.put("jsonStr", jsonObjectUser);
                //先查询编码和名称查询是否存在
                Object attribute = comparisonServiceimpl.queryEntityPage(jsonStr);
                logger.info("得到的attribute值为：{}", jsonStr.toJSONString(attribute));
                JSONObject jsonObjectAttribute = (JSONObject) JSON.toJSON(attribute);
                JSONObject pageInfo = jsonObjectAttribute.getJSONObject("pageInfo");
                JSONArray jsonArrayList = pageInfo.getJSONArray("list");
                //如果jsonArrayList为null，说明没有值，在表中不存在
                if (jsonArrayList == null || jsonArrayList.size() == 0) {
                    hashMap.put("appName","数智中台");
                    hashMap.put("appCode","800004");
                    hashMap.put("mdmCode", mdmCode);
                    hashMap.put("optionName", "数智中台");
                    jsonStr.put("jsonStr", hashMap);
                    Object  object = comparisonServiceimpl.saveEntity(jsonStr);
                    logger.info("应付单新增结果为：{}", JSON.toJSONString(object));
                    result.add(object);
                } else {
                    hashMap.put("appName","数智中台");
                    hashMap.put("appCode","800004");
                    hashMap.put("mdmCode", mdmCode);
                    hashMap.put("optionName", "数智中台");
                    jsonStr.put("jsonStr", hashMap);
                    Object object = comparisonServiceimpl.updateEntity(jsonStr);
                    logger.info("应付单更新结果为：{}", JSON.toJSONString(result));
                    result.add(object);
                }
            }
            return result;
        }catch (Exception e){
            logger.info("将数据查询之后进行组装调用通用方法错误:{}",e.getMessage());
            //保存业务数据日志
            saveTaskLivingDetails(jsonObjectUser.getString("data_id"),hashMaps.get(0).getString("documentNo"),hashMaps.get(0).toString(),result.toString(),false,"ZxBankPluginInitializer");
            e.printStackTrace();
        }
        return null;
    }

    private void saveTaskLivingDetails(String rootAppPk,String rootAppBill,String rootAppNewData,String newTransmitInfo,boolean flag,String plugin) {
        try {
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setId(UUIDUtils.getUUID());
            integrationTaskLivingDetailsEntity.setSts("Y");
            integrationTaskLivingDetailsEntity.setCreate_user_id("1");
            integrationTaskLivingDetailsEntity.setModify_user_id("1");
            integrationTaskLivingDetailsEntity.setCreate_time(new Date());
            integrationTaskLivingDetailsEntity.setModify_time(new Date());
            integrationTaskLivingDetailsEntity.setOrg_id("0");
            integrationTaskLivingDetailsEntity.setCompanyId("0");
            integrationTaskLivingDetailsEntity.setRootAppPk(rootAppPk);
            integrationTaskLivingDetailsEntity.setRootAppBill(rootAppBill);
            integrationTaskLivingDetailsEntity.setPluginId(plugin);
            integrationTaskLivingDetailsEntity.setRootAppNewData(rootAppNewData);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(newTransmitInfo);
            if(flag){
                taskLivingDetailsService.saveLogToSuccess(integrationTaskLivingDetailsEntity);
            }else {
                taskLivingDetailsService.saveLogToFail(integrationTaskLivingDetailsEntity);
            }
        }catch (Exception e){
            logger.info("抽取杭泰付款单保存日志到集成任务日志明细中失败:{}",e.getMessage());
            e.printStackTrace();
        }
    }

}
