package com.dgtly.sync.service;

import cn.hutool.core.date.DateTime;
import com.dgtly.common.config.Global;
import com.dgtly.common.utils.DateUtils;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.http.HttpUtils;
import com.dgtly.system.service.ICustomersExtService;
import com.dgtly.system.service.IMetaHanaDeliverSignService;
import com.dgtly.system.service.ISysUserOrderAuthorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class HanaOrderComponent {

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

    @Value(value = "${hana.hana-driver:none}")
    private String hanaDriver;
    @Value(value = "${hana.hana-url:none}")
    private String hanaUrl;
    @Value(value = "${hana.hana-user:none}")
    private String hanaUser;
    @Value(value = "${hana.hana-pwd:none}")
    private String hanaPwd;

    @Value(value = "${hana.mysql-driver:none}")
    private String mysqlDriver;
    @Value(value = "${hana.mysql-url:none}")
    private String mysqlUrl;
    @Value(value = "${hana.mysql-user:none}")
    private String mysqlUser;
    @Value(value = "${hana.mysql-pwd:none}")
    private String mysqlPwd;

    /*清空SalesOrder缓存*/
    @Value(value = "${ruoyi.orderGetDataHook}")
    private String orderGetDataHook;
    /*清空deliverOrder缓存*/
    @Value(value = "${ruoyi.deliverGetDataHook}")
    private String deliverGetDataHook;

    @Autowired
    private ISysUserOrderAuthorService userOrderAuthorService;

    @Autowired
    private IMetaHanaDeliverSignService metaHanaDeliverSignService;

    public HanaOrderComponent() {
    }

    public void hanaSalesOrderSync() throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT\n" +
                "                T.VBELN,\n" +
                "                T.POSNR,\n" +
                "                T.VKORG,\n" +
                "                T.VKORG_TXT,\n" +
                "                T.VTWEG,\n" +
                "                T.KUNNR,\n" +
                "                T.NAME1,\n" +
                "                T.ROUTE,\n" +
                "                T.SPART,\n" +
                "                T.VKGRP,\n" +
                "                T.WERKS,\n" +
                "                T.WERKS_NAME,\n" +
                "                T.LGORT ,\n" +
                "                T.LGOBE ,\n" +
                "                T.AUART,\n" +
                "                T.ERDAT,\n" +
                "                T.ERDAT_P,\n" +
                "                T.LFSTA,\n" +
                "                T.MATNR,\n" +
                "                T.ZMAKTXX,\n" +
                "                T.PRODHA_TXT, \n" +
                "                T.GROES,\n" +
                "                T.ZCMFRE,\n" +
                "                T.ZCMGST,\n" +
                "                T.ABGRU,\n" +
                "                T.ZZMENG,\n" +
                "                T.ZZMENG2,\n" +
                "                T.ZNETWR,\n" +
                "                T.ZRFMNG,\n" +
                "                T.ZRFMNG2,\n" +
                "                T.ZNETWR1,\n" +
                "                T.VSBED,\n" +
                "                T.VSBED_TXT,\n" +
                "                T.MEINS,\n" +
                "                T.TRAGR,\n" +
                "                T.ABRVW,\n" +
                "                T.ABRVW_TXT,\n" +
                "                T.VKBUR, \n" +
                "                T.ZCODE1,\n" +
                "                T.ZCODE1_DESC,\n" +
                "                T.ZCODE4,\n" +
                "                T.ZCODE4_DESC, \n" +
                "                T.KVGR3,\n" +
                "                T.KVGR4,\n" +
                "                T.POSID, \n" +
                "               T.PD_NO,\n"+
                "\t replace(replace(T.BSTKD,CHAR(10),''),CHAR(13),'') BSTKD, \n" +
                "               T.NETPR,\n"+
                "               T.NTGEW_MARA,\n"+
                "               T.PSTYV,\n"+
                "               T.UEPOS, \n"+
                "               T.MAABC, \n"+
                "               T.ZCODE8, \n"+
                "               T.ZBEZEI1,"+
                "\t replace(replace(T.BSTKD_E,CHAR(10),''),CHAR(13),'') BSTKD_E \n" +
                "FROM (\n" +
                "\n" +
                "SELECT\n" +
                "\t\t\t\tDISTINCT  concat(A.VBELN, A.POSNR) ss,\n" +
                "                A.VBELN,\n" +
                "                A.POSNR,\n" +
                "                A.VKORG,\n" +
                "                A.VKORG_TXT,\n" +
                "                A.VTWEG,\n" +
                "                A.KUNNR,\n" +
                "                A.NAME1,\n" +
                "                A.ROUTE,\n" +
                "                A.SPART,\n" +
                "                A.VKGRP,\n" +
                "                A.WERKS,\n" +
                "                C.NAME1 WERKS_NAME,\n" +
                "                E.LGORT ,\n" +
                "                E.LGOBE ,\n" +
                "                A.AUART,\n" +
                "                A.ERDAT,\n" +
                "                A.ERDAT_P,\n" +
                "                A.LFSTA,\n" +
                "                A.MATNR,\n" +
                "                A.ZMAKTXX,\n" +
                "                D.PRODHA3_TXT PRODHA_TXT, \n" +
                "                A.GROES,\n" +
                "                A.ZCMFRE,\n" +
                "                A.ZCMGST,\n" +
                "                A.ABGRU,\n" +
                "                A.ZZMENG,\n" +
                "                A.ZZMENG2,\n" +
                "                A.ZNETWR,\n" +
                "                A.ZRFMNG,\n" +
                "                A.ZRFMNG2,\n" +
                "                A.ZNETWR1,\n" +
                "                A.VSBED,\n" +
                "                A.VSBED_TXT,\n" +
                "                A.MEINS,\n" +
                "                B.TRAGR, "+
                "                A.ABRVW, "+
                "                A.ABRVW_TXT, "+
                "                A.VKBUR,  " +
                "                CAL.ZCODE1,\n" +
                "                CAL.ZCODE1_DESC,\n" +
                "                CAL.ZCODE4,\n" +
                "                CAL.ZCODE4_DESC, "+
                "                A.KVGR3, "+
                "                A.KVGR4, "+
                "                A.POSID, "+
                "               A.PD_NO, "+
                "               A.BSTKD,"+
                "               A.NETPR, "+
                "               A.NTGEW_MARA,"+
                "               A.PSTYV,"+
                "               A.UEPOS,"+
                "               A.MAABC,"+
                "               A.ZCODE8,"+
                 "               A.ZBEZEI1,"+
                "                A.BSTKD_E "+
                "FROM \"_SYS_BIC\".\"com.sd/CAL_SALES\"" +
                "('PLACEHOLDER' = ('$$IP_ENDDATE$$',\n" +
                "\t '"+DateUtils.dateTime()+"'),\n" +
                "\t 'PLACEHOLDER' = ('$$IP_STATDATE$$',\n" +
                "\t '"+DateUtils.getThreeMonthDate()+"'),\n" +
                "\t 'PLACEHOLDER' = ('$$language$$', '1')) A  LEFT JOIN ERP.MARA B ON B.MATNR = A.MATNR \n" +
                "\t LEFT JOIN ERP.T001W C ON C.WERKS = A.WERKS \n" +
                "\t LEFT JOIN ERP.ZHANAMATDOWN D ON D.MATNR = A.MATNR \n" +
                "\t LEFT JOIN ERP.T001L E ON E.WERKS = A.WERKS AND E.LGORT = A.LGORT \n" +
                "\t LEFT JOIN \"_SYS_BIC\".\"com.md/CAL_MAT_HIERARCHY_S\" CAL ON B.MATNR=CAL.MATNR AND A.VTWEG=CAL.VTWEG \n" +
                "\t WHERE A.VKORG != '4000' AND A.VTWEG IN ('D9','Y9','D8') AND A.SPART != '16' AND A.AUART NOT IN ('31','32','33','35','36','39','29','11','45') " +
                "and ((A.ZCMGST !='信用通过' and A.ABGRU='') or (A.ZCMGST ='信用通过' and A.ABGRU=''))\n" +
                " order by A.VBELN,A.POSNR " +
                " ) T");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("SalesOrder查询用时：" + (endTime - startTime)+"毫秒");
