package com.hzya.frame.plugin.incomeInvoiceData.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.mdm.mdmModuleSource.entity.MdmModuleSourceEntity;
import com.hzya.frame.plugin.incomeInvoiceData.dao.IIncomeInvoiceDao;
import com.hzya.frame.plugin.incomeInvoiceData.entity.IncomeInvoiceEntity;
import com.hzya.frame.plugin.incomeInvoiceData.service.IIncomeInvoiceService;
import com.hzya.frame.seeyon.util.YzfSignUtil;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.sysnew.comparison.controlsLog.dao.impl.ControlsLogDaoImpl;
import com.hzya.frame.sysnew.comparison.controlsLog.entity.ControlsLogEntity;
import com.hzya.frame.sysnew.comparison.dao.IComparisonDao;
import com.hzya.frame.sysnew.comparison.entity.ComparisonEntity;
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 org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import com.hzya.frame.basedao.service.impl.BaseService;
import org.springframework.core.task.TaskExecutor;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author makejava
 * @since 2024-06-21 13:52:35
 */
public class IncomeInvoiceServiceImpl extends BaseService<IncomeInvoiceEntity, String> implements IIncomeInvoiceService {

    private IIncomeInvoiceDao incomeInvoiceDao;
    @Autowired
    private ControlsLogDaoImpl controlsLogDaoimpl;
    @Autowired
    private IComparisonDao comparisonDao;
    @Autowired
    public void setIncomeInvoiceDao(IIncomeInvoiceDao dao) {
        this.incomeInvoiceDao = dao;
        this.dao = dao;
    }
    String cbUrl = "http://oapi.nanofintax.com/api/collect/uploadFinancialReport?accessToken=";
    String dataUrl = "http://oapi.nanofintax.com/api/invoice_receive/fp/v1/query?accessToken=";
    String tokenUrl = "http://oapi.nanofintax.com/api/getToken";
    String accessKey = "6X3B526P5HqE6ums";
    String accessSecret = "34e5fc32ac894a2ba2ade8c3852c7a0a";
    String taxNo = "91330110MAC5FPUY2U";
    Integer size = 50;
    @Resource
    private TaskExecutor taskExecutor;
    /**
     * @Author lvleigang
     * @Description  全量发票数据
     * @Date 4:28 下午 2025/4/16
     * @param requestJson
     * @return com.hzya.frame.web.entity.JsonResultEntity
     **/
    @Override
    public JsonResultEntity getIncomeInvoiceData(JSONObject requestJson) {
        //1、调用token
        String access_token = getToken();
        if (access_token == null) {
            return BaseResult.getFailureMessageEntity("token获取失败");
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String times = sdf.format(date);
        //2、调用接口获取数据
        Integer queryCursor = 1;
        JSONArray datalist = new JSONArray();
        sendBusinessData(datalist, access_token, queryCursor,times);

        if(datalist != null && datalist.size() > 0){
            for (int i = 0; i < datalist.size(); i++) {
                 JSONObject saveData = new JSONObject();
                //3、对照数据
                JSONObject jsonObject = datalist.getJSONObject(i);
                JSONObject content = jsonObject.getJSONObject("content");

                //发票号码
                String fphm = jsonObject.getString("fphm");
                if(fphm == null || "".equals(fphm) ){
                    continue;
                }
                saveData.put("fphm",fphm);
                //判断是否有这个数据
                List<JSONObject> checkData = incomeInvoiceDao.queryData(saveData);
                if(checkData != null && checkData.size() > 0){
                    continue;
                }
                saveData.put("id", String.valueOf(UUIDLong.longUUID()));
                saveData.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                saveData.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                saveData.put("org_id", "0");
                saveData.put("create_time", new Date());
                saveData.put("modify_time", new Date());
                saveData.put("sts", "Y");
                saveData.put("data_status", "Y");//新增状态
                saveData.put("add_status", "0");//新增状态
                saveData.put("update_status", "1");//修改状态
                saveData.put("delete_status", "1");//删除状态
                ComparisonEntity comparisonEntityRule = new ComparisonEntity();
                comparisonEntityRule.setRulePrefix("FP");
                comparisonEntityRule.setRuleMiddle("%Y-%m-%d");
                comparisonEntityRule.setRuleSuffix(5);
                comparisonEntityRule.setDbName("mdm_fp");
                ComparisonEntity comparisonEntityRuleGz = comparisonDao.queryComparisonRule(comparisonEntityRule);
                saveData.put("document_rule", comparisonEntityRuleGz.getDocumentRule());//单据规则
                saveData.put("document_rule_num", comparisonEntityRuleGz.getDocumentRuleNum());//单据规则流水号

                saveData.put("fphm",fphm);
                saveData.put("fpdm",content.getString("fpdm"));
                saveData.put("kprq",jsonObject.getString("kprq"));
                saveData.put("xfsh",content.getString("xfsh"));
                saveData.put("xfmc",content.getString("xfmc"));
                saveData.put("gfsh",content.getString("gfsh"));
                saveData.put("gfmc",content.getString("gfmc"));
                saveData.put("hjje",content.getString("hjje"));
                saveData.put("hjse",content.getString("hjse"));
                saveData.put("jshj",content.getString("jshj"));
                saveData.put("jym",content.getString("jym"));
                saveData.put("xfdzdh",content.getString("xfdzdh"));
                saveData.put("xfyhzh",content.getString("xfyhzh"));
                saveData.put("gfdzdh",content.getString("gfdzdh"));
                saveData.put("gfyhzh",content.getString("gfyhzh"));
                saveData.put("mmq",content.getString("mmq"));
                saveData.put("bz",content.getString("bz"));
                saveData.put("jqbh",content.getString("jqbh"));
                saveData.put("jdhm",content.getString("jdhm"));
                saveData.put("kpr",content.getString("kpr"));
                saveData.put("skr",content.getString("skr"));
                saveData.put("fhr",content.getString("fhr"));
                saveData.put("url",content.getOrDefault("url","http://prd-cabinet-1257122416.cos.ap-shanghai.myqcloud.com/recv-open-input-1313818348185971712-1362629996254053632.pdf"));
                saveData.put("ofdurl",content.getOrDefault("ofdUrl","http://prd-cabinet-1257122416.cos.ap-shanghai.myqcloud.com/recv-open-input-1313818348185971712-1362629996254053632.pdf"));
                saveData.put("xmlurl",content.getOrDefault("xmlUrl","http://prd-cabinet-1257122416.cos.ap-shanghai.myqcloud.com/recv-open-input-1313818348185971712-1362630000427386112.xml"));
                saveData.put("htbh",content.getString("contraceNumber"));

                JSONArray detaildata = content.getJSONArray("items");
                if(detaildata != null && detaildata.size() > 0){
                    for (int i1 = 0; i1 < detaildata.size(); i1++) {
                        JSONObject saveDetailData = new JSONObject();

                        saveDetailData.put("id", String.valueOf(UUIDLong.longUUID()));
                        saveDetailData.put("formmain_id", saveData.getString("id"));
                        saveDetailData.put("data_status", "Y");//新增状态

                        saveDetailData.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                        saveDetailData.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                        saveDetailData.put("org_id", "0");
                        saveDetailData.put("create_time", new Date());
                        saveDetailData.put("modify_time", new Date());
                        saveDetailData.put("sts", "Y");
                        saveDetailData.put("xh", detaildata.getJSONObject(i1).getString("xh"));
                        saveDetailData.put("ssflbm", detaildata.getJSONObject(i1).getString("ssflbm"));
                        saveDetailData.put("xmmc", detaildata.getJSONObject(i1).getString("xmmc"));
                        saveDetailData.put("ggxh", detaildata.getJSONObject(i1).getString("ggxh"));
                        saveDetailData.put("dw", detaildata.getJSONObject(i1).getString("dw"));
                        saveDetailData.put("sl", detaildata.getJSONObject(i1).getString("sl"));
                        saveDetailData.put("dj", detaildata.getJSONObject(i1).getString("dj"));
                        saveDetailData.put("je", detaildata.getJSONObject(i1).getString("je"));
                        saveDetailData.put("slv", detaildata.getJSONObject(i1).getString("slv"));
                        saveDetailData.put("se", detaildata.getJSONObject(i1).getString("se"));

                        incomeInvoiceDao.saveDetailData(saveDetailData);
                    }
                }
                incomeInvoiceDao.saveData(saveData);

                //5、保存写入日志
                ControlsLogEntity controlsLogEntity=new ControlsLogEntity();
                controlsLogEntity.setId(UUIDUtils.getUUID());
                controlsLogEntity.setFormmainId(saveData.getString("id"));
                controlsLogEntity.setSourceName("数智中台");
                controlsLogEntity.setCode("800004");
                controlsLogEntity.setSourceData(jsonObject.toString());
                controlsLogEntity.setOptionType("接口新增");
                controlsLogEntity.setOptionName("数智中台");
                controlsLogEntity.setDbName("mdm_fp_option_log");
                controlsLogEntity.setDataType("1");
                controlsLogEntity.setCreate_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
                controlsLogEntity.setModify_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
                controlsLogEntity.setOrg_id("0");
                controlsLogEntity.setRemark("插件新增");
                controlsLogDaoimpl.saveControlsLog(saveData.getString("id"), "数智中台", "800004", jsonObject.toJSONString(), "接口新增", "数智中台", "mdm_fp_option_log", "1");
            }
        }
        return BaseResult.getSuccessMessageEntity("处理成功");


    }


    /**
     * @Author lvleigang
     * @Description  获取业务数据
     * @Date 4:31 下午 2025/4/9
     * @param datalist
     * @param access_token
     * @param queryCursor
     * @param dataTime
     * @return void
     **/
    private void sendBusinessData(JSONArray datalist, String access_token, Integer queryCursor, String dataTime) {
        String url = dataUrl+access_token;
        JSONObject dayabody = new JSONObject();
        dayabody.put("accessKey",accessKey);
        long timestamp = System.currentTimeMillis();
        dayabody.put("timestamp",timestamp);
        JSONObject queryParams = new JSONObject();
        queryParams.put("page",queryCursor);
        queryParams.put("size",size);
        //queryParams.put("kprqq",dataTime);
        //queryParams.put("kprqz",dataTime);
        queryParams.put("taxNo",taxNo);
        dayabody.put("queryParams",queryParams);
        Map<String, Object> parametersMap = new HashMap<>();
        parametersMap.put("accessKey",accessKey);
        parametersMap.put("timestamp",timestamp);
        String a = YzfSignUtil.signRequest(parametersMap,accessSecret);
        dayabody.put("sign",a);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        String returndata = sendPost(url, headers, dayabody.toJSONString());

		if (returndata != null && JSONObject.isValidObject(returndata)) {
			JSONObject dataJson = JSONObject.parseObject(returndata);
			if(dataJson != null && dataJson.getString("code") != null && "0".equals( dataJson.getString("code"))){
                JSONObject data = dataJson.getJSONObject("result");
			    if(data != null  ){
                    JSONArray businessList = data.getJSONArray("data");
                    if(data.getInteger("total") > queryCursor*size){
                        queryCursor = queryCursor+1;
                        sendBusinessData(datalist, access_token, queryCursor, dataTime);
                    }
                    if(businessList != null && businessList.size() > 0){
                        datalist.addAll(businessList);
                    }
				}
			}
		}
    }

    private String getOAToken(String name) {
        String url = "http://60.204.152.210/seeyon/rest/token";
        Map<String, String> headers = null;
        String bodys = "{\"password\":\"a5ce21b8-91db-4cec-b3e3-3e44719655fd\",\"userName\":\"hzyaRest\",\"loginName\":\""+name+"\"}";
        String tokenData = sendPost(url, headers, bodys);
        String access_token = null;
        if (tokenData != null && JSONObject.isValidObject(tokenData)) {
            JSONObject tokendataJson = JSONObject.parseObject(tokenData);
            if (tokendataJson != null && tokendataJson.getString("id") != null) {
                access_token = tokendataJson.getString("id");
            }
        }
        return access_token;
    }
    /**
     * @Author lvleigang
     * @Description  获取token
     * @Date 4:18 下午 2025/4/9
     * @param
     * @return java.lang.String
     **/
    private String getToken() {
        String url = tokenUrl;
        JSONObject tokenJson = new JSONObject();
        tokenJson.put("accessKey",accessKey);
        tokenJson.put("accessSecret",accessSecret);
        String bodys = tokenJson.toJSONString();
        StringBuilder body = new StringBuilder();
        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
                    .build();
        } catch (Exception e) {
            return null;
        }
        CloseableHttpClient closeableHttpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).build();
        post.setConfig(requestConfig);//设置请求参数【超时时间】
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        try {
            if (bodys != null && !"".equals(bodys)) {
                ByteArrayEntity entity = new ByteArrayEntity(bodys.getBytes("UTF-8"));
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            response = closeableHttpClient.execute(post);

            HttpEntity entity = response.getEntity();
            body.append(EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            body.append(e.getMessage());
        } finally {
            try {
                // 关闭响应对象
                if (response != null) {
                    response.close();
                }
                // 关闭响应对象
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        logger.info("token返回结果{}",body);
        JSONObject bodyJson = JSONObject.parseObject(body.toString());
        if(bodyJson.getString("code") == null || !"0".equals(bodyJson.getString("code"))){
            return null;
        }
        JSONObject resultJson = bodyJson.getJSONObject("result");
        if(resultJson == null){
            return null;
        }
        if(resultJson.getString("accessToken") != null && !"".equals(resultJson.getString("accessToken"))){
            return resultJson.getString("accessToken");
        }
        return null;
    }

    private String sendPost(String url, Map<String, String> headers, String bodys) {
        logger.info("url："+url+"。bodys："+bodys);

        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
                    .build();
        } catch (Exception e) {

        }
        CloseableHttpClient closeableHttpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).build();
        post.setConfig(requestConfig);//设置请求参数【超时时间】
        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {
                post.setHeader(key, headers.get(key));
            }
        }
        StringBuilder body = new StringBuilder();
        try {
            if (bodys != null && !"".equals(bodys)) {
                ByteArrayEntity entity = new ByteArrayEntity(bodys.getBytes("UTF-8"));
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            response = closeableHttpClient.execute(post);
            HttpEntity entity = response.getEntity();
            body.append(EntityUtils.toString(entity, "UTF-8"));
            logger.info("返回结果：" + body);
        } catch (Exception e) {
            logger.error("请求错误：" + e.getMessage());
            body = new StringBuilder();
        } finally {
            try {
                // 关闭响应对象
                if (response != null) {
                    response.close();
                }
                // 关闭响应对象
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        logger.info("url："+url+"。bodys："+bodys+"。body"+body);

        return body.toString();
    }
    private String sendGet(String url, Map<String, String> headers) {
        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
                    .build();
        } catch (Exception e) {

        }
        CloseableHttpClient closeableHttpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
        // HttpClient
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).build();
        get.setConfig(requestConfig);//设置请求参数【超时时间】
        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {
                get.setHeader(key, headers.get(key));
            }
        }
        StringBuilder body = new StringBuilder();

        try {
            response = closeableHttpClient.execute(get);
            HttpEntity entity = response.getEntity();
            body.append(EntityUtils.toString(entity,"UTF-8"));
            logger.info("返回结果：" + body);
        } catch (Exception e) {
            logger.error("请求错误：" + e.getMessage());
            body.append(e.getMessage());
        } finally {
            try {
                // 关闭响应对象
                if (response != null) {
                    response.close();
                }
                // 关闭响应对象
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return body.toString();
    }


    /**
     * seeyon流程事件监听前置方法，绑定数据源
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public SysExtensionApiEntity setData(SysExtensionApiEntity entity) throws Exception {
        try {
            JSONObject sendBody = new JSONObject();
            String bodys = entity.getBodys();
            Map<String, String> headers = entity.getHeaders();
            JSONObject jsonObject = JSONObject.parseObject(bodys);
            String loginName = "hzya";
            String dataXml = getXml(jsonObject);
            //处理xml数据
            String oaToken = getOAToken(loginName);
            headers.put("token",oaToken);
            sendBody.put("token",oaToken);
            sendBody.put("loginName",loginName);
            sendBody.put("dataXml",dataXml);
            entity.setBodys(sendBody.toJSONString());
            //修改明细表
            if(jsonObject.getString("htbh") != null){
                IncomeInvoiceEntity incomeInvoiceEntity = new IncomeInvoiceEntity();
                incomeInvoiceEntity.setDataSourceCode("master");//todo
                //incomeInvoiceEntity.setDataSourceCode("HT-OA");//todo
                incomeInvoiceEntity.setField0003(jsonObject.getString("htbh"));//合同号
                incomeInvoiceEntity.setField0127(jsonObject.getString("fpdm"));//发票代码
                incomeInvoiceEntity.setField0128(jsonObject.getString("fphm"));//发票号码
                incomeInvoiceEntity.setField0129(jsonObject.getString("jshj"));//发票总额
                incomeInvoiceEntity.setField0130(jsonObject.getString("fpwj"));//发票文件 todo
                List<IncomeInvoiceEntity> list = incomeInvoiceDao.queryOaZb(incomeInvoiceEntity);
                if(list != null && list.size() == 1){
                    incomeInvoiceEntity.setFormmainId(list.get(0).getDataId());
                }
                List<IncomeInvoiceEntity> mxlist = incomeInvoiceDao.queryOaMx(incomeInvoiceEntity);
                if(mxlist != null && mxlist.size() == 1){
                    incomeInvoiceEntity.setDataId(mxlist.get(0).getDataId());
                    incomeInvoiceDao.updateMx(incomeInvoiceEntity);
                }
                if(mxlist == null || mxlist.size() == 0){
                    incomeInvoiceEntity.setDataId(1);
                    incomeInvoiceDao.saveMx(incomeInvoiceEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }



    private String getXml(JSONObject jsonObject) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<forms  version=\"2.1\">");
        stringBuffer.append("<formExport>");
        stringBuffer.append("<summary  id=\"142379148423086857\" name=\"formmain_0705\"/>");
        stringBuffer.append("<definitions>");
        stringBuffer.append("<column  id=\"field0001\" type=\"0\" name=\"发票代码\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0002\" type=\"0\" name=\"发票号码\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0003\" type=\"3\" name=\"开票日期\" isNullable=\"false\" length=\"255\"/>");
        stringBuffer.append("<column  id=\"field0004\" type=\"0\" name=\"销方税号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0005\" type=\"0\" name=\"销方名称\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0006\" type=\"0\" name=\"购方税号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0007\" type=\"0\" name=\"购方名称\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0008\" type=\"4\" name=\"合计金额\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0009\" type=\"4\" name=\"合计税额\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0010\" type=\"4\" name=\"价税合计\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0011\" type=\"0\" name=\"校验码\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0012\" type=\"0\" name=\"销售方地址电话\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0013\" type=\"0\" name=\"销售方开户行及账号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0014\" type=\"0\" name=\"购买方地址电话\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0015\" type=\"0\" name=\"购买方开户行及账号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0017\" type=\"0\" name=\"备注\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0018\" type=\"0\" name=\"机器编号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0019\" type=\"0\" name=\"机打号码\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0020\" type=\"0\" name=\"开票人\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0021\" type=\"0\" name=\"收款人\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0022\" type=\"0\" name=\"复核人\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0033\" type=\"0\" name=\"合同编号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0034\" type=\"0\" name=\"发票文件\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("</definitions>");
        stringBuffer.append("<values>");

        stringBuffer.append("<column  name=\"发票代码\">").append("<value>");
        stringBuffer.append(jsonObject.getString("fpdm") != null?"<![CDATA["+jsonObject.getString("fpdm")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"发票号码\">").append("<value>");
        stringBuffer.append(jsonObject.getString("fphm") != null?"<![CDATA["+jsonObject.getString("fphm")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"开票日期\">").append("<value>");
        stringBuffer.append(jsonObject.getString("kprq") != null?"<![CDATA["+jsonObject.getString("kprq")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"销方税号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("xfsh") != null?"<![CDATA["+jsonObject.getString("xfsh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"销方名称\">").append("<value>");
        stringBuffer.append(jsonObject.getString("xfmc") != null?"<![CDATA["+jsonObject.getString("xfmc")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"购方税号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("gfsh") != null?"<![CDATA["+jsonObject.getString("gfsh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"购方名称\">").append("<value>");
        stringBuffer.append(jsonObject.getString("gfmc") != null?"<![CDATA["+jsonObject.getString("gfmc")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"合计金额\">").append("<value>");
        stringBuffer.append(jsonObject.getString("hjje") != null?"<![CDATA["+jsonObject.getString("hjje")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"合计税额\">").append("<value>");
        stringBuffer.append(jsonObject.getString("hjse") != null?"<![CDATA["+jsonObject.getString("hjse")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"价税合计\">").append("<value>");
        stringBuffer.append(jsonObject.getString("jshj") != null?"<![CDATA["+jsonObject.getString("jshj")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"校验码\">").append("<value>");
        stringBuffer.append(jsonObject.getString("jym") != null?"<![CDATA["+jsonObject.getString("jym")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"销售方地址电话\">").append("<value>");
        stringBuffer.append(jsonObject.getString("xfdzdh") != null?"<![CDATA["+jsonObject.getString("xfdzdh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"销售方开户行及账号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("xfyhzh") != null?"<![CDATA["+jsonObject.getString("xfyhzh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"购买方地址电话\">").append("<value>");
        stringBuffer.append(jsonObject.getString("gfdzdh") != null?"<![CDATA["+jsonObject.getString("gfdzdh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"购买方开户行及账号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("gfyhzh") != null?"<![CDATA["+jsonObject.getString("gfyhzh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"备注\">").append("<value>");
        stringBuffer.append(jsonObject.getString("bz") != null?"<![CDATA["+jsonObject.getString("bz")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"机器编号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("jqbh") != null?"<![CDATA["+jsonObject.getString("jqbh")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"机打号码\">").append("<value>");
        stringBuffer.append(jsonObject.getString("jdhm") != null?"<![CDATA["+jsonObject.getString("jdhm")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"开票人\">").append("<value>");
        stringBuffer.append(jsonObject.getString("kpr") != null?"<![CDATA["+jsonObject.getString("kpr")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"收款人\">").append("<value>");
        stringBuffer.append(jsonObject.getString("skr") != null?"<![CDATA["+jsonObject.getString("skr")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"复核人\">").append("<value>");
        stringBuffer.append(jsonObject.getString("fhr") != null?"<![CDATA["+jsonObject.getString("fhr")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"合同编号\">").append("<value>");
        stringBuffer.append(jsonObject.getString("htbm") != null?"<![CDATA["+jsonObject.getString("htbm")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");

        stringBuffer.append("<column  name=\"发票文件\">").append("<value>");
        stringBuffer.append(jsonObject.getString("fpwj") != null?"<![CDATA["+jsonObject.getString("url")+"]]>":"");
        stringBuffer.append("</value>").append("</column>");


        stringBuffer.append("</values>");
        stringBuffer.append("<subForms>");
        stringBuffer.append("<subForm>");
        stringBuffer.append("<definitions>");
        stringBuffer.append("<column  id=\"field0023\" type=\"4\" name=\"序号1\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0024\" type=\"0\" name=\"税收分类编码\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0025\" type=\"0\" name=\"项目名称\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0026\" type=\"0\" name=\"规格型号\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0027\" type=\"0\" name=\"单位\" isNullable=\"false\" length=\"100\"/>");
        stringBuffer.append("<column  id=\"field0028\" type=\"4\" name=\"数量\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0029\" type=\"4\" name=\"单价\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0030\" type=\"4\" name=\"金额\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0031\" type=\"4\" name=\"税率\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("<column  id=\"field0032\" type=\"4\" name=\"税额\" isNullable=\"false\" length=\"20\"/>");
        stringBuffer.append("</definitions>");
        stringBuffer.append("<values>");

        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("mdm_fp_detail"));
        if(jsonArray != null&& jsonArray.size() > 0){
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject detailObject = jsonArray.getJSONObject(i);
                stringBuffer.append("<row>");
                stringBuffer.append("<column  name=\"序号1\"><value>").append(detailObject.getString("xh") != null?"<![CDATA["+detailObject.getString("xh")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"税收分类编码\"><value>").append(detailObject.getString("ssflbm") != null?"<![CDATA["+detailObject.getString("ssflbm")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"项目名称\"><value>").append(detailObject.getString("xmmc") != null?"<![CDATA["+detailObject.getString("xmmc")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"规格型号\"><value>").append(detailObject.getString("ggxh") != null?"<![CDATA["+detailObject.getString("ggxh")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"单位\"><value>").append(detailObject.getString("dw") != null?"<![CDATA["+detailObject.getString("dw")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"数量\"><value>").append(detailObject.getString("sl") != null?"<![CDATA["+detailObject.getString("sl")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"单价\"><value>").append(detailObject.getString("dj") != null?"<![CDATA["+detailObject.getString("dj")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"金额\"><value>").append(detailObject.getString("je") != null?"<![CDATA["+detailObject.getString("je")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"税率\"><value>").append(detailObject.getString("slv") != null?"<![CDATA["+detailObject.getString("slv")+"]]>":"").append("</value></column>");
                stringBuffer.append("<column  name=\"税额\"><value>").append(detailObject.getString("se") != null?"<![CDATA["+detailObject.getString("se")+"]]>":"").append("</value></column>");
                stringBuffer.append("</row>");
            }
        }
        stringBuffer.append("</values>");
        stringBuffer.append("</subForm>");
        stringBuffer.append("</subForms>");
        stringBuffer.append("</formExport>");
        stringBuffer.append("</forms>");

        return stringBuffer.toString();
    }


    /**
     * @Author lvleigang
     * @Description 财报数据推送
     * @Date 4:28 下午 2025/4/16
     * @param requestJson
     * @return com.hzya.frame.web.entity.JsonResultEntity
     **/
    @Override
    public JsonResultEntity sendFinancialReportPlugin(JSONObject requestJson) {

        logger.error("财报数据推送入参"+requestJson.toJSONString());
        JSONObject jsonStr = requestJson.getJSONObject("jsonStr");
        JSONObject businessDataStr = jsonStr.getJSONObject("businessDataStr");
        String eventType = jsonStr.getString("eventType");
        switch (eventType) {
            case "onProcessFinished"://流程结束事件，同步物料到U8C
                if(businessDataStr.getString("dataType") == null){//数据类型
                    return BaseResult.getFailureMessageEntity("数据类型为空");
                }
                if(businessDataStr.getString("dataType").equals("1")){//科目余额

                }
                if(businessDataStr.getString("dataType").equals("2")){//财报
                    String ztbm = businessDataStr.getString("ztCode");//账套编码
                    String cjzq = businessDataStr.getString("period");//采集账期
                    String rwbm = businessDataStr.getString("taskNo");//任务编码
                    if(ztbm == null || "".equals(ztbm)){
                        return BaseResult.getFailureMessageEntity("账套编码为空");
                    }
                    if(cjzq == null || "".equals(cjzq)){
                        return BaseResult.getFailureMessageEntity("采集账期为空");
                    }
                    if(rwbm == null || "".equals(rwbm)){
                        return BaseResult.getFailureMessageEntity("任务编码为空");
                    }
                    taskExecutor.execute(() -> sendFinancialReport(ztbm,cjzq,rwbm));
                    return BaseResult.getSuccessMessageEntity("数据获取成功");
                }
                if(businessDataStr.getString("dataType").equals("3")){//进项发票
                    return BaseResult.getFailureMessageEntity("数据类型错误");
                }
                if(businessDataStr.getString("dataType").equals("4")){//销项发票
                    return BaseResult.getFailureMessageEntity("数据类型错误");
                }
                return BaseResult.getSuccessMessageEntity("推送数据成功");
            default:
                return BaseResult.getFailureMessageEntity("未匹配到流程监听事件！当前传入的eventType：" + eventType);
        }



    }


    /**
     * @Author lvleigang
     * @Description
     * @Date 3:18 下午 2025/4/24
     * @param ztbm 账套编码
     * @param cjzq 采集账期
     * @param rwbm 任务编码
     * @return com.hzya.frame.web.entity.JsonResultEntity
     **/
    private JsonResultEntity sendFinancialReport(String ztbm ,String cjzq,String rwbm) {
        String access_token = getToken();
        if (access_token == null) {
            return BaseResult.getFailureMessageEntity("token获取失败");
        }
        String url = cbUrl+access_token;

        Date date = null;
        String qncjzq = null;
        IncomeInvoiceEntity dyAloneId = null;
        JSONObject dydata = null;
        JSONObject qndata = null;
        IncomeInvoiceEntity qnAloneId = null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        try {
            date = sdf.parse(cjzq);
        } catch (ParseException e) {
            return BaseResult.getSuccessMessageEntity("采集账期格式错误");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -1);
        Date qn = calendar.getTime();
        qncjzq = sdf.format(qn);

        //查询当月帐套组织
        IncomeInvoiceEntity jnentity = new IncomeInvoiceEntity();
        jnentity.setDataSourceCode("htBip");
        jnentity.setSysData(cjzq);
        jnentity.setOrgCode(ztbm);
        List<IncomeInvoiceEntity> jnlist = incomeInvoiceDao.queryZtzz(jnentity);
        if(jnlist != null && jnlist.size() == 1){
            dyAloneId = jnlist.get(0);
        }else {
            return BaseResult.getSuccessMessageEntity("未查询到当月的财报数据，不推送");
        }
        //查询去年当帐套组织
        IncomeInvoiceEntity qnentity = new IncomeInvoiceEntity();
        qnentity.setDataSourceCode("htBip");
        qnentity.setSysData(qncjzq);
        qnentity.setOrgCode(ztbm);
        List<IncomeInvoiceEntity> qnlist = incomeInvoiceDao.queryZtzz(qnentity);
        if(qnlist != null && qnlist.size() == 1){
            qnAloneId = qnlist.get(0);
        }else {
            logger.info("未查询到去年当期的财报数据");
        }

        //查询当月的财报数据
        IncomeInvoiceEntity jnquerydata = new IncomeInvoiceEntity();
        jnquerydata.setDataSourceCode("htBip");
        jnquerydata.setAloneId(dyAloneId.getAloneId());
        List<JSONObject> dydataList = incomeInvoiceDao.queryByAloneId(jnquerydata);
        if(dydataList != null && dydataList.size() == 1){
            dydata = dydataList.get(0);
        }else {
            return BaseResult.getSuccessMessageEntity("未查询到当月的财报数据，不推送");
        }
        //查询去年当期的财报数据
        if(qnAloneId != null){
            //查找去年数据
            IncomeInvoiceEntity qnquerydata = new IncomeInvoiceEntity();
            qnquerydata.setDataSourceCode("htBip");
            qnquerydata.setAloneId(qnAloneId.getAloneId());
            List<JSONObject> qndataList = incomeInvoiceDao.queryByAloneId(qnquerydata);
            if(qndataList != null && qndataList.size() == 1){
                qndata = qndataList.get(0);
            }
        }
        //拼接数据
        JSONObject sendData = new JSONObject();
        sendData.put("accessKey",accessKey);
        long timestamp = System.currentTimeMillis();
        sendData.put("timestamp",timestamp);
        sendData.put("taskNo",rwbm);
        sendData.put("period",cjzq);

        JSONArray reportList = new JSONArray();
        JSONObject zcfzb = new JSONObject();//资产负债表1：期末余额 2：年初余额
        zcfzb.put("period",cjzq);
        zcfzb.put("reportType",1);
        JSONArray reportSubjects1 = new JSONArray();
        setDataToArray("货币资金",dydata.getString("AM10251"),dydata.getString("AM10250"),reportSubjects1);
        setDataToArray("短期借款",dydata.getString("AM10249"),dydata.getString("AM10248"),reportSubjects1);
        setDataToArray("交易性金融资产",dydata.getString("BMPQW10U"),dydata.getString("BMP81A2Z"),reportSubjects1);
        setDataToArray("以公允价值计量且其变动计入当期损益的金融负债",dydata.getString("AM10227"),dydata.getString("AM10226"),reportSubjects1);
        setDataToArray("应收票据",dydata.getString("AM10189"),dydata.getString("AM10188"),reportSubjects1);
        setDataToArray("应付票据",dydata.getString("AM10187"),dydata.getString("AM10186"),reportSubjects1);
        setDataToArray("应收账款",dydata.getString("AM10171"),dydata.getString("AM10170"),reportSubjects1);
        setDataToArray("应付账款",dydata.getString("AM10169"),dydata.getString("AM10168"),reportSubjects1);
        setDataToArray("减：坏账准备",dydata.getString("AM10153"),dydata.getString("AM10152"),reportSubjects1);
        setDataToArray("预收款项",dydata.getString("AM10151"),dydata.getString("AM10150"),reportSubjects1);
        setDataToArray("预付款项",dydata.getString("AM10135"),dydata.getString("AM10134"),reportSubjects1);
        setDataToArray("合同负债",dydata.getString("AM10133"),dydata.getString("AM10132"),reportSubjects1);
        setDataToArray("应收利息",dydata.getString("AM10117"),dydata.getString("AM10116"),reportSubjects1);
        setDataToArray("应付职工薪酬",dydata.getString("AM10115"),dydata.getString("AM10114"),reportSubjects1);
        setDataToArray("应收股利",dydata.getString("AM10099"),dydata.getString("AM10098"),reportSubjects1);
        setDataToArray("应交税费",dydata.getString("AM10097"),dydata.getString("AM10096"),reportSubjects1);
        setDataToArray("其他应收款",dydata.getString("AM10081"),dydata.getString("AM10080"),reportSubjects1);
        setDataToArray("应付利息",dydata.getString("AM10079"),dydata.getString("AM10078"),reportSubjects1);
        setDataToArray("减：坏账准备",dydata.getString("AM10063"),dydata.getString("AM10062"),reportSubjects1);
        setDataToArray("应付股利",dydata.getString("AM10061"),dydata.getString("AM10060"),reportSubjects1);
        setDataToArray("存货",dydata.getString("AM10048"),dydata.getString("AM10047"),reportSubjects1);
        setDataToArray("其他应付款",dydata.getString("AM10046"),dydata.getString("AM10045"),reportSubjects1);
        setDataToArray("合同资产",dydata.getString("AM10033"),dydata.getString("AM10032"),reportSubjects1);
        setDataToArray("其他流动资产",dydata.getString("AM10348"),dydata.getString("AM10347"),reportSubjects1);
        setDataToArray("长期借款",dydata.getString("AM10316"),dydata.getString("AM10315"),reportSubjects1);
        setDataToArray("应付债券",dydata.getString("AM10301"),dydata.getString("AM10300"),reportSubjects1);
        setDataToArray("债权投资",dydata.getString("AM10288"),dydata.getString("AM10287"),reportSubjects1);
        setDataToArray("长期应收款",dydata.getString("AM10268"),dydata.getString("AM10266"),reportSubjects1);
        setDataToArray("长期股权投资",dydata.getString("AM10246"),dydata.getString("AM10244"),reportSubjects1);
        setDataToArray("租赁负债",dydata.getString("AM10242"),dydata.getString("AM10241"),reportSubjects1);
        setDataToArray("长期应付款",dydata.getString("AM10220"),dydata.getString("AM10219"),reportSubjects1);
        setDataToArray("其他非流动金融资产",dydata.getString("BMS13DPL"),dydata.getString("BM6TFKPL"),reportSubjects1);
        setDataToArray("专项应付款",dydata.getString("AM10198"),dydata.getString("AM10197"),reportSubjects1);
        setDataToArray("投资性房地产",dydata.getString("AM10224"),dydata.getString("AM10222"),reportSubjects1);
        setDataToArray("预计负债",dydata.getString("AM10180"),dydata.getString("AM10179"),reportSubjects1);
        setDataToArray("递延收益",dydata.getString("AM10162"),dydata.getString("AM10161"),reportSubjects1);
        setDataToArray("递延所得税负债",dydata.getString("AM10144"),dydata.getString("AM10143"),reportSubjects1);
        setDataToArray("固定资产",dydata.getString("AM10202"),dydata.getString("AM10200"),reportSubjects1);
        setDataToArray("减：累计折旧",dydata.getString("AM10184"),dydata.getString("AM10182"),reportSubjects1);
        setDataToArray("减：固定资产减值准备",dydata.getString("AM10166"),dydata.getString("AM10164"),reportSubjects1);
        setDataToArray("在建工程",dydata.getString("AM10148"),dydata.getString("AM10146"),reportSubjects1);
        setDataToArray("实收资本（或股本）",dydata.getString("AM10054"),dydata.getString("AM10053"),reportSubjects1);
        setDataToArray("工程物资",dydata.getString("AM10130"),dydata.getString("AM10128"),reportSubjects1);
        setDataToArray("固定资产清理",dydata.getString("AM10112"),dydata.getString("AM10110"),reportSubjects1);
        setDataToArray("资本公积",dydata.getString("AM10354"),dydata.getString("AM10352"),reportSubjects1);
        setDataToArray("使用权资产",dydata.getString("AM10058"),dydata.getString("AM10056"),reportSubjects1);
        setDataToArray("减：库存股",dydata.getString("AM10339"),dydata.getString("AM10337"),reportSubjects1);
        setDataToArray("减：累计折旧",dydata.getString("AM10043"),dydata.getString("AM10041"),reportSubjects1);
        setDataToArray("减：使用权资产减值准备",dydata.getString("AM10028"),dydata.getString("AM10026"),reportSubjects1);
        setDataToArray("盈余公积",dydata.getString("AM10309"),dydata.getString("AM10307"),reportSubjects1);
        setDataToArray("无形资产",dydata.getString("AM10013"),dydata.getString("AM10011"),reportSubjects1);
        setDataToArray("未分配利润",dydata.getString("AM10294"),dydata.getString("AM10292"),reportSubjects1);
        setDataToArray("减：累计摊销",dydata.getString("CM10002"),dydata.getString("CM10000"),reportSubjects1);
        setDataToArray("减：无形资产减值准备",dydata.getString("AM10342"),dydata.getString("AM10340"),reportSubjects1);
        setDataToArray("开发支出",dydata.getString("AM10327"),dydata.getString("AM10325"),reportSubjects1);
        setDataToArray("商誉",dydata.getString("AM10312"),dydata.getString("AM10310"),reportSubjects1);
        setDataToArray("长期待摊费用",dydata.getString("AM10297"),dydata.getString("AM10295"),reportSubjects1);
        setDataToArray("递延所得税资产",dydata.getString("AM10283"),dydata.getString("AM10281"),reportSubjects1);
        setDataToArray("其他非流动资产",dydata.getString("AM10259"),dydata.getString("AM10257"),reportSubjects1);


        zcfzb.put("reportSubjects",reportSubjects1);

        JSONObject llb = new JSONObject();//利润表1：本年累计 2：上年累计
        llb.put("period",cjzq);
        llb.put("reportType",2);
        JSONArray reportSubjects2 = new JSONArray();

        setDataToArray("一、营业收入",dydata.getString("AM10267"),qndata.getString("AM10267"),reportSubjects2);
        setDataToArray("其中:主营业务收入",dydata.getString("AM10245"),qndata.getString("AM10245"),reportSubjects2);
        setDataToArray("其他业务收入",dydata.getString("AM10223"),qndata.getString("AM10223"),reportSubjects2);
        setDataToArray("减：营业成本",dydata.getString("AM10201"),qndata.getString("AM10201"),reportSubjects2);
        setDataToArray("其中:主营业务成本",dydata.getString("AM10183"),qndata.getString("AM10183"),reportSubjects2);
        setDataToArray("其他业务成本",dydata.getString("AM10165"),qndata.getString("AM10165"),reportSubjects2);
        setDataToArray("税金及附加",dydata.getString("AM10147"),qndata.getString("AM10147"),reportSubjects2);
        setDataToArray("销售费用",dydata.getString("AM10129"),qndata.getString("AM10129"),reportSubjects2);
        setDataToArray("管理费用",dydata.getString("AM10111"),qndata.getString("AM10111"),reportSubjects2);
        setDataToArray("财务费用（收益以\"－\"号填列）",dydata.getString("AM10093"),qndata.getString("AM10093"),reportSubjects2);
        setDataToArray("其中：利息费用",dydata.getString("AM10075"),qndata.getString("AM10075"),reportSubjects2);
        setDataToArray("利息收入",dydata.getString("AM10057"),qndata.getString("AM10057"),reportSubjects2);
        setDataToArray("研发费用",dydata.getString("AM10042"),qndata.getString("AM10042"),reportSubjects2);
        setDataToArray("资产减值损失",dydata.getString("AM10027"),qndata.getString("AM10027"),reportSubjects2);
        setDataToArray("信用减值损失",dydata.getString("AM10012"),qndata.getString("AM10012"),reportSubjects2);
        setDataToArray("加：公允价值变动净收益（净损失以\"－\"号填列）",dydata.getString("CM10003"),qndata.getString("CM10003"),reportSubjects2);
        setDataToArray("投资净收益（净损失以\"－\"号填列）",dydata.getString("AM10343"),qndata.getString("AM10343"),reportSubjects2);
        setDataToArray("资产处置收益（净损失以\"－\"号填列）",dydata.getString("AM10328"),qndata.getString("AM10328"),reportSubjects2);
        setDataToArray("其他收益",dydata.getString("AM10313"),qndata.getString("AM10313"),reportSubjects2);
        setDataToArray("二、营业利润",dydata.getString("AM10298"),qndata.getString("AM10298"),reportSubjects2);
        setDataToArray("加:营业外收入",dydata.getString("AM10282"),qndata.getString("AM10282"),reportSubjects2);
        setDataToArray("减:营业外支出",dydata.getString("AM10258"),qndata.getString("AM10258"),reportSubjects2);
        setDataToArray("三、利润总额（亏损总额以“-”号填列）",dydata.getString("AM10236"),qndata.getString("AM10236"),reportSubjects2);
        setDataToArray("减:所得税费用",dydata.getString("AM10214"),qndata.getString("AM10214"),reportSubjects2);
        setDataToArray("四、净利润（净亏损以“-”号填列）",dydata.getString("AM10193"),qndata.getString("AM10193"),reportSubjects2);

        llb.put("reportSubjects",reportSubjects2);

        JSONObject xjll = new JSONObject();//现金流量表1：本年累计 2：上年累计
        xjll.put("period",cjzq);
        xjll.put("reportType",3);
        JSONArray reportSubjects3 = new JSONArray();
        setDataToArray("销售商品、提供劳务收到的现金",dydata.getString("AM10240"),qndata.getString("AM10240"),reportSubjects3);
        setDataToArray("收到的税费返还",dydata.getString("AM10218"),qndata.getString("AM10218"),reportSubjects3);
        setDataToArray("收到的其他与经营活动有关的现金",dydata.getString("AM10196"),qndata.getString("AM10196"),reportSubjects3);
        setDataToArray("现金收入小计",dydata.getString("AM10160"),qndata.getString("AM10160"),reportSubjects3);
        setDataToArray("购买商品、接受劳务支付的现金",dydata.getString("AM10142"),qndata.getString("AM10142"),reportSubjects3);
        setDataToArray("支付给职工以及为职工支付的现金",dydata.getString("AM10124"),qndata.getString("AM10124"),reportSubjects3);
        setDataToArray("支付的各项税费",dydata.getString("AM10106"),qndata.getString("AM10106"),reportSubjects3);
        setDataToArray("支付的其他与经营活动有关的现金",dydata.getString("AM10088"),qndata.getString("AM10088"),reportSubjects3);
        setDataToArray("现金流出小计",dydata.getString("AM10052"),qndata.getString("AM10052"),reportSubjects3);
        setDataToArray("经营活动产生的现金流量净额",dydata.getString("AM10022"),qndata.getString("AM10022"),reportSubjects3);
        setDataToArray("收回投资所收到的现金",dydata.getString("AM10353"),qndata.getString("AM10353"),reportSubjects3);
        setDataToArray("取得投资收益所收到的现金",dydata.getString("AM10338"),qndata.getString("AM10338"),reportSubjects3);
        setDataToArray("处置固定资产、无形资产和其他长期资产所收回的现金净额",dydata.getString("AM10323"),qndata.getString("AM10323"),reportSubjects3);
        setDataToArray("处置子公司及其他营业单位收到的现金净额",dydata.getString("AM10308"),qndata.getString("AM10308"),reportSubjects3);
        setDataToArray("收到的其他与投资活动有关的现金",dydata.getString("AM10293"),qndata.getString("AM10293"),reportSubjects3);
        setDataToArray("现金流入小计",dydata.getString("AM10277"),qndata.getString("AM10277"),reportSubjects3);
        setDataToArray("购建固定资产、无形资产和其他长期资产所支付的现金",dydata.getString("AM10253"),qndata.getString("AM10253"),reportSubjects3);
        setDataToArray("投资所支付的现金",dydata.getString("AM10231"),qndata.getString("AM10231"),reportSubjects3);
        setDataToArray("取得子公司及其他营业单位收到的现金净额",dydata.getString("AM10209"),qndata.getString("AM10209"),reportSubjects3);
        setDataToArray("其他与投资有关",dydata.getString("AM10191"),qndata.getString("AM10191"),reportSubjects3);
        setDataToArray("现金流出小计",dydata.getString("AM10173"),qndata.getString("AM10173"),reportSubjects3);
        setDataToArray("投资活动产生的现金流量净额",dydata.getString("AM10155"),qndata.getString("AM10155"),reportSubjects3);
        setDataToArray("吸收投资所收到的现金",dydata.getString("AM10119"),qndata.getString("AM10119"),reportSubjects3);
        setDataToArray("子公司吸收少数股东投资收到的现金",dydata.getString("AM10101"),qndata.getString("AM10101"),reportSubjects3);
        setDataToArray("借贷所收到现金",dydata.getString("AM10083"),qndata.getString("AM10083"),reportSubjects3);
        setDataToArray("发行债券收到的现金",dydata.getString("AM10065"),qndata.getString("AM10065"),reportSubjects3);
        setDataToArray("收到的其他与筹资活动有关的现金",dydata.getString("AM10050"),qndata.getString("AM10050"),reportSubjects3);
        setDataToArray("现金流入小计",dydata.getString("AM10035"),qndata.getString("AM10035"),reportSubjects3);
        setDataToArray("偿还债务所支付的现金",dydata.getString("AM10020"),qndata.getString("AM10020"),reportSubjects3);
        setDataToArray("分配股利、利润、偿付利息所支付的现金",dydata.getString("AM10005"),qndata.getString("AM10005"),reportSubjects3);
        setDataToArray("支付的其他与筹资活动有关的现金",dydata.getString("AM10350"),qndata.getString("AM10350"),reportSubjects3);
        setDataToArray("现金流出小计",dydata.getString("AM10335"),qndata.getString("AM10335"),reportSubjects3);
        setDataToArray("筹资活动产生的现金流量净额",dydata.getString("AM10320"),qndata.getString("AM10320"),reportSubjects3);
        setDataToArray("四、汇率变动对现金流量的影响",dydata.getString("AM10305"),qndata.getString("AM10305"),reportSubjects3);
        setDataToArray("五、现金及现金等价物净增加额",dydata.getString("AM10290"),qndata.getString("AM10290"),reportSubjects3);

        xjll.put("reportSubjects",reportSubjects3);

        reportList.add(zcfzb);
        reportList.add(llb);
        reportList.add(xjll);

        sendData.put("reportList",reportList);
        String a = YzfSignUtil.signRequest(sendData,accessSecret);
        sendData.put("sign",a);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        String returndata = sendPost(url, headers, sendData.toJSONString());

        if (returndata != null && JSONObject.isValidObject(returndata)) {
            JSONObject dataJson = JSONObject.parseObject(returndata);
            if(dataJson != null && dataJson.getString("code") != null && "0".equals( dataJson.getString("code"))){
                JSONObject data = dataJson.getJSONObject("result");
                if(data != null  ){
                    if(data != null && data.getString("resultCode") != null && "0".equals( data.getString("resultCode"))){
                        return BaseResult.getSuccessMessageEntity("执行成功");
                    }else {
                        return BaseResult.getFailureMessageEntity("发送失败："+data.getString("message"));
                    }
                }else {
                    return BaseResult.getFailureMessageEntity("发送失败："+returndata);
                }
            }else {
                return BaseResult.getFailureMessageEntity("发送失败："+returndata);
            }
        }else {
            return BaseResult.getFailureMessageEntity("发送失败："+returndata);
        }
    }

    private void setDataToArray(String subjectName, String value,String value2, JSONArray reportSubjects) {
        if(value != null && !"".equals(value)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subjectName",subjectName);
            jsonObject.put("value",new BigDecimal(value));
            jsonObject.put("valueType",1);
            reportSubjects.add(jsonObject);
        }
        if(value2 != null && !"".equals(value2)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subjectName",subjectName);
            jsonObject.put("value",new BigDecimal(value2));
            jsonObject.put("valueType",2);
            reportSubjects.add(jsonObject);
        }
    }
}
