/*
 * @Author: Kane
 * 
 * @Date: 2025-03-12 09:01:59
 * 
 * @LastEditors: Kane
 * 
 * @FilePath: /cpicxim-XMNHSA-repeater/src/main/java/com/cpic/xim/huixiabao/nhs/CpicximToXMNHS.java
 * 
 * @Description:
 * 
 * Copyright (c) ${2023} by Kane, All Rights Reserved.
 */

package com.cpic.xim.huixiabao.nhs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.Vector;
import com.cpic.xim.huixiabao.data.pojo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.hsa.zephyr.apisdk.DefaultZephyrClient;
import cn.hsa.zephyr.apisdk.internal.exception.ZephyrApiException;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.EncryptionModeEnum;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.SignTypeEnum;
import cn.hsa.zephyr.apisdk.request.DefaultZephyrRequest;
import cn.hsa.zephyr.apisdk.response.DefaultZephyrResponse;
import com.cpic.xim.huixiabao.data.config.HuixiabaoConfig;

@SuppressWarnings(
    "unused"
)
public class CpicximToXMNHS
{
    private static Logger logger = LoggerFactory.getLogger( CpicximToXMNHS.class );

    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String url        = "jdbc:mysql://10.39.0.85:3306/huixiabao?useUnicode=true&characterEncoding=utf8&useSSL=true";
    private static String userName   = "huixiabao";
    private static String password   = "Kane@1981";

    /**
     * 从HmbXyxInfo_Update中获取未发送过的小药箱数据。
     * 
     * @return
     */
    public static Vector<HmbXyxInfo> getNeverTransHmbList()
    {

        Vector<HmbXyxInfo> items = new Vector<HmbXyxInfo>();
        HmbXyxInfo         item  = null;

        Connection connection = null;
        Statement  statement  = null;
        ResultSet  result     = null;

        try
        {
            Class.forName( "com.mysql.cj.jdbc.Driver" );

            String url      = CpicximToXMNHS.url;
            String userName = CpicximToXMNHS.userName;
            String password = CpicximToXMNHS.password;
            // String sql      = """
            //         select info.psnName, info.certNo, info.serviceId, info.status, info.xyxNo
            //           from HmbXyxInfo info,
            //                HmbXyxInfo_Update u
            //          where info.xyxNo = u.xyxNo """;

            String sql = "select info.psnName, info.certNo, info.serviceId, info.status, info.xyxNo \n" +
                         "  from HmbXyxInfo info, \n" +
                         "       HmbXyxInfo_Update u \n" +
                         "  where info.xyxNo = u.xyxNo";

            connection = DriverManager.getConnection( url, userName, password );
            statement  = connection.createStatement();
            result     = statement.executeQuery( sql.trim() );

            while ( result.next() )
            {
                item = new HmbXyxInfo( result.getString( "psnName" ),
                                       result.getString( "certno" ),
                                       result.getString( "serviceId" ),
                                       result.getString( "status" ),
                                       result.getString( "xyxNo" ) );

                items.add( item );
            }
        }
        catch ( SQLException error )
        {
            error.printStackTrace();
        }
        catch ( ClassNotFoundException error )
        {
            logger.error( "加载sql驱动错误：" + error.getMessage() );
        }
        finally
        {
            if ( result != null )
            {
                try
                {
                    result.close();
                }
                catch ( SQLException error )
                {

                }
            }

            if ( statement != null )
            {
                try
                {
                    statement.close();
                }
                catch ( SQLException error )
                {

                }
            }

            if ( connection != null )
            {
                try
                {
                    connection.close();
                }
                catch ( SQLException error )
                {

                }
            }
        }

        return items;
    }

    /**
     * 将 postedItems 中的小药箱数据，冲HmbXyxInfo_update中清除。
     * 
     * @param postedItems 已发送的小药箱数据
     */
    public static void removePostedHmbXyxInfo( Vector<HmbXyxInfo> postedItems )
    {
        Vector<HmbXyxInfo> items = new Vector<HmbXyxInfo>();
        HmbXyxInfo         item  = null;

        Connection        connection = null;
        PreparedStatement statement  = null;
        ResultSet         result     = null;

        try
        {
            Class.forName( "com.mysql.cj.jdbc.Driver" );

            String url      = CpicximToXMNHS.url;
            String userName = CpicximToXMNHS.userName;
            String password = CpicximToXMNHS.password;
            String sql      = "delete from HmbXyxInfo_Update where  xyxNo = ?";

            connection = DriverManager.getConnection( url, userName, password );
            statement  = connection.prepareStatement( sql.trim() );

            for ( HmbXyxInfo info : postedItems )
            {
                statement.setString( 1, info.getXyxNo() );
                statement.execute();
            }
        }
        catch ( SQLException error )
        {
            try
            {
                connection.rollback();
            }
            catch ( SQLException e )
            {

            }

            logger.error( "清理已发送数据失败：" + error.getMessage() );
        }
        catch ( ClassNotFoundException error )
        {

        }
        finally
        {
            if ( result != null )
            {
                try
                {
                    result.close();
                }
                catch ( SQLException error )
                {

                }
            }

            if ( statement != null )
            {
                try
                {
                    statement.close();
                }
                catch ( SQLException error )
                {
                    logger.error( "加载sql驱动错误：" + error.getMessage() );
                }
            }

            if ( connection != null )
            {
                try
                {
                    connection.close();
                }
                catch ( SQLException error )
                {

                }
            }
        }
    }