//        this.insertSalesOrderResult(rs);
        this.createSalesOrderTxt(rs);
        this.runLoadSalesOrder();
        this.closeConnection(con, pstmt);

    }

    /**
     * @description: C类产品订单标记
     * @param: []
     * @return: void
     * @author: njs
     * @date: 2025/5/7 13:24
     */
    public void hanaErpOrderSyncByC() throws  Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT MAABC,SPRAS,TMABC,MANDT FROM ERP.TMABCT");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("TMABCT查询用时：" + (endTime - startTime)+"毫秒");
        this.createTmabcTxt(rs);
        this.runLoadTmabcTxt();
        this.closeConnection(con, pstmt);

    }

    public void certificationSync()  {
        metaHanaDeliverSignService.certificationSync();
    }


    /**
     * @description: 交货单电子签收数据同步
     * @param: []
     * @return: void
     * @author: njs
     * @date: 2024/12/31 10:14
     */
    public void hanaSalesDeliverSignatureSync() throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT\n" +
                "\t VBELN,\n" +
                 "\t POSNR,\n" +
                "\t MATNR,\n" +
                "\t VGBEL,\n" +
                "\t VGPOS, \n"+
                "\t ERDAT_SO,\n" +
                "\t LFIMG,\n" +
                "\t MODIFIEDVALUE,\n" +
                "\t LFIMG_CY,\n" +
                "\t ZDATE_KH,\n" +
                "\t ZTIME_KH,\n" +
                "\t ZVBELN_YCHH,\n" +
                "\t ZSTATUS_HH,\n" +
                "\t CONTRACTID, \n" +
                "\t BIZNO, \n" +
                 "\t MANDT \n" +
                " FROM  ERP.ZSDT056 where ERDAT_SO between ADD_MONTHS(CURRENT_DATE, -3) AND CURRENT_DATE");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("hanaSalesDeliverSignatureSync查询用时：" + (endTime - startTime)+"毫秒");
        this.createDeliverSignatureTxt(rs);
        this.runLoadDeliverSignature();
        this.closeConnection(con, pstmt);

    }
    /*批量插入*/
  /*  private void insertSalesOrderResult(ResultSet rs) throws Exception {
        Connection conn = null;
        PreparedStatement pstm =null;
        PreparedStatement pstm1 =null;
        try {
            conn = getMysqlConnection();
            String sql1 = "TRUNCATE TABLE sap_hana_sales_order";
            String sql = "INSERT INTO sap_hana_sales_order values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            pstm1 = conn.prepareStatement(sql1);
            pstm1.execute();
            pstm = conn.prepareStatement(sql);
            Long startTime = System.currentTimeMillis();
            conn.setAutoCommit(false);

            if (rs.next()) {
                long i=0;
                ResultSetMetaData rsmd = rs.getMetaData();
                *//*循环遍历数据，创建执行批量插入的sql语句*//*
                do {
                    i++;
                    pstm.setString(1, rs.getString("VBELN"));
                    pstm.setString(2, rs.getString("POSNR"));
                    pstm.setString(3, rs.getString("VKORG"));
                    pstm.setString(4, rs.getString("VKORG_TXT"));
                    pstm.setString(5, rs.getString("VTWEG"));
                    pstm.setString(6, rs.getString("KUNNR"));
                    pstm.setString(7, rs.getString("NAME1"));
                    pstm.setString(8, rs.getString("ROUTE"));
                    pstm.setString(9, rs.getString("SPART"));
                    pstm.setString(10, rs.getString("VKGRP"));
                    pstm.setString(11, rs.getString("WERKS"));
                    pstm.setString(12, rs.getString("AUART"));
                    pstm.setString(13, rs.getString("ERDAT"));
                    pstm.setString(14, rs.getString("ERDAT_P"));
                    pstm.setString(15, rs.getString("LFSTA"));
                    pstm.setString(16, rs.getString("MATNR"));
                    pstm.setString(17, rs.getString("ZMAKTXX"));
                    pstm.setString(18, rs.getString("GROES"));
                    pstm.setString(19, "");
                    pstm.setString(20, rs.getString("ZCMFRE"));
                    pstm.setString(21, rs.getString("ZCMGST"));
                    pstm.setString(22, rs.getString("ABGRU"));
                    pstm.setBigDecimal(23, rs.getBigDecimal("ZZMENG"));
                    pstm.setBigDecimal(24, rs.getBigDecimal("ZZMENG2"));
                    pstm.setBigDecimal(25, rs.getBigDecimal("ZNETWR"));
                    pstm.setBigDecimal(26, rs.getBigDecimal("ZRFMNG"));
                    pstm.setBigDecimal(27, rs.getBigDecimal("ZRFMNG2"));
                    pstm.setBigDecimal(28, rs.getBigDecimal("ZNETWR1"));
                    pstm.setString(29, rs.getString("VSBED"));
                    pstm.setString(30, rs.getString("VSBED_TXT"));
                    pstm.addBatch();
                    if (i%10000==0){
                        pstm.executeBatch();
                    }
                } while (rs.next());
            } else {
                log.info("SalesOrder查询数据为空");
            }
            pstm.executeBatch();
            conn.commit();
            Long endTime = System.currentTimeMillis();
            log.info("SalesOrder插入用时：" + (endTime - startTime)+"毫秒");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            if(pstm1!=null){
                try {
                    pstm1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }*/

    //C类
    private int  createTmabcTxt(ResultSet result) throws Exception {
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;

            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"erpOrderByC/"));
            log.info("erpOrderByC数据缓存路径：" + Global.getTemdataPath()+"erpOrderByC/");
            if(!file.exists()){
                file.mkdir();
            }

            file = new File(Global.getTemdataPath()+"erpOrderByC/"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"erpOrderByC/").listFiles();
                //遍历该目录下的文件对象

                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){

                fw.write(
                        result.getString("MAABC")
                                +"$$"+ result.getString("SPRAS")
                                +"$$"+ result.getString("TMABC")
                                +"$$"+ result.getString("MANDT")
                                + "\r\n");

                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"erpOrderByC/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成erpOrderByC-TXT用时：" + (endTime - startTime) + "毫秒");


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }

