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

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
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.invoice.dao.IInvoiceDao;
import com.hzya.frame.seeyon.invoice.dao.IInvoiceDetailsDao;
import com.hzya.frame.seeyon.invoice.entity.InvoiceEntity;
import com.hzya.frame.seeyon.invoice.entity.InvoiceImportState;
import com.hzya.frame.seeyon.invoice.entity.InvoiceState;
import com.hzya.frame.seeyon.invoice.service.IInvoiceService;
import com.hzya.frame.seeyon.util.OARestUtil;
import com.hzya.frame.seeyon.util.YzfSignUtil;
import com.hzya.frame.seeyon.zxbank.entity.PayState;
import com.hzya.frame.seeyon.zxbank.entity.ZxBankEntity;
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 javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.*;

@Service(value = "InvoiceServiceImpl")
public class InvoiceServiceImpl extends BaseService<InvoiceEntity, String> implements IInvoiceService {
    @Autowired
    private MdmModuleSourceDaoImpl mdmModuleSourceDaoImpl;

    @Autowired
    private IInvoiceDao invoiceDao;
    @Autowired
    private IInvoiceDetailsDao invoiceDetailsDao;

    @Autowired
    private IIntegrationTaskLivingDetailsService taskLivingDetailsService;
    @Autowired
    private ComparisonServiceImpl comparisonServiceimpl;
    @Autowired
    private ICtpAttachmentDao ctpAttachmentDao;
    @Autowired
    private ICtpFileDao ctpFileDao;


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

    @Value("${invoice_pdf.url:}")
    private String invoicePdfUrl;
    @Value("${invoice_ofd.url:}")
    private String invoiceOfdUrl;
    @Value("${invoice_xml.url:}")
    private String invoiceXmlUrl;