    public static void postHmbXyxInfo( Vector<HmbXyxInfo> items )
    {
        String url       = HuixiabaoConfig.getUrl();
        String appId     = HuixiabaoConfig.getAppid();
        String appSecret = HuixiabaoConfig.getAppSecret();
        String funId     = HuixiabaoConfig.getFunId();
        String encKey    = HuixiabaoConfig.getEncKey();
        String signKey   = HuixiabaoConfig.getSignKey();

        SignTypeEnum       signType = SignTypeEnum.SM3;
        EncryptionModeEnum encType  = EncryptionModeEnum.SM4;

        // 发送用工具对象
        DefaultZephyrClient   client = new DefaultZephyrClient( url,
                                                                funId,
                                                                appId,
                                                                appSecret,
                                                                signType,
                                                                signKey,
                                                                encType,
                                                                encKey );
        DefaultZephyrRequest  req    = new DefaultZephyrRequest();
        DefaultZephyrResponse resp   = null;

        // 数据
        JSONObject         data = new JSONObject();
        JSONObject         requestObject = new JSONObject();
        JSONObject         xyxInfo       = null;
        JSONArray          xyxInfoList   = new JSONArray();
        Vector<HmbXyxInfo> postedInfo    = new Vector<HmbXyxInfo>(); // 存放已经送出的数据

        requestObject.put( "topic", "hmbXyxInfo" );

        int request_count = 0; // 计数，每个请求不能超过500条
        int total_count   = 0;

        for ( HmbXyxInfo info : items )
        {
            xyxInfo = new JSONObject();

            xyxInfo.put( "psnName", info.getPsnName() );
            xyxInfo.put( "certno", info.getCertNo() );
            xyxInfo.put( "serviceId", info.getServiceId() );
            xyxInfo.put( "status", info.getStatus() );
            xyxInfo.put( "xyxNo", info.getXyxNo() );

            xyxInfoList.add( xyxInfo );
            postedInfo.add( info );

            request_count++;
            total_count++;

            logger.info( "准备数据：" + xyxInfo.toJSONString() );

            if ( request_count >= HuixiabaoConfig.getMAX_COUNT_PER_REQUEST() - 1 || total_count == items.size() )
            {
                // 达到上限，或者记录已经全部处理，将当前生成的数据送出
                requestObject.remove( "hmbList" );
                requestObject.put( "hmbList", xyxInfoList );

                try
                {
                    data.remove("data");
                    data.put("data", requestObject);
                    logger.info( "发送请求内容:" + requestObject.toJSONString() );
                    logger.info( "请求地址：" + HuixiabaoConfig.getUrl() );

                    req.setData( requestObject );
                    resp = client.execute( req );

                    if ( resp != null )
                    {
                        logger.info( "发送成功，返回消息Body：" + resp.getBody() );
                        logger.info( "发送成功，返回消息data：" + resp.getData() );
                        logger.info( "发送成功，返回消息message：" + resp.getMessage() );

                        // 将已发送的数据从HmbXyxInfo_update表中清理掉
                        removePostedHmbXyxInfo( postedInfo );
                    }
                    else
                    {
                        logger.info( "已发送请求，但获取的DefaultZephyrResponse为null！" );
                    }
                }
                catch ( ZephyrApiException error )
                {
                    // 发送不成功，记录日志
                    // 不从HmbXyxInfo_update中清理当前这批数据，待以后重新发送
                    logger.error( "发送异常：" + error.getMessage() );
                }
                finally
                {
                    // 清理清单，重置计数
                    // 如果发送失败，在HmbXyxInfo_update表中保留发送失败的记录，待下次发送
                    xyxInfoList.clear();
                    postedInfo.clear();

                    request_count = 0;
                }
            }
        }
    }
}