//电子单签收

    private int createDeliverSignatureTxt(ResultSet result) throws Exception {
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;

            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"deliverSignature/"));
            log.info("deliverSignature数据缓存路径：" + Global.getTemdataPath()+"deliverSignature/");
            if(!file.exists()){
                file.mkdir();
            }

            file = new File(Global.getTemdataPath()+"deliverSignature/"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"deliverSignature/").listFiles();

                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){

                fw.write(
                        result.getString("VBELN")
                         +"$$"+ result.getString("POSNR")
                                +"$$"+ result.getString("MATNR")
                                +"$$"+ result.getString("VGBEL")
                                +"$$"+ result.getString("VGPOS")
                                +"$$"+ result.getString("ERDAT_SO")
                                +"$$"+ result.getString("LFIMG")
                                +"$$"+ result.getString("MODIFIEDVALUE")
                                +"$$"+ result.getString("LFIMG_CY")
                                +"$$"+ result.getString("ZDATE_KH")
                                +"$$"+ result.getString("ZTIME_KH")
                                +"$$"+ result.getString("ZVBELN_YCHH")
                                +"$$"+ result.getString("ZSTATUS_HH")
                                +"$$"+ result.getString("CONTRACTID")
                                +"$$"+ result.getString("BIZNO")
                                +"$$"+ result.getString("MANDT")
                                + "\r\n");


                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"deliverSignature/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成deliverSignature-TXT用时：" + (endTime - startTime) + "毫秒");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }

//订单
    private int createSalesOrderTxt(ResultSet result) throws Exception {
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;

            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"salesOrder/"));
            log.info("SalesOrder数据缓存路径：" + Global.getTemdataPath()+"salesOrder/");
            if(!file.exists()){
                file.mkdir();
            }

            file = new File(Global.getTemdataPath()+"salesOrder/"+j+".txt");
//            file = new File("C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\testIO"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"salesOrder/").listFiles();
                //遍历该目录下的文件对象
                /*for (int y = 0; y < files.length; y++) {
                    if (files[y].isFile()){//删除子文件
                        files[y].delete();
                    }
                }*/
                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){

                fw.write(
                        result.getString("VBELN")
                                +"$$"+ result.getString("POSNR")
                                +"$$"+ result.getString("VKORG")
                                +"$$"+ result.getString("VKORG_TXT")
                                +"$$"+ result.getString("VTWEG")
                                +"$$"+ result.getString("KUNNR")
                                +"$$"+ result.getString("NAME1")
                                +"$$"+ result.getString("ROUTE")
                                +"$$"+ result.getString("SPART")
                                +"$$"+ result.getString("VKGRP")
                                +"$$"+ result.getString("WERKS")
                                +"$$"+ result.getString("WERKS_NAME")
                                +"$$"+ result.getString("LGORT")
                                +"$$"+ result.getString("LGOBE")
                                +"$$"+ result.getString("AUART")
                                +"$$"+ result.getString("ERDAT")
                                +"$$"+ result.getString("ERDAT_P")
                                +"$$"+ result.getString("LFSTA")
                                +"$$"+ result.getString("MATNR")
                                +"$$"+ result.getString("ZMAKTXX")
                                +"$$"+ result.getString("PRODHA_TXT")
                                +"$$"+ result.getString("GROES")
                                +"$$"+ result.getString("TRAGR")
                                +"$$"+ result.getString("ZCMFRE")
                                +"$$"+ result.getString("ZCMGST")
                                +"$$"+ result.getString("ABGRU")
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZZMENG"))
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZZMENG2"))
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZNETWR"))
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZRFMNG"))
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZRFMNG2"))
                                +"$$"+ checkgetBigDecimal(result.getBigDecimal("ZNETWR1"))
                                +"$$"+ result.getString("VSBED")
                                +"$$"+ result.getString("VSBED_TXT")
                                +"$$"+ result.getString("ABRVW")
                                +"$$"+ result.getString("ABRVW_TXT")
                                +"$$"+ result.getString("VKBUR")
                                +"$$"+ result.getString("ZCODE1")
                                +"$$"+ result.getString("ZCODE1_DESC")
                                +"$$"+ result.getString("ZCODE4")
                                +"$$"+ result.getString("ZCODE4_DESC")
                                +"$$"+ result.getString("KVGR3")
                                +"$$"+ result.getString("KVGR4")
                                +"$$"+ result.getString("POSID")
                                +"$$"+ result.getString("PD_NO")
                                +"$$"+ result.getString("BSTKD")
                                +"$$"+ result.getString("NETPR")
                                +"$$"+ result.getString("NTGEW_MARA")
                                +"$$"+ result.getString("PSTYV")
                                +"$$"+ result.getString("UEPOS")
                                +"$$"+ result.getString("MAABC")
                                +"$$"+ result.getString("ZCODE8")
                                +"$$"+ result.getString("ZBEZEI1")
                                +"$$"+ result.getString("BSTKD_E")
                                + "\r\n");


                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"salesOrder/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成salesOrder-TXT用时：" + (endTime - startTime) + "毫秒");

            //conn = getMysqlConnection();
            //测试表