    @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 "10049"://杭泰开票申请单
                                tableName = "mdm_invoice_application";
                                listAll = bindingInvoice(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 ("10049".equals(mdmCode)) {
                                    JSONArray jsonArray = JSONArray.parseArray(resultString);
                                    if (CollectionUtils.isNotEmpty(jsonArray)) {
                                        for (Object o : jsonArray) {
                                            JSONObject attributeArray = (JSONObject) JSON.toJSON(o);
                                            String cmpApply = attributeArray.getString(tableName);
                                            JSONObject jsonObjectCmpApply = JSONObject.parseObject(cmpApply);
                                            String id = jsonObjectCmpApply.getString("data_id");//主表id
                                            String vdef1 = jsonObjectCmpApply.getString("business_no");//主表id
                                            logger.info("=====开始根据单据id:{},单据号：{},更新表：formmain_0331的推送标识", id, vdef1);
                                            InvoiceEntity invoiceEntity = new InvoiceEntity();
                                            invoiceEntity.setPush_status("1");
                                            invoiceEntity.setId(id);
                                            invoiceEntity.setDataSourceCode(mdmModuleSourceEntity.getDataSourceCode());
                                            invoiceDao.updateInvoicePush(invoiceEntity);
                                            //保存业务数据日志
                                            saveTaskLivingDetails(id, jsonObjectCmpApply.getString("business_no"), listAll.get(0).toString(), object.toString(), true,"MakeInvoicePluginInitializer");
                                        }
                                    }
                                }
                            } else {
                                saveTaskLivingDetails(JSONObject.parseObject(listAll.get(0).getString("mdm_invoice_application")).getString("data_id"), JSONObject.parseObject(listAll.get(0).getString("mdm_invoice_application")).getString("business_no"), listAll.get(0).toString(), JSON.parseObject(JSON.toJSONString(object)).getString("msg"), false,"MakeInvoicePluginInitializer");
                            }
                        }
                    }
                } else {
                    logger.info("三维单据视图数据没有需要同步中台的数据");
                }
            }catch (Exception e){
                logger.info("杭泰付款单同步失败:{}",e.getMessage());
                saveTaskLivingDetails(JSONObject.parseObject(listAll.get(0).getString("mdm_invoice_application")).getString("data_id"),JSONObject.parseObject(listAll.get(0).getString("mdm_invoice_application")).getString("business_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,"MakeInvoicePluginInitializer");
                e.printStackTrace();
            }
        }
        return BaseResult.getSuccessMessageEntity("开票申请单同步成功");
    }

    @Override
    public JsonResultEntity queryInvoiceResult(JSONObject json) {
        try {
            InvoiceEntity invoiceEntity = json.toJavaObject(InvoiceEntity.class);
            invoiceEntity.setDataSourceCode("HT-OA");
            logger.info("=======开始查询杭泰税务的开票申请单返回结果=========");
            List<InvoiceEntity> invoiceEntities = invoiceDao.queryInvoiceResult(invoiceEntity);
            if(CollectionUtils.isEmpty(invoiceEntities)){
                logger.info("=====杭泰税务中没有需要查询申请单详情得数据========");
                return BaseResult.getSuccessMessageEntity("查询成功");
            }
            for (InvoiceEntity entity : invoiceEntities) {
                entity.setDataSourceCode("HT-OA");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("serialNumber", entity.getSerial_number());
                    //发送数据
                    String result = HttpRequest.post(url).
                            header("appId", "800060").
                            header("apiCode", "8000600003").
                            header("publicKey", "ZJYAmRjjYEDgqw4UXWHZNicYclErG0hsrwKQcHukPlP0K1pCe7eDIk+3zDUT+v578prj").
                            header("secretKey", "D6AHU3PL8UsNfK6A8I6mL4X1ma2NXckX/vM7AOzI/jmzJf+R1aY06Q6SBz7Y7drHj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                            body(jsonObject.toJSONString()).
                            execute().
                            body();
                    logger.info("=====调用杭泰税务查询申请单详情的返回参数为:{}===========", result);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (!resultJson.getBoolean("flag")) {
                        saveTaskLivingDetails(entity.getSerial_number(), entity.getBusiness_no(), jsonObject.toJSONString(), resultJson.toJSONString(), false, "QueryInvoiceResultPluginInitializer");
                    } else {
                        JSONObject attribute = resultJson.getJSONObject("attribute");
                        if ("0".equals(attribute.getString("code"))) {
                            JSONObject jsonResult = JSONObject.parseObject(attribute.getString("result"));
                            if (null != jsonResult && jsonResult.getString("serialNumber").equals(entity.getSerial_number())) {
                                JSONArray jsonArray = jsonResult.getJSONArray("invoiceInfoVOList");
                                if (CollectionUtils.isNotEmpty(jsonArray)) {
                                    for (int i = 0; i < jsonArray.size(); i++) {
                                        //表单的附件字段=ctpAttachment的Sub_reference，表单的Summary_id=ctpAttachment的att_reference
                                        String sub_reference = String.valueOf(UUIDLong.longUUID());
                                        String att_reference = entity.getSummaryId();//Summary_id
                                        JSONObject invoiceInfo = jsonArray.getJSONObject(i);
                                        String invoiceCode = invoiceInfo.getString("invoiceCode");//发票代码
                                        String invoiceNumber = invoiceInfo.getString("invoiceNumber");//发票号码
                                        String resultStatus = InvoiceState.invoiceStateGetValue(jsonResult.getString("resultStatus"));//开票结果
                                        entity.setInvoice_code(invoiceCode);
                                        entity.setInvoice_number(invoiceNumber);
                                        entity.setResult_status(resultStatus);
                                        entity.setId(entity.getSerial_number());
                                        //将开票结果，发票号码，发票代码，回写OA
                                        logger.info("=======开始将开票结果，发票号码，发票代码，回写OA======");
                                        invoiceDao.updateInvoiceResult(entity);
                                        logger.info("=======将开票结果，发票号码，发票代码，回写OA完毕======");
                                        if (null != invoiceInfo.getString("url") || null != invoiceInfo.getString("ofdUrl")) {
                                            String pdfUrl = invoiceInfo.getString("url");//pdf文件
                                            String ofdUrl = invoiceInfo.getString("ofdUrl");//ofd文件
                                            String xmlUrl = invoiceInfo.getString("xmlUrl");//xml文件
                                            //获取pdf文件到本地 并为pdf取名，否则会报无法访问错误
                                            logger.info("========开始将pdf文件保存到本地========");
                                            String pdfFileName = generateFileName(pdfUrl, "PDF");
                                            String pdfSavePath = invoicePdfUrl + pdfFileName;
                                            downloadPdf(pdfUrl, pdfSavePath);
                                            logger.info("========pdf文件保存到本地完成========");
                                            File filePdf = new File(pdfSavePath);
                                            if(null !=filePdf){
                                                logger.info("========开始将pdf文件上传OA========");
                                                ManyfileUpload(filePdf, entity, sub_reference, att_reference, jsonObject);
                                                logger.info("========pdf文件上传OA完成========");
                                            }
                                            //获取ofd文件到本地
                                            logger.info("========开始将ofd文件保存到本地========");
                                            String ofdFileName = generateFileName(ofdUrl, "OFD");
                                            String ofdSavePath = invoiceOfdUrl + ofdFileName;
                                            downloadPdf(ofdUrl, ofdSavePath);
                                            logger.info("========ofd文件保存到本地完成========");
                                            File fileOfd = new File(ofdSavePath);
                                            if(null !=fileOfd){
                                                logger.info("========开始将ofd文件上传OA========");
                                                ManyfileUpload(fileOfd, entity, sub_reference, att_reference, jsonObject);
                                                logger.info("========ofd文件上传OA完成========");
                                            }
                                            //获取xml文件到本地 并为xml取名，否则会报无法访问错误
                                            logger.info("========开始将xml文件保存到本地========");
                                            String xmlFileName = generateFileName(xmlUrl, "XML");
                                            String xmlSavePath = invoiceXmlUrl + xmlFileName;
                                            downloadPdf(xmlUrl, xmlSavePath);
                                            logger.info("========pdf文件保存到本地完成========");
                                            File fileXml = new File(xmlSavePath);
                                            if(null !=fileXml){
                                                logger.info("========开始将xml文件上传OA========");
                                                ManyfileUpload(fileXml, entity, sub_reference, att_reference, jsonObject);
                                                logger.info("========xml文件上传OA完成========");
                                            }
                                            saveTaskLivingDetails(entity.getSerial_number(), entity.getBusiness_no(), jsonObject.toJSONString(), resultJson.toJSONString(), true, "QueryInvoiceResultPluginInitializer");
                                        }
                                    }
                                }else{
                                    logger.info("=======开始将开票结果回写OA======");
                                    String resultStatus = InvoiceState.invoiceStateGetValue(jsonResult.getString("resultStatus"));//开票结果
                                    entity.setResult_status(resultStatus);
                                    entity.setId(entity.getSerial_number());
                                    invoiceDao.updateInvoiceResult(entity);
                                    logger.info("=======将开票结果回写OA完毕======");
                                    saveTaskLivingDetails(entity.getSerial_number(), entity.getBusiness_no(), jsonObject.toJSONString(), resultJson.toJSONString(), false, "QueryInvoiceResultPluginInitializer");
                                }
                            }
                        }
                    }
            }
        }catch (Exception e){
            logger.info("======查询杭泰税务申请单详情失败:{}====",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    //进项发票推送结果查询（查询发票批量录入结果）
    @Override
    public JsonResultEntity queryInputInvoiceResult(JSONObject json) {
        try {
            InvoiceEntity invoiceEntity = json.toJavaObject(InvoiceEntity.class);
            invoiceEntity.setDataSourceCode("HT-OA");
            logger.info("=======开始查询杭泰税务的发票批量录入返回结果=========");
            List<InvoiceEntity> invoiceEntities = invoiceDao.queryInputInvoiceResult(invoiceEntity);
            if(CollectionUtils.isEmpty(invoiceEntities)){
                logger.info("=====杭泰税务中没有需要查询发票批量录入返回结果的数据========");
                return BaseResult.getSuccessMessageEntity("查询成功");
            }
            for (InvoiceEntity entity : invoiceEntities) {
                entity.setDataSourceCode("HT-OA");
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("serialNumber",entity.getYd_result());
                logger.info("=====调用杭泰税务查询发票批量录入结果的请求参数为:{}===========",jsonObject.toJSONString());
                //发送数据
                String result = HttpRequest.post(url).
                        header("appId", "800060").
                        header("apiCode", "8000600006").
                        header("publicKey", "ZJYAmRjjYEDgqw4UXWHZNicYclErG0hsrwKQcHukPlP0K1pCe7eDIk+3zDUT+v578prj").
                        header("secretKey", "D6AHU3PL8UsNfK6A8I6mL4X1ma2NXckX/vM7AOzI/jmzJf+R1aY06Q6SBz7Y7drHj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                        body(jsonObject.toJSONString()).
                        execute().
                        body();
                logger.info("=====调用杭泰税务查询发票批量录入结果的返回参数为:{}===========",result);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (!resultJson.getBoolean("flag")) {
                    saveTaskLivingDetails(entity.getId(), entity.getBill_code(), jsonObject.toJSONString(), resultJson.toJSONString(), false,"QueryInputInvoiceResultPluginInitializer");
                } else {
                    JSONObject attribute = resultJson.getJSONObject("attribute");
                    if("0".equals(attribute.getString("code"))) {
                        JSONObject jsonResult = JSONObject.parseObject(attribute.getString("result"));
                        if (null != jsonResult) {
                            String serialNumber = jsonResult.getString("serialNumber");//流水号
                            String status = jsonResult.getString("status");//发票批量录入返回结果状态
                            if(serialNumber.equals(entity.getYd_result())){
                                //修改发票批量录入结果状态
                                logger.info("=========开始更新进项发票的结果==========");
                                entity.setImport_result(InvoiceImportState.invoiceStateGetValue(status));
                                entity.setDataSourceCode("HT-OA");
                                invoiceDao.updateInputInvoiceResult(entity);
                                logger.info("=========更新进项发票的结果完成==========");
                                saveTaskLivingDetails(entity.getId(),entity.getBill_code(),jsonObject.toJSONString(), resultJson.toJSONString(), true,"QueryInputInvoiceResultPluginInitializer");
                            }
                        }
                    }
                        }
            }
        }catch (Exception e){
            logger.info("======查询杭泰税务发票批量录入结果失败:{}====",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    private void ManyfileUpload(File file,InvoiceEntity entity,String sub_reference,String att_reference,JSONObject jsonObject){
        logger.info("=======文件名称为:{}=====",file.getName());
        if(null !=file) {
            JSONObject jsonObjectOfd = fileUploadPdfAndOfd(file);
            if (jsonObjectOfd.getString("fileUrl") != null) {
                entity.setUrl(sub_reference);
                entity.setDataSourceCode("HT-OA");
                logger.info("===========查询开票详情开始将附件id更新OA==========");
                invoiceDao.updateInvoiceUrl(entity);
                logger.info("===========查询开票详情将附件id更新OA完毕==========");
                //根据附件id查询附件信息
                CtpFileEntity ctpFileEntity=new CtpFileEntity();
                ctpFileEntity.setId(jsonObjectOfd.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 = jsonObjectOfd.getString("fileUrl");
                    CtpAttachmentEntity ctpAttachmentEntity = new CtpAttachmentEntity();
                    ctpAttachmentEntity.setFile_url(file_url);
                    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:{}没有查询到附件信息======",jsonObjectOfd.getString("fileUrl"));
                }
            }
            file.delete();
        }else{
            logger.info("==========本地没有文件==============");
        }
    }

    public  JSONObject fileUploadPdfAndOfd(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 void downloadPdf(String pdfUrl, String savePath) {
        try {
            URL url = new URL(pdfUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 处理 HTTPS 证书（测试环境忽略验证，生产环境需移除）
            if (pdfUrl.startsWith("https")) {
                trustAllCertificates((HttpsURLConnection) connection);
            }
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(savePath);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
            } else {
                logger.info("下载失败，响应码: {}" , responseCode);
            }
            connection.disconnect();
        }catch (Exception e){
            logger.info("====查询申请单详情获取税务pdf或ofd文件失败:{}========",e.getMessage());
            e.printStackTrace();
        }
    }

    private static void trustAllCertificates(HttpsURLConnection conn) throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                    @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                    @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
                }
        };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        conn.setHostnameVerifier((hostname, session) -> true); // 忽略主机名验证
    }

    private String generateFileName(String url, String extension) {
        // 这里简单根据 URL 的参数生成文件名，你可以根据实际需求调整
        String[] parts = url.split("&");
        String fphm = "";
        for (String part : parts) {
            if (part.startsWith("fphm=")) {
                fphm = part.substring(5);
                break;
            }
        }
        return fphm + "." + extension;
    }

    private List<JSONObject> bindingInvoice(JSONObject jsonObject, MdmModuleSourceEntity mdmModuleSourceEntity, String dbCode) {
        List<JSONObject> list = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select * from v_hzya_invoice where push_status is null ");
        mdmModuleSourceEntity.setDataSourceCode(dbCode);
        List<HashMap<String, Object>> hashMaps = invoiceDao.queryInvoice(stringBuffer.toString(), mdmModuleSourceEntity);
        int i = 0;
        if (CollectionUtils.isNotEmpty(hashMaps)) {
            for (HashMap<String, Object> hashMap : hashMaps) {
                JSONObject main = new JSONObject();
                JSONObject invoice = new JSONObject();
                for (String key : hashMap.keySet()) {
                    invoice.put(key.toLowerCase(), hashMap.get(key));
                }
                //获取明细信息
                Long formmainId = (Long) hashMap.get("data_id");
                StringBuffer stringBufferDetails = new StringBuffer();
                stringBufferDetails.append("SELECT * FROM v_hzya_invoice_details WHERE f_id = '"+formmainId+"' " );
                List<HashMap<String, Object>> hashMapsDetails = invoiceDetailsDao.queryInvoiceDetails(stringBufferDetails.toString(),mdmModuleSourceEntity);
                JSONArray invoiceDetails = new JSONArray();
                if(CollectionUtils.isNotEmpty(hashMapsDetails)){
                    for (HashMap<String, Object> detailsMap : hashMapsDetails) {
                        JSONObject details = new JSONObject();
                        for (String key : detailsMap.keySet()) {
                            details.put(key.toLowerCase(), detailsMap.get(key));
                        }
                        invoiceDetails.add(details);
                    }
                }
                main.put("mdm_invoice_application_details", invoiceDetails);
                main.put("mdm_invoice_application", invoice);
                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("business_no"),hashMaps.get(0).toString(),result.toString(),false,"MakeInvoicePluginInitializer");
            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();
        }
    }

}