//            String sql = "TRUNCATE TABLE sap_hana_sales_order";
            //生产表
            /*String sql = "TRUNCATE TABLE meta_hana_sales_order";
            pstm = conn.prepareStatement(sql);
            pstm.execute();*/
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }
    public String getFreezeCustomer(String  customer) throws Exception {
        Connection con = getConnection(hanaDriver,hanaUrl,hanaUser,hanaPwd);
        String sql = "select a.KUNNR from (SELECT  s.KUNNR FROM ERP.KNVV s WHERE   (s.SPART = (case   when  SPART='14' then '14' when SPART='15' then '15'    when SPART='16' then '16' when SPART='19' then '19'  when SPART='29' then '29' else  '39' end )   and (s.LIFSD IS NULL or s.LIFSD = '')  and s.KUNNR = '" + customer + "' AND s.VTWEG = 'D9'and s.VKORG = 'S200' and s.KVGR3 not in ('D03')) or (s.KVGR3 = 'D03'  and (s.LIFSD IS NULL or s.LIFSD = '') and s.KUNNR = '" + customer + "' AND s.VTWEG = 'D9')order by s.SPART asc)a group by a.KUNNR";

        log.info("拼接的sql:{}", sql);
        PreparedStatement pstmt = con.prepareStatement(sql);
        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("NotFreezeCustomer查询用时：" + (endTime - startTime) + "毫秒");
        if (rs.next()) {
            log.info("1111--:{}", rs.getString("KUNNR"));
            int selectCus = userOrderAuthorService.selectCus(rs.getString("KUNNR"));
            if (selectCus == 0){
                int stu = userOrderAuthorService.insertCus(rs.getString("KUNNR"));
                if (stu > 0) {
                    log.info("插入成功");
                    return "经销商"+rs.getString("KUNNR")+"已解冻";
                } else {
                    log.info("插入失败");
                    return "经销商"+rs.getString("KUNNR")+"插入失败";
                }
            }else {
                return "经销商"+rs.getString("KUNNR")+"已解冻";
            }
        } else {
            log.info("查询结果为空");
            return "经销商"+customer+"未找到";
        }
    }

    /**HANA已冻结经销商**/
    public void hanaFreezeCustomer()throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement(" select a.KUNNR from (SELECT   s.KUNNR \n" +
                "                FROM ERP.KNVV s \n" +
                "                WHERE \n" +
                "                 (s.SPART = (case   when  SPART='14' then '14' \n" +
                "                                 when SPART='15' then '15'    when SPART='16' then '16'  \n" +
                "               when SPART='19' then '19' \n" +
                "               when SPART='29' then '29' \n" +
                "                                 else  '39' end )   and (s.LIFSD IS NULL or s.LIFSD = '')  AND s.VTWEG = 'D9'and s.VKORG = 'S200' and s.KVGR3 not in ('D03')) or (s.KVGR3 = 'D03'  and (s.LIFSD IS NULL or s.LIFSD = '') AND s.VTWEG = 'D9' )order by s.SPART asc)a \n" +
                "                 group by a.KUNNR  ");
        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("NotFreezeCustomer查询用时：" + (endTime - startTime)+"毫秒");
        this.createFreezeCustomerTxt(rs);
        this.runLoadFreezeCustomer();
        this.closeConnection(con, pstmt);
    }

    /**HANA已复核线下月底手动过账的交货单仍需自提同步*/
    public void hanaSelfReviewedDeliverOrderSync() throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT MANDT,VBELN,DATUM from ERP.ZSDT_POST_IN_ADV where DATUM >= TO_CHAR(add_months(CURRENT_DATE ,-3),'YYYYMMDD')and DATUM<= TO_CHAR(CURRENT_DATE,'YYYYMMDD') and ZDEL_IND !='X'");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("selfDeliverOrder查询用时：" + (endTime - startTime)+"毫秒");
        this.createSelfReviewedDeliverOrderTxt(rs);
        this.runLoadSelfReviewedDeliverOrder();
        this.closeConnection(con, pstmt);
    }

    public void hanaDeliverOrderSync() throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT\n" +
                "\tA.VBELN,\n" +
                "\tA.POSNR,\n" +
                "\tB.VGBEL,\n" +
                "\tB.VGPOS,\n" +
                "\tB.ROUTE,\n" +
                "\tB.VKORG,\n" +
                "\tB.VKORG_TXT,\n" +
                "\tB.VTWEG,\n" +
                "\tB.KUNAG,\n" +
                "\tB.KUNAG_TXT,\n" +
                "\tB.SPART,\n" +
                "\tB.VKGRP,\n" +
                "\tB.WERKS,\n" +
                "\tC.NAME1 WERKS_NAME,\n" +
                "\tB.AUART_S,\n" +
                "\tB.LFART,\n" +
                "\tB.MATNR,\n" +
                "\tB.ZMAKTXX,\n" +
                "\tB.GROES,\n" +
                "\tB.ZTKNUM,\n" +
                "\treplace(replace(B.ZSTREET,CHAR(10),''),CHAR(13),'') ZSTREET,\n" +
                "\tB.ERDAT_S,\n" +
                "\tB.ZERDAT2,\n" +
                "\tB.ERDAT,\n" +
                "\tB.WADAT_IST,\n" +
                "\tB. STATUS,\n" +
                "\tA.ZKWMENG,\n" +
                "\tA.NTGEW_VBAP,\n" +
                "\tA.LFIMG,\n" +
                "\tA.NTGEW,\n" +
                "\tA.KZWI4,\n" +
                "\tB.WADAT_IST,\n" +
                "\tB.BOLNR,\n" +
                "\tB.ERZET\n" +
                "FROM\n" +
                "\t(\n" +
                "\t\tSELECT\n" +
                "\t\t\tVBELN,\n" +
                "\t\t\tMIN(POSNR) AS POSNR,\n" +
                "\t\t\tSUM(ZKWMENG) AS ZKWMENG,\n" +
                "\t\t\tSUM(NTGEW_VBAP) AS NTGEW_VBAP,\n" +
                "\t\t\tSUM(LFIMG) AS LFIMG,\n" +
                "\t\t\tSUM(NTGEW) AS NTGEW,\n" +
                "\t\t\tSUM(KZWI4) AS KZWI4\n" +
                "\t\tFROM\n" +
                "\t\t\t\"_SYS_BIC\".\"com.delivery/CAL_DELIVERY\" ('PLACEHOLDER' = ('$$IP_ENDDATE$$',\n" +
                "\t\t\t\t\t'"+DateUtils.dateTime()+"'\n" +
                "\t\t\t\t),'PLACEHOLDER' = ('$$IP_STATDATE$$',\n" +
                "\t\t\t\t\t'"+DateUtils.getThreeMonthDate()+"'\n" +
                "\t\t\t\t)\n" +
                "\t\t\t)\n" +
                "\t\tWHERE\n" +
                "\t\t\tVTWEG IN ('D9','Y9','D8') \n" +
                "\t\tAND SPART != '16'\n" +
                "\t\tAND AUART_S NOT IN (\n" +
                "\t\t\t'31',\n" +
                "\t\t\t'32',\n" +
                "\t\t\t'33',\n" +
                "\t\t\t'35',\n" +
                "\t\t\t'36',\n" +
                "\t\t\t'39',\n" +
                "\t\t\t'29'\n" +
                "\t\t)\n" +
                "\t\tGROUP BY\n" +
                "\t\t\tVBELN,\n" +
                "\t\t\tVGBEL,\n" +
                "\t\t\tVGPOS\n" +
                "\t\tORDER BY\n" +
                "\t\t\tVBELN,\n" +
                "\t\t\tPOSNR\n" +
                "\t  ) A\n" +
                "LEFT JOIN \"_SYS_BIC\".\"com.delivery/CAL_DELIVERY\" ('PLACEHOLDER' = ('$$IP_ENDDATE$$',\n" +
                "\t\t'"+DateUtils.dateTime()+"'\n" +
                "\t),'PLACEHOLDER' = ('$$IP_STATDATE$$',\n" +
                "\t\t'"+DateUtils.getThreeMonthDate()+"'\n" +
                "\t)\n" +
                ") B ON A.VBELN = B.VBELN AND A.POSNR = B.POSNR\n"+
                " LEFT JOIN ERP.T001W C ON C.WERKS = B.WERKS \n"+
                "\t\tORDER BY\n" +
                "\t\t\tA.VBELN,\n" +
                "\t\t\tA.POSNR\n" +
                " ");
//                " limit 10000");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("DeliverOrder查询用时：" + (endTime - startTime)+"毫秒");
//        this.insertDeliverOrderResult(rs);
        this.createDeliverOrderTxt(rs);
        this.runLoadDeliverOrder();
        this.closeConnection(con, pstmt);

    }

    /*public void hanaDeliverOrderSync() throws Exception {
        Connection con = this.getHanaConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT\t\n" +
                "\tVBELN,\t\n" +
                "\tPOSNR,\t\n" +
                "\tVGBEL,\t\n" +
                "\tVGPOS,\t\n" +
                "\tVKORG,\t\n" +
                "\tVKORG_TXT,\t\n" +
                "\tVTWEG,\t\n" +
                "\tKUNAG,\t\n" +
                "\tKUNAG_TXT,\t\n" +
                "\tSPART,\t\n" +
                "\tVKGRP,\t\n" +
                "\tWERKS,\t\n" +
                "\tAUART_S,\t\n" +
                "\tLFART,\t\n" +
                "\tMATNR,\t\n" +
                "\tZMAKTXX,\t\n" +
                "\tGROES,\t\n" +
                "\tZSTREET,\t\n" +
                "\tERDAT_S,\t\n" +
                "\tZERDAT2,\t\n" +
                "\tERDAT,\t\n" +
                "\tWADAT_IST,\t\n" +
                "\tSTATUS,\t\n" +
                "\tZKWMENG,\t\n" +
                "\tNTGEW_VBAP,\t\n" +
                "\tLFIMG,\t\n" +
                "\tVRKME,\t\n" +
                "\tNTGEW,\t\n" +
                "\tKZWI4,\t\n" +
                "\tBOLNR\t\n" +
                "\tERZET\t\n" +
                "FROM \"_SYS_BIC\".\"com.delivery/CAL_DELIVERY\"('PLACEHOLDER' = ('$$IP_ENDDATE$$',\t\n" +
                "\t '"+DateUtils.dateTime()+"'),\n" +
                "\t 'PLACEHOLDER' = ('$$IP_STATDATE$$',\n" +
                "\t '"+DateUtils.getThreeMonthDate()+"')) \n" +
                "\t where VTWEG IN ('D9','Y9') AND VKORG != '4000'" +
                " ");

        Long startTime = System.currentTimeMillis();
        ResultSet rs = pstmt.executeQuery();
        Long endTime = System.currentTimeMillis();
        log.info("DeliverOrder查询用时：" + (endTime - startTime)+"毫秒");
//        this.insertDeliverOrderResult(rs);
        this.createDeliverOrderTxt(rs);
        this.runLoadDeliverOrder();
        this.closeConnection(con, pstmt);

    }*/


    private int createFreezeCustomerTxt(ResultSet result)throws Exception{
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;

            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"freezeCustomer/"));
            log.info("freezeCustomer数据缓存路径：" + Global.getTemdataPath()+"freezeCustomer/");
            if(!file.exists()){
                file.mkdir();
            }

            file = new File(Global.getTemdataPath()+"freezeCustomer/"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"freezeCustomer/").listFiles();
                //遍历该目录下的文件对象
                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){

                fw.write(
                        result.getString("KUNNR")
                        +"$$"+new DateTime()
                        +"\r\n");
                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"freezeCustomer/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成freezeCustomer-TXT用时：" + (endTime - startTime) + "毫秒");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }


    private int createSelfReviewedDeliverOrderTxt(ResultSet result)throws Exception{
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;

            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"selfDeliverOrder/"));
            log.info("selfDeliverOrder数据缓存路径：" + Global.getTemdataPath()+"selfDeliverOrder/");
            if(!file.exists()){
                file.mkdir();
            }

            file = new File(Global.getTemdataPath()+"selfDeliverOrder/"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"selfDeliverOrder/").listFiles();
                //遍历该目录下的文件对象
                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){

                fw.write(
                        result.getString("MANDT")
                                +"$$"+result.getString("VBELN")
                                +"$$"+result.getString("DATUM")
                                + "\r\n");
                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"selfDeliverOrder/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成selfDeliverOrder-TXT用时：" + (endTime - startTime) + "毫秒");

         /*   conn = getMysqlConnection();
            //生产表
            String sql = "TRUNCATE TABLE meta_hana_self_deliver_order";
            pstm = conn.prepareStatement(sql);
            pstm.execute();*/
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }

    private int createDeliverOrderTxt(ResultSet result) throws Exception {
        File file = null;
        FileWriter fw = null;
        Connection conn = null;
        PreparedStatement pstm =null;
        int j =0;
        try {
            long i =0;
            //创建IO需求的条件，并声明输出路径
            file = new File((Global.getTemdataPath()+"deliverOrder/"));
            log.info("deliverOrder数据缓存路径：" + Global.getTemdataPath()+"deliverOrder/");
            if(!file.exists()){
                file.mkdir();
            }
            file = new File(Global.getTemdataPath()+"deliverOrder/"+j+".txt");
//            file = new File("C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\testIO"+j+".txt");
            if(!file.exists()){
                file.createNewFile();
            }else {
                //取得这个目录下的所有子文件对象
                File[] files = new File(Global.getTemdataPath()+"deliverOrder/").listFiles();
                //遍历该目录下的文件对象
                for (File f: files){
                    f.delete();
                }
                file.delete();
                file.createNewFile();
            }
            fw = new FileWriter(file);
            Long startTime = System.currentTimeMillis();
            while (result.next()){
                log.info("测试数据1：{}",result.getString("ROUTE"));
                fw.write(
                        result.getString("VBELN")
                                +"$$"+result.getString("POSNR")
                                +"$$"+result.getString("VGBEL")
                                +"$$"+result.getString("VGPOS")
                                +"$$"+result.getString("ROUTE")
                                +"$$"+result.getString("VKORG")
                                +"$$"+result.getString("VKORG_TXT")
                                +"$$"+result.getString("VTWEG")
                                +"$$"+result.getString("KUNAG")
                                +"$$"+result.getString("KUNAG_TXT")
                                +"$$"+result.getString("SPART")
                                +"$$"+result.getString("VKGRP")
                                +"$$"+result.getString("WERKS")
                                +"$$"+result.getString("WERKS_NAME")
                                +"$$"+result.getString("AUART_S")
                                +"$$"+result.getString("LFART")
                                +"$$"+result.getString("MATNR")
                                +"$$"+result.getString("ZMAKTXX")
                                +"$$"+result.getString("GROES")
                                +"$$"+result.getString("ZTKNUM")
                                +"$$"+""
                                +"$$"+result.getString("ZSTREET")
                                +"$$"+result.getString("ERDAT_S")
                                +"$$"+result.getString("ZERDAT2")
                                +"$$"+result.getString("ERDAT")
                                +"$$"+result.getString("WADAT_IST")
                                +"$$"+""
                                +"$$"+""
                                +"$$"+""
                                +"$$"+result.getString("STATUS")
                                +"$$"+result.getBigDecimal("ZKWMENG")
                                +"$$"+result.getBigDecimal("NTGEW_VBAP")
                                +"$$"+result.getBigDecimal("LFIMG")
                                +"$$"+result.getBigDecimal("NTGEW")
                                +"$$"+result.getBigDecimal("KZWI4")
                                +"$$"+result.getString("WADAT_IST")
                                +"$$"+result.getString("BOLNR")
                                +"$$"+result.getString("ERZET")
                                + "\r\n");

                fw.flush();
                i++;
                if (i%50000==0){
                    j++;
                    //创建IO需求的条件，并声明输出路径
                    file = new File(Global.getTemdataPath()+"deliverOrder/"+j+".txt");
                    if(!file.exists()){
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    fw = new FileWriter(file);

                }
            }
            Long endTime = System.currentTimeMillis();
            log.info("生成deliverOrder-TXT用时：" + (endTime - startTime) + "毫秒");

        /*    conn = getMysqlConnection();
            //测试表
//            String sql = "TRUNCATE TABLE sap_hana_deliver_order";
            //生产表
            String sql = "TRUNCATE TABLE meta_hana_deliver_order";
            pstm = conn.prepareStatement(sql);
            pstm.execute();*/
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fw.close();
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return j;
    }

    /*批量插入*/
    /*private void insertDeliverOrderResult(ResultSet rs) throws Exception {
        Connection conn = null;
        PreparedStatement pstm =null;
        PreparedStatement pstm1 =null;
        try {
            conn = getMysqlConnection();
            String sql1 = "TRUNCATE TABLE sap_hana_deliver_order";
            String sql = "INSERT INTO sap_hana_deliver_order values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            pstm1 = conn.prepareStatement(sql1);
            pstm1.execute();
            pstm = conn.prepareStatement(sql);
            Long startTime = System.currentTimeMillis();
            conn.setAutoCommit(false);

            if (rs.next()) {
                long i =0;
                ResultSetMetaData rsmd = rs.getMetaData();
                int colNum = rsmd.getColumnCount();
                *//*循环遍历数据，创建执行批量插入的sql语句*//*
                do {
                    pstm.setString(1, rs.getString("VBELN"));
                    pstm.setString(2, rs.getString("POSNR"));
                    pstm.setString(3, rs.getString("VGBEL"));
                    pstm.setString(4, rs.getString("VGPOS"));
                    pstm.setString(5, rs.getString("VKORG"));
                    pstm.setString(6, rs.getString("VKORG_TXT"));
                    pstm.setString(7, rs.getString("VTWEG"));
                    pstm.setString(8, rs.getString("KUNAG"));
                    pstm.setString(9, rs.getString("KUNAG_TXT"));
                    pstm.setString(10, rs.getString("SPART"));
                    pstm.setString(11, rs.getString("VKGRP"));
                    pstm.setString(12, rs.getString("WERKS"));
                    pstm.setString(13, rs.getString("AUART_S"));
                    pstm.setString(14, rs.getString("LFART"));
                    pstm.setString(15, rs.getString("MATNR"));
                    pstm.setString(16, rs.getString("ZMAKTXX"));
                    pstm.setString(17, rs.getString("GROES"));
                    pstm.setString(18, "");
                    pstm.setString(19, "");
                    pstm.setString(20, rs.getString("ZSTREET"));
                    pstm.setString(21, rs.getString("ERDAT_S"));
                    pstm.setString(22, rs.getString("ZERDAT2"));
                    pstm.setString(23, rs.getString("ERDAT"));
                    pstm.setString(24, rs.getString("WADAT_IST"));
                    pstm.setString(25, "");
                    pstm.setString(26, "");
                    pstm.setString(27, "");
                    pstm.setString(28, rs.getString("STATUS"));
                    pstm.setBigDecimal(29, rs.getBigDecimal("ZKWMENG"));
                    pstm.setBigDecimal(30, rs.getBigDecimal("NTGEW_VBAP"));
                    pstm.setBigDecimal(31, rs.getBigDecimal("LFIMG"));
                    pstm.setBigDecimal(32, rs.getBigDecimal("NTGEW"));
                    pstm.setBigDecimal(33, rs.getBigDecimal("KZWI4"));
                    pstm.setString(34, "");
                    pstm.addBatch();
                    if (i%10000==0){
                        pstm.executeBatch();
                    }
                } while (rs.next());
            } else {
                log.info("DeliverOrder查询数据为空");
            }
            pstm.executeBatch();
            conn.commit();
            Long endTime = System.currentTimeMillis();
            log.info("DeliverOrder插入用时：" + (endTime - startTime)+"毫秒");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            if(pstm1!=null){
                try {
                    pstm1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }*/



    public int bulkLoadFromInputStream (String loadDataSql,
                                       InputStream dataStream) throws Exception {
        if(dataStream==null){
            log.info("InputStream is null ,No data is imported");
            return 0;
        }
        Connection conn = null;
        conn = this.getMysqlConnection();
        PreparedStatement statement = conn.prepareStatement(loadDataSql);

        int result = 0;

        if (statement.isWrapperFor(com.mysql.jdbc.Statement.class)) {

            com.mysql.jdbc.PreparedStatement mysqlStatement = statement
                    .unwrap(com.mysql.jdbc.PreparedStatement.class);

            mysqlStatement.setLocalInfileInputStream(dataStream);
            result = mysqlStatement.executeUpdate();
        }
        return result;
    }

    //订单C类标识
    private void runLoadTmabcTxt()throws Exception{
        //生产表
        Connection conn = null;
        PreparedStatement pstm =null;
        try{
            conn = getMysqlConnection();
            String sql = "TRUNCATE TABLE meta_hana_order_maabc";
            pstm = conn.prepareStatement(sql);
            pstm.execute();
            String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_order_maabc fields terminated by '$$' lines terminated by '\\n'";
            long beginTime=System.currentTimeMillis();
            int rows=this.bulkLoadFromInputStream(testSql, mergeGetStream(new File((Global.getTemdataPath()+"erpOrderByC/"))));
            long endTime=System.currentTimeMillis();
            log.info("importing erpOrderByC := "+rows+" rows data into mysql and cost "+(endTime-beginTime)+" ms!");

        }catch (Exception e){
            String name ="meta_hana_order_maabc订单C类标识表同步异常";
            userOrderAuthorService.sendMailHanaWarning(name);
            log.error(name, e);
            e.printStackTrace();
        }finally {
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }

    }



 //电子单签收状态
 public void runLoadDeliverSignature () throws Exception{
        //生产表
        Connection conn = null;
        PreparedStatement pstm =null;
        try{
            conn = getMysqlConnection();
            String sql = "TRUNCATE TABLE meta_hana_deliver_sign";
            pstm = conn.prepareStatement(sql);
            pstm.execute();
            String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_deliver_sign fields terminated by '$$' lines terminated by '\\n'";
            long beginTime=System.currentTimeMillis();
            int rows=this.bulkLoadFromInputStream(testSql, mergeGetStream(new File((Global.getTemdataPath()+"deliverSignature/"))));
            long endTime=System.currentTimeMillis();
            log.info("importing salesOrder := "+rows+" rows data into mysql and cost "+(endTime-beginTime)+" ms!");
        //预处理电子单签收数据
             metaHanaDeliverSignService.pretreatmentHanaDeliverSign();
        }catch (Exception e){
            String name ="meta_hana_deliver_sign电子单签收表同步异常";
            userOrderAuthorService.sendMailHanaWarning(name);
            log.error(name, e);
            e.printStackTrace();
        }finally {
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }

    }

//订单
    public void runLoadSalesOrder(){
            int maxRetries = 3; // 最大重试次数
            long retryInterval = 30000; // 重试间隔30秒
            int retryCount = 0;
            boolean renameSuccess = false;
            Exception lastException = null;

            Connection conn = null;
            Statement stmt = null;

            try {
                conn = getMysqlConnection();
                stmt = conn.createStatement();

                // 1. 创建临时表（无重试）
                stmt.execute("CREATE TABLE IF NOT EXISTS meta_hana_sales_order_temp LIKE meta_hana_sales_order");

                // 2. 加载数据到临时表（无重试）
                String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_sales_order_temp " +
                        "fields terminated by '$$' lines terminated by '\\n'";
                long beginTime = System.currentTimeMillis();
                String filePath = Global.getTemdataPath() + "salesOrder/";
                try (InputStream inputStream = mergeGetStream(new File(filePath))) {
                    int rows = this.bulkLoadFromInputStream(testSql, inputStream);
                    long endTime = System.currentTimeMillis();
                    log.info("导入数据到临时表: {} 行, 耗时: {} ms", rows, (endTime - beginTime));
                }

                // 3. 删除旧表（无重试）
                stmt.execute("DROP TABLE IF EXISTS meta_hana_sales_order_old");
                log.info("成功删除旧表: meta_hana_sales_order_old");

                // 4. RENAME操作（带重试机制）
                while (retryCount < maxRetries && !renameSuccess) {
                    try {
                        stmt.execute("RENAME TABLE meta_hana_sales_order TO meta_hana_sales_order_old, " +
                                "meta_hana_sales_order_temp TO meta_hana_sales_order");
                        renameSuccess = true;
                        log.info("表切换成功");
                    } catch (Exception e) {
                        lastException = e;
                        retryCount++;
                        if (retryCount < maxRetries) {
                            log.warn("第{}次表切换失败，将在{}ms后重试(剩余重试次数:{})",
                                    retryCount, retryInterval, maxRetries - retryCount);
                            try {
                                Thread.sleep(retryInterval);
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt();
                                throw new RuntimeException("重试被中断", ie);
                            }
                        }
                    }
                }

                // 5. 清空缓存（无重试）
                if (renameSuccess) {
                    String result = HttpUtils.sendGet(orderGetDataHook);
                    log.info("清空salesOrder缓存：{}", result);
                }

            } catch (Exception e) {
                lastException = e;
                log.error("处理过程中发生异常", e);
            } finally {
                // 资源清理
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                        log.error("关闭Statement失败", e);
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        log.error("关闭Connection失败", e);
                    }
                }
            }

            // 最终失败处理
            if (!renameSuccess) {
                String name = "meta_hana_sales_order订单表同步失败(重试3次后)";
                userOrderAuthorService.sendMailHanaWarning(name);
                log.error(name + ", 文件路径: " + Global.getTemdataPath() + "salesOrder/", lastException);
                throw new RuntimeException(name, lastException);
            }



    }




    public void runLoadFreezeCustomer()throws Exception{
        //生产表
        Connection conn = null;
        PreparedStatement pstm =null;
        try {
            conn = getMysqlConnection();
            //生产表
            String sql = "TRUNCATE TABLE meta_hana_not_freeze_customer";
            pstm = conn.prepareStatement(sql);
            pstm.execute();
            String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_not_freeze_customer fields terminated by '$$' lines terminated by '\\n'";
            long beginTime=System.currentTimeMillis();
            int rows=this.bulkLoadFromInputStream(testSql, mergeGetStream(new File((Global.getTemdataPath()+"freezeCustomer/"))));
            long endTime=System.currentTimeMillis();
            log.info("importing freezeCustomer := "+rows+" rows data into mysql and cost "+(endTime-beginTime)+" ms!");
        } catch (SQLException e) {
            String name ="meta_hana_not_freeze_customer 未冻结经销商表同步异常";
            userOrderAuthorService.sendMailHanaWarning(name);
            log.error(name, e);
            e.printStackTrace();
        }finally {
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }


    public void runLoadSelfReviewedDeliverOrder()throws Exception{
        int maxRetries = 3; // 最大重试次数
        long retryInterval = 30000; // 重试间隔30秒
        int retryCount = 0;
        boolean renameSuccess = false;
        Exception lastException = null;

        Connection conn = null;
        Statement stmt = null;

        try {
            conn = getMysqlConnection();
            stmt = conn.createStatement();

            // 1. 创建临时表（无重试）
            stmt.execute("CREATE TABLE IF NOT EXISTS meta_hana_self_deliver_order_temp LIKE meta_hana_self_deliver_order");

            // 2. 加载数据到临时表（无重试）
            String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_self_deliver_order_temp " +
                    "fields terminated by '$$' lines terminated by '\\n'";
            long beginTime = System.currentTimeMillis();
            String filePath = Global.getTemdataPath() + "selfDeliverOrder/";
            try (InputStream inputStream = mergeGetStream(new File(filePath))) {
                int rows = this.bulkLoadFromInputStream(testSql, inputStream);
                long endTime = System.currentTimeMillis();
                log.info("导入数据到临时表: {} 行, 耗时: {} ms", rows, (endTime - beginTime));
            }

            // 3. 删除旧表（无重试）
            stmt.execute("DROP TABLE IF EXISTS meta_hana_self_deliver_order_old");
            log.info("成功删除旧表: meta_hana_self_deliver_order_old");

            // 4. RENAME操作（带重试机制）
            while (retryCount < maxRetries && !renameSuccess) {
                try {
                    stmt.execute("RENAME TABLE meta_hana_self_deliver_order TO meta_hana_self_deliver_order_old, " +
                            "meta_hana_self_deliver_order_temp TO meta_hana_self_deliver_order");
                    renameSuccess = true;
                    log.info("表切换成功");
                } catch (Exception e) {
                    lastException = e;
                    retryCount++;
                    if (retryCount < maxRetries) {
                        log.warn("第{}次表切换失败，将在{}ms后重试(剩余重试次数:{})",
                                retryCount, retryInterval, maxRetries - retryCount);
                        try {
                            Thread.sleep(retryInterval);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("重试被中断", ie);
                        }
                    }
                }
            }


        } catch (Exception e) {
            lastException = e;
            log.error("处理过程中发生异常", e);
        } finally {
            // 资源清理
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    log.error("关闭Statement失败", e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("关闭Connection失败", e);
                }
            }
        }

        // 最终失败处理
        if (!renameSuccess) {
            String name = "meta_hana_self_deliver_order自提过账表同步失败(重试3次后)";
            userOrderAuthorService.sendMailHanaWarning(name);
            log.error(name + ", 文件路径: " + Global.getTemdataPath() + "selfDeliverOrder/", lastException);
            throw new RuntimeException(name, lastException);
        }







    }


    public void runLoadDeliverOrder() throws Exception{
        int maxRetries = 3; // 最大重试次数
        long retryInterval = 30000; // 重试间隔30秒
        int retryCount = 0;
        boolean renameSuccess = false;
        Exception lastException = null;

        Connection conn = null;
        Statement stmt = null;

        try {
            conn = getMysqlConnection();
            stmt = conn.createStatement();

            // 1. 创建临时表（无重试）
            stmt.execute("CREATE TABLE IF NOT EXISTS meta_hana_deliver_order_temp LIKE meta_hana_deliver_order");

            // 2. 加载数据到临时表（无重试）
            String testSql = "LOAD DATA LOCAL INFILE 'testIO.txt' into table meta_hana_deliver_order_temp " +
                    "fields terminated by '$$' lines terminated by '\\n'";
            long beginTime = System.currentTimeMillis();
            String filePath = Global.getTemdataPath() + "deliverOrder/";
            try (InputStream inputStream = mergeGetStream(new File(filePath))) {
                int rows = this.bulkLoadFromInputStream(testSql, inputStream);
                long endTime = System.currentTimeMillis();
                log.info("导入数据到临时表: {} 行, 耗时: {} ms", rows, (endTime - beginTime));
            }

            // 3. 删除旧表（无重试）
            stmt.execute("DROP TABLE IF EXISTS meta_hana_deliver_order_old");
            log.info("成功删除旧表: meta_hana_sales_order_old");

            // 4. RENAME操作（带重试机制）
            while (retryCount < maxRetries && !renameSuccess) {
                try {
                    stmt.execute("RENAME TABLE meta_hana_deliver_order TO meta_hana_deliver_order_old, " +
                            "meta_hana_deliver_order_temp TO meta_hana_deliver_order");
                    renameSuccess = true;
                    log.info("表切换成功");
                } catch (Exception e) {
                    lastException = e;
                    retryCount++;
                    if (retryCount < maxRetries) {
                        log.warn("第{}次表切换失败，将在{}ms后重试(剩余重试次数:{})",
                                retryCount, retryInterval, maxRetries - retryCount);
                        try {
                            Thread.sleep(retryInterval);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("重试被中断", ie);
                        }
                    }
                }
            }

            // 5. 清空缓存（无重试）
            if (renameSuccess) {
                String result = HttpUtils.sendGet(orderGetDataHook);
                log.info("清空deliverOrder缓存：{}", result);
            }

        } catch (Exception e) {
            lastException = e;
            log.error("处理过程中发生异常", e);
        } finally {
            // 资源清理
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    log.error("关闭Statement失败", e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("关闭Connection失败", e);
                }
            }
        }

        // 最终失败处理
        if (!renameSuccess) {
            String name = "meta_hana_deliver_order交货表同步失败(重试3次后)";
            userOrderAuthorService.sendMailHanaWarning(name);
            log.error(name + ", 文件路径: " + Global.getTemdataPath() + "deliverOrder/", lastException);
            throw new RuntimeException(name, lastException);
        }



    }

    public static InputStream mergeGetStream(File sourceFile) throws FileNotFoundException {
        String[] fileList = sourceFile.list();
        List<FileInputStream> fileInputStreams = new ArrayList<>();
        if (fileList != null) {
            for (String fileName : fileList) {
                File file = new File(sourceFile.getPath() + "/" + fileName);
                fileInputStreams.add(new FileInputStream(file));
            }
        }
        // 通过流工具类，获取一个枚举对象
        Enumeration<FileInputStream> en = Collections.enumeration(fileInputStreams);
        // 源
        SequenceInputStream sis = new SequenceInputStream(en);
        return sis;
    }

    private Connection getHanaConnection() throws Exception {
        return getConnection(hanaDriver,hanaUrl,hanaUser,hanaPwd);
    }
    private Connection getMysqlConnection() throws Exception {
        return getConnection(mysqlDriver,mysqlUrl,mysqlUser,mysqlPwd);
    }
    private Connection getConnection(String driver, String url, String user, String password) throws Exception {
        Class.forName(driver);

        return DriverManager.getConnection(url, user, password);

    }

    private BigDecimal checkgetBigDecimal(BigDecimal bg){
        if (bg==null){
            return new BigDecimal("0");
        }else{
            return bg;
        }
    }

    private void closeConnection(Connection con, Statement stmt)

            throws Exception {
        if (stmt != null) {
            stmt.close();

        }

        if (con != null) {
            con.close();

        }

    }
}
