/****************************************************************************
** File name    :  HTIEC61850CSGFile.cpp
** Description  :  中国南方电网有限责任公司(CSG)-广东电网有限责任公司变电设备在线监测系统
**              ： 数据通信技术要求V1.5(2014-12).--谱图文件解析
** Create date  :  2019.09.01
** Auther by    :  Liuyx
** Version info :  V1.0.01
** Copyrigth By:  xi'an huatek, Inc Co., Ltd
** Update record:
** DATE         AUTHER   DESC
** -------------------------------------------------------------------------
** 2019.09.01   Liuyx    first build
****************************************************************************/
#include "HTGlobal.h"
#include "HTType.h"
static const char *_FILE_ = "HTIEC61850CSGFile.cpp";

// 判断float是否有效值
// return : true -- not use  flase: used.
bool isFloatValueUseFlag(float fval)
{
    float fvalue = 0;
    memset(&fvalue,0xFF,sizeof(float));
    return ((memcmp(&fval, &fvalue, sizeof(float))) == 0) ? true:false;
}

// 打开CSG规约的局放文件
static FILE *icsg_load_pd_file_open(char *pszFileName)
{
    char szFile[DEF_BUFFER_1K] = { 0 };
    if (pszFileName) {
#ifdef _WIN32
        sprintf(szFile, "%s\\%s", g_TConfig.getIecComtradeHomePath(), pszFileName);
#else
        sprintf(szFile, "%s/%s", g_TConfig.getIecComtradeHomePath(), pszFileName);
#endif
        FILE *fp = fopen(szFile, "r+b");
        if (!fp) {
            vPrtLogMsg(LOG_ERROR, errno, "Open csg pdfile %s failed! msg:%s", szFile, strerror(errno));
            return NULL;
        }
        return fp;
    }
    else vPrtLogMsg(LOG_ERROR, errno, "Open csg pdfile %s failed! msg:%s", szFile, strerror(errno));
    return NULL;
}

// 获取CSG规约的局放谱图文件头信息
static int icsg_get_pd_file_head(FILE *fp, ST_CSG_PDFILE_HEAD &stHeader)
{
    int counter = 0;
    int iLen = sizeof(ST_CSG_PDFILE_HEAD);
    counter = fread((void*)&stHeader, sizeof(char),iLen,fp);
    if (counter != iLen) {
        vPrtLogMsg(LOG_ERROR, errno, "read csg pdfile head size:%d error,real=%d,read_len=%d", iLen, counter);
        return RET_FAIL;
    }
#ifdef ENDIAN_CONIVER
    stHeader.fStandardVersion = n2hf(stHeader.fStandardVersion);
    stHeader.fFileVersion = n2hf(stHeader.fFileVersion);
    stHeader.shSpectrogramCode = ntohs(stHeader.shSpectrogramCode);
    stHeader.ilSpectrogramGenTime = ntohll(stHeader.ilSpectrogramGenTime);
    for (int i = 0; i < 7; i++) {
        stHeader.fProbability[i] = n2hf(stHeader.fProbability[i]);
    }
    stHeader.iFdPhaseNum_m = ntohi(stHeader.iFdPhaseNum_m);
    stHeader.iAmplitude_n = ntohi(stHeader.iAmplitude_n);
    stHeader.iFrequencyCycle_p = ntohi(stHeader.iFrequencyCycle_p);

    stHeader.f50Relevance = n2hf(stHeader.f50Relevance);
    stHeader.f100Relevance = n2hf(stHeader.f100Relevance);
    stHeader.fMinAmplitude = n2hf(stHeader.fMinAmplitude);
    stHeader.fMaxAmplitude = n2hf(stHeader.fMaxAmplitude);
#endif
    return counter;
}

//显示csg规约局放谱图文件头信息
//isFound : true  -- 检索到通道与设备的对应关系，sensorid
//          false -- 没有检索到通道与设备的对应关系
static void set_csg_print_pdfile_header(ST_FILE61850_LIST &stListFile, ST_CSG_PDFILE_HEAD &stHeader, 
    ST_DESIVE_REALTION &stRealtion, bool isFound)
{
    char szTmp[128] = { 0 };
    char szRowKey[256] = { 0 };
    char szProbability[DEF_BUFFER_256] = { 0 };
    char sz50Relevance[32] = { 0 }, sz100Relevance[32] = { 0 }, szMinAmplitude[32] = { 0 }, szMaxAmplitude[32] = { 0 };

    vPrtLogMsg(LOG_DEBUG, RET_OK, "-----------------CSG PD FILE HEAD-----------------------");
    vPrtLogMsg(LOG_DEBUG, RET_OK, "Path:%s", g_TConfig.getIecComtradeHomePath());
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%.4f, %.4f; %.02d, %llu",
        stHeader.fStandardVersion, stHeader.fFileVersion, stHeader.shSpectrogramCode, stHeader.ilSpectrogramGenTime);
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%c, %s; %c, %c; %c",
        stHeader.cTestFileFlag, stHeader.szChannleName, stHeader.cFdType, stHeader.cWarnLevel, stHeader.cProbabilityFlag);
    vPrtLogMsg(LOG_DEBUG, RET_OK, "m=%d, n=%d, p=%d ", stHeader.iFdPhaseNum_m, stHeader.iAmplitude_n, stHeader.iFrequencyCycle_p);
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%.4f, %.4f, type=%c ", stHeader.f50Relevance, stHeader.f100Relevance, stHeader.cSpectrogramType);
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%c, %.4f, %.4f ", stHeader.cAmplitudeUnit, stHeader.fMinAmplitude, stHeader.fMaxAmplitude);
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%.4s ", stHeader.szSeparation);

    int pos = 0;
    for (int i = 0; i < 7; i++){
        sprintf(szTmp, "%.4f,", stHeader.fProbability[i]);
        sprintf(szProbability + pos, szTmp);
        pos += strlen(szTmp);
    }
    szProbability[pos - 1] = 0x00;
    vPrtLogMsg(LOG_DEBUG, RET_OK, "%s ", szProbability);
    if (stHeader.cSpectrogramType == CSG_SPECTROGRAM_PRPD)  // 二维谱图
        vPrtLogMsg(LOG_DEBUG, RET_OK, "-->[%dx%d]  type=2D(PRPD)", stHeader.iFdPhaseNum_m, stHeader.iAmplitude_n);
    else if (stHeader.cSpectrogramType == CSG_SPECTROGRAM_PRPS)  // 三维谱图
        vPrtLogMsg(LOG_DEBUG, RET_OK, "-->[%dx%d]  type=3D(PRPS)", stHeader.iFrequencyCycle_p, stHeader.iFdPhaseNum_m);

    // 判断float的值是否有效,0xFFFFFFFF为无效值
    if (!isFloatValueUseFlag(stHeader.f50Relevance)) {
        sprintf(sz50Relevance, "%.4f", stHeader.f50Relevance);
    }
    if (!isFloatValueUseFlag(stHeader.f100Relevance)) {
        sprintf(sz100Relevance, "%.4f", stHeader.f100Relevance);
    }
    if (!isFloatValueUseFlag(stHeader.fMinAmplitude)) {
        sprintf(szMinAmplitude, "%.4f", stHeader.fMinAmplitude);
    }
    if (!isFloatValueUseFlag(stHeader.fMaxAmplitude)) {
        sprintf(szMaxAmplitude, "%.4f", stHeader.fMaxAmplitude);
    }
    ST_DB_INSERT_LIST stSql;
    stSql.pBuf = (char*)calloc(DEF_BUFFER_1K, sizeof(char));
    if (stSql.pBuf == NULL) {
        vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", DEF_BUFFER_1K);
        return;
    }
    if (isFound) {
        memset(szTmp, 0x00, sizeof(szTmp));
        sprintf(szTmp, "%llu", stHeader.ilSpectrogramGenTime);
        strSwap(szTmp, strlen(szTmp));   // 时间倒序
        sprintf(szRowKey, "%s_%s_%llu_%s_%s", szTmp, stRealtion.szSensorID, stHeader.ilSpectrogramGenTime,
            stRealtion.szCacTypeCode, stRealtion.szMainTreeID); 
    }
    vPrtLogMsg(LOG_DEBUG, RET_OK, "--> SensorID=[%s] eqm_id=[%s]", stRealtion.szSensorID, stRealtion.szMainTreeID);
    snprintf(stSql.pBuf, DEF_BUFFER_1K, "insert into iec_pd_file_header "
        "(id, pd_id,pd_file,d_time,state,iso_version,file_version,spectrogram_code,file_testflag,"
        "channel_name,fdType,warn_level,probability_flag,probability,phasemum_m,amplitude_n,"
        "cycle_p,relevance_fifty,relevance_hundred,dimension,amplitude_unit,min_amplitude,max_amplitude,hbase_rowkey) "
        "value('%s','%s','%s','%llu','%d','%.04f','%.4f','%.02d','%c','%s','%c','%c','%c','%s','%d','%d','%d',"
        "'%s','%s','%c','%c','%s','%s','%s')",
        stListFile.id, stRealtion.szPdID,stListFile.szFileName, stHeader.ilSpectrogramGenTime, 3,
        stHeader.fStandardVersion, stHeader.fFileVersion, stHeader.shSpectrogramCode, stHeader.cTestFileFlag,
        stHeader.szChannleName, stHeader.cFdType, stHeader.cWarnLevel, stHeader.cProbabilityFlag, szProbability,
        stHeader.iFdPhaseNum_m, stHeader.iAmplitude_n, stHeader.iFrequencyCycle_p, sz50Relevance,
        sz100Relevance, stHeader.cSpectrogramType, stHeader.cAmplitudeUnit, szMinAmplitude, szMaxAmplitude, szRowKey);
    //printf("=====> INSHEAD: %s\n", stSql.pBuf);
    stSql.iLen = strlen(stSql.pBuf);
    //stSql.cOpt = DB_OPT_UPDATE;
    stSql.cOpt = DB_OPT_INSERT;
    mutex_lock(g_list_dbsql_mutex);
    g_list_dbsql.push_front(stSql);
    mutex_unlock(g_list_dbsql_mutex);
}
static void csg_print_pdfile_header(FILE *fp, ST_CSG_PDFILE_HEAD &stHeader)
{
    if (stHeader.cSpectrogramType == CSG_SPECTROGRAM_PRPD)  // 二维谱图
        fprintf(fp, "-->[%dx%d]  type=2D(PRPD)\n", stHeader.iFdPhaseNum_m, stHeader.iAmplitude_n);
    else if (stHeader.cSpectrogramType == CSG_SPECTROGRAM_PRPS)  // 三维谱图
        fprintf(fp, "-->[%dx%d]  type=3D(PRPS)\n", stHeader.iFrequencyCycle_p, stHeader.iFdPhaseNum_m);

    fprintf(fp, "%.4f, %.4f, %.02d, %lld,",
        stHeader.fStandardVersion, stHeader.fFileVersion, stHeader.shSpectrogramCode, stHeader.ilSpectrogramGenTime);
    fprintf(fp, "%c, %s, %c, %c, %c,",
        stHeader.cTestFileFlag, stHeader.szChannleName, stHeader.cFdType, stHeader.cWarnLevel, stHeader.cProbabilityFlag);
    
    for (int i = 0; i < 7; i++)
        fprintf(fp, "%.4f,", stHeader.fProbability[i]);
    fprintf(fp, "%d, %d, %d, ", stHeader.iFdPhaseNum_m, stHeader.iAmplitude_n, stHeader.iFrequencyCycle_p);
    fprintf(fp, "%.4f, %.4f, %c, ", stHeader.f50Relevance, stHeader.f100Relevance, stHeader.cSpectrogramType);
    fprintf(fp, "%c, %.4f, %.4f, ", stHeader.cAmplitudeUnit, stHeader.fMinAmplitude, stHeader.fMaxAmplitude);
    fprintf(fp, "%.4s\n", stHeader.szSeparation);
}

// 主变sensorid查找
//pszBrandFlag == 文件名称前缀+通道串"0312B12000042A383000000_001_01_DCU1:CH 1"
static bool bMatchByqRealtion(char *pszBrandFlag, tint64 pllTime, ST_DESIVE_REALTION &stRealtion)
{
    char szSql[DEF_BUFFER_1K] = { 0 };
    bool ret = false;
    if (strlen(pszBrandFlag) <= 0) return false;

    CDBMySQL *pdbHandle = CDBMySQL::Instance();
    if (!pdbHandle) return false;
    
    // 主变表查找
    sprintf(szSql, "SELECT b.id,b.main_tree_id,b.cac_monitor_type_code,a1.sensor_code,"
        "min(abs(timestampdiff(SECOND, b.time_stamp, '%llu'))) as minval "
        "FROM busi_transformer_sensor as a1, transformer_pd b "
        "WHERE a1.sensor_brand = '%s' "
        "AND  a1.sensor_code = b.sensor_id ", pllTime, pszBrandFlag);
    MYSQL_RES *res = pdbHandle->SelectRecord(szSql);
    if (!res)  return false;

    MYSQL_ROW row = pdbHandle->GetRecord(res);
    if (NULL != *row )
    {
        if (row[0] && strlen(row[0]) > 0) {
            strncpy((char*)stRealtion.szPdID, (const char*)row[0], sizeof(stRealtion.szPdID));
        }
        if (row[1] && strlen(row[1]) > 0) {
            strncpy((char*)stRealtion.szMainTreeID, (const char*)row[1], sizeof(stRealtion.szMainTreeID));
        }
        if (row[2] && strlen(row[2]) > 0) {
            strncpy((char*)stRealtion.szCacTypeCode, (const char*)row[2], sizeof(stRealtion.szCacTypeCode));
        }
        if (row[3] && strlen(row[3]) > 0) {
            strncpy((char*)stRealtion.szSensorID, (const char*)row[3], sizeof(stRealtion.szSensorID));
        }
        ret = true;
    }
    pdbHandle->FreeRecord(res);
    return ret;
}
// 断路器sensorid查找
//pszBrandFlag == 文件名称前缀+通道串"0312B12000042A383000000_001_01_DCU1:CH 1"
static bool bMatchGisRealtion(char *pszBrandFlag, tint64 pllTime, ST_DESIVE_REALTION &stRealtion)
{
    char szSql[DEF_BUFFER_1K] = { 0 };
    bool ret = false;
    if (strlen(pszBrandFlag) <= 0) return false;
    CDBMySQL *pdbHandle = CDBMySQL::Instance();
    if (!pdbHandle) return false;

    // GIS_sensor表查找
    sprintf(szSql, "SELECT b.id,b.main_tree_id,b.cac_monitor_type_code,a1.sensor_code,"
        "min(abs(timestampdiff(SECOND, b.time_stamp, '%llu'))) as minval "
        "FROM busi_gis_sensor as a1, transformer_pd b "
        "WHERE a1.sensor_brand = '%s' "
        "AND  a1.sensor_code = b.sensor_id ", pllTime, pszBrandFlag);
    MYSQL_RES *res = pdbHandle->SelectRecord(szSql);
    if (!res)  return false;

    MYSQL_ROW row = pdbHandle->GetRecord(res);
    if (NULL != *row)
    {
        if (row[0] && strlen(row[0]) > 0) {
            strncpy((char*)stRealtion.szPdID, (const char*)row[0], sizeof(stRealtion.szPdID));
        }
        if (row[1] && strlen(row[1]) > 0) {
            strncpy((char*)stRealtion.szMainTreeID, (const char*)row[1], sizeof(stRealtion.szMainTreeID));
        }
        if (row[2] && strlen(row[2]) > 0) {
            strncpy((char*)stRealtion.szCacTypeCode, (const char*)row[2], sizeof(stRealtion.szCacTypeCode));
        }
        if (row[3] && strlen(row[3]) > 0) {
            strncpy((char*)stRealtion.szSensorID, (const char*)row[3], sizeof(stRealtion.szSensorID));
        }
        ret = true;
    }
    pdbHandle->FreeRecord(res);
    return ret;
}
// 其他sensorid查找
//pszBrandFlag == 文件名称前缀+通道串"0312B12000042A383000000_001_01_DCU1:CH 1"
static bool bMatchOtherRealtion(char *pszBrandFlag, tint64 pllTime, ST_DESIVE_REALTION &stRealtion)
{
    char szSql[DEF_BUFFER_1K] = { 0 };
    bool ret = false;

    if (strlen(pszBrandFlag) <= 0) return false;
    CDBMySQL *pdbHandle = CDBMySQL::Instance();
    if (!pdbHandle) return false;

    // GIS_sensor表查找
    sprintf(szSql, "SELECT b.id,b.main_tree_id,b.cac_monitor_type_code,a1.sensor_code,"
        "min(abs(timestampdiff(SECOND, b.time_stamp, '%llu'))) as minval "
        "FROM busi_other_sensor as a1, transformer_pd b "
        "WHERE a1.sensor_brand = '%s' "
        "AND  a1.sensor_code = b.sensor_id ", pllTime, pszBrandFlag);
    MYSQL_RES *res = pdbHandle->SelectRecord(szSql);
    if (!res)  return false;

    MYSQL_ROW row = pdbHandle->GetRecord(res);
    if (NULL != *row)
    {
        if (row[0] && strlen(row[0]) > 0) {
            strncpy((char*)stRealtion.szPdID, (const char*)row[0], sizeof(stRealtion.szPdID));
        }
        if (row[1] && strlen(row[1]) > 0) {
            strncpy((char*)stRealtion.szMainTreeID, (const char*)row[1], sizeof(stRealtion.szMainTreeID));
        }
        if (row[2] && strlen(row[2]) > 0) {
            strncpy((char*)stRealtion.szCacTypeCode, (const char*)row[2], sizeof(stRealtion.szCacTypeCode));
        }
        if (row[3] && strlen(row[3]) > 0) {
            strncpy((char*)stRealtion.szSensorID, (const char*)row[3], sizeof(stRealtion.szSensorID));
        }
        ret = true;
    }
    pdbHandle->FreeRecord(res);
    return ret;
}
// 根据解析出的通道号,产生时间查找trandformaer_pd表
static bool iSerachEquimentRelation(ST_FILE61850_LIST &stListFile,ST_CSG_PDFILE_HEAD &stFileHead, ST_DESIVE_REALTION &stRealtion)
{
    char szFactorCode[DEF_BUFFER_128] = { 0 };   //文件名称时间之前前缀 0312B12000042A383000000_001_01_20191207235310.dat
    
    if (iGetFileBeforString((char *)stListFile.szFileName, strlen((char*)stListFile.szFileName), szFactorCode) <= 0) {
        vPrtLogMsg(LOG_WARNG, RET_FAIL, "iGetFileBeforString int filename length(%d < 31):[%s]", 
            strlen((char*)stListFile.szFileName),stListFile.szFileName);
        return false;
    }
    //vPrtLogMsg(LOG_DEBUG, RET_OK, "file[%s], befor str:[%s]", (char*)stListFile.szFileName, szFactorCode);
    //strcat(szFactorCode, stFileHead.szChannleName);  // 文件名前缀_通道名称
    strcpy(szFactorCode, stFileHead.szChannleName);    //通道名称
    //RigthTrim((unsigned char*)szFactorCode);
    tint64 lltime = stFileHead.ilSpectrogramGenTime;

    if (bMatchByqRealtion(szFactorCode, lltime, stRealtion))   return true;
    if (bMatchGisRealtion(szFactorCode, lltime, stRealtion))   return true;
    if (bMatchOtherRealtion(szFactorCode, lltime, stRealtion))   return true;
    return false;
}

/********************************************************************
* function   : csgIEC61850PdFileParser
* param in   : parser files lists.
* param out  : None
* return val : None
* Description: csg iec 61850 局放文件解析
********************************************************************/
#ifdef CMTR_OUT_TXTFILE
void csgIEC61850PdFileParser(ST_FILE61850_LIST &stListFile)
{
    FILE *fd = NULL;
    ST_CSG_PDFILE_HEAD stFileHead;
    ST_DESIVE_REALTION stRealtion;
    char szGuuid[DEF_BUFFER_64 + 1] = { 0 };

    FILE *fp = NULL;    // 解析后的数据文件,临时存储,测试用
    char szTmpFile[DEF_BUFFER_256] = { 0 }; 
    char szTmpData[DEF_BUFFER_256] = { 0 };

    memset(&stFileHead, 0x00, sizeof(ST_CSG_PDFILE_HEAD));
    if ((fd = icsg_load_pd_file_open((char*)stListFile.szFileName)) == NULL)
    {
        vPrtLogMsg(LOG_ERROR, errno, "icsg_load_pd_file_open faild");
        return;
    }

    int iHeadLen = icsg_get_pd_file_head(fd, stFileHead);
    if (iHeadLen != sizeof(ST_CSG_PDFILE_HEAD))
    {
        vPrtLogMsg(LOG_WARNG, iHeadLen, "icsg_get_pd_file_head file head length != Standarg size.");
        fclose(fd);
        return;
    }
    memset(&stRealtion, 0x00, sizeof(ST_DESIVE_REALTION));
    bool ret = iSerachEquimentRelation(stListFile, stFileHead, stRealtion);  // 查找sensor_brand对应的设备sensor_id编码
    if(!ret){
        memset(&stRealtion, 0x00, sizeof(ST_DESIVE_REALTION));
    }
    set_csg_print_pdfile_header(stListFile,stFileHead,stRealtion, ret);

    int m = stFileHead.iFdPhaseNum_m;
    int n = stFileHead.iAmplitude_n;
    int p = stFileHead.iFrequencyCycle_p;
    int cnt = 0;
    int counter = 0;
    memset(szTmpFile, 0x00, sizeof(szTmpFile));
    sprintf(szTmpFile, "%s/%s", g_TConfig.getIecComtradeHomePath(), stListFile.szFileName);
    string strFile = szTmpFile;
    strFile = strFile.replace(strFile.end() - 3, strFile.end(), "txt");

    fp = fopen(strFile.c_str(),"w+");
    if (stFileHead.cSpectrogramType == CSG_SPECTROGRAM_PRPD)  // 二维谱图
    {
        int dat = 0;
        cnt = m*n;
        csg_print_pdfile_header(fp, stFileHead);
        for (int i = 0; i < m; i++)
        {
            ST_DB_INSERT_LIST stSql;
            stSql.pBuf = (char*)calloc(DEF_BUFFER_2K, sizeof(char));
            if (stSql.pBuf == NULL) {
                vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", DEF_BUFFER_2K);
                continue;
            }
            
            fprintf(fp, "-->[%d]", i + 1);
            memset(szGuuid, 0x00, sizeof(szGuuid));
            getuuid((char*)szGuuid, sizeof(szGuuid));
            snprintf(stSql.pBuf, DEF_BUFFER_2K, "insert into iec_pd_file_data(id,fhid,record_id,point,hbase_rowkey) value('%s','%s', '%d','",
                szGuuid,stListFile.id, i + 1);
            for (int r = 0; r < n; r++)
            {
                counter = fread(&dat, sizeof(char),sizeof(int),fd);
                if (counter == sizeof(int))
                {
                    sprintf(szTmpData, "%d,", dat);
                    strcat(stSql.pBuf, szTmpData);

                    if (((r) % 20) == 0x00)  fprintf(fp, "\n");
                    fprintf(fp, "%d ", dat);
                }
                else vPrtLogMsg(LOG_WARNG, counter, "icsg_get_pd_file_data File:[%s] counter=%d != %d.", szTmpFile, counter, sizeof(int));
            }
            fprintf(fp, "\n");

            stSql.pBuf[strlen(stSql.pBuf) -1 ] = 0x00;
            sprintf(szTmpData, "','%s')", szGuuid);
            strcat(stSql.pBuf, szTmpData);
            stSql.iLen = strlen(stSql.pBuf);
            stSql.cOpt = DB_OPT_INSERT;
            mutex_lock(g_list_dbsql_mutex);
            g_list_dbsql.push_front(stSql);
            mutex_unlock(g_list_dbsql_mutex);
        }
        vPrtLogMsg(LOG_DEBUG, RET_OK, "File:%s,2D,record_num=[%dx%d]...OK!", stListFile.szFileName, m,n);
    }
    else if (stFileHead.cSpectrogramType == CSG_SPECTROGRAM_PRPS)  // 三维谱图
    {
        float fm = 0.0f;
        cnt = p*m*4;
        csg_print_pdfile_header(fp, stFileHead);
        for (int i = 0; i < p; i++)
        {
            ST_DB_INSERT_LIST stSql;
            stSql.pBuf = (char*)calloc(DEF_BUFFER_2K, sizeof(char));
            if (stSql.pBuf == NULL) {
                vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", DEF_BUFFER_2K);
                continue;
            }

            fprintf(fp, "-->[%d]", i + 1);
            memset(szGuuid, 0x00, sizeof(szGuuid));
            getuuid((char*)szGuuid, sizeof(szGuuid));
            snprintf(stSql.pBuf, DEF_BUFFER_2K, "insert into iec_pd_file_data(id,fhid,record_id,point,hbase_rowkey) value('%s','%s', '%d','",
                szGuuid,stListFile.id, i + 1);
            for (int r = 0; r < m; r++)
            {
                counter = fread(&fm, 1, sizeof(float),fd);
                if (counter == sizeof(float))
                {
                    sprintf(szTmpData, "%.4f,", fm);
                    strcat(stSql.pBuf, szTmpData);

                    if (((r) % 20) == 0x00)  fprintf(fp, "\n");
                    fprintf(fp, "%.4f ", fm);
                }
                else vPrtLogMsg(LOG_WARNG, counter, "icsg_get_pd_file_data File:[%s] counter=%d != %d.", szTmpFile, counter, sizeof(float));
            }
            fprintf(fp, "\n");
           
            stSql.pBuf[strlen(stSql.pBuf) - 1] = 0x00;
            memset(szTmpData, 0x00, sizeof(szTmpData));
            sprintf(szTmpData, "','%s')", szGuuid);
            strcat(stSql.pBuf, szTmpData);
            stSql.iLen = strlen(stSql.pBuf);
            stSql.cOpt = DB_OPT_INSERT;
            mutex_lock(g_list_dbsql_mutex);
            g_list_dbsql.push_front(stSql);
            mutex_unlock(g_list_dbsql_mutex);
            //printf("SQL=(%d)%s\n", stSql.iLen,stSql.pBuf);
        }
        vPrtLogMsg(LOG_DEBUG, RET_OK, "File:%s,3D,record_num=[%dx%d]...OK!", stListFile.szFileName, p, m);
    }
    fclose(fd);
    fclose(fp);
    return;
}
#else
void csgIEC61850PdFileParser(ST_FILE61850_LIST &stListFile)
{
    FILE *fd = NULL;
    ST_CSG_PDFILE_HEAD stFileHead;
    ST_DESIVE_REALTION stRealtion;
    char szTmpData[DEF_BUFFER_256] = { 0 }, szGuuid[DEF_BUFFER_64 + 1] = { 0 };

    memset(&stFileHead, 0x00, sizeof(ST_CSG_PDFILE_HEAD));
    if ((fd = icsg_load_pd_file_open((char*)stListFile.szFileName)) == NULL)
    {
        vPrtLogMsg(LOG_ERROR, errno, "icsg_load_pd_file_open faild");
        return;
    }

    int iHeadLen = icsg_get_pd_file_head(fd, stFileHead);
    if (iHeadLen != sizeof(ST_CSG_PDFILE_HEAD))
    {
        vPrtLogMsg(LOG_WARNG, iHeadLen, "icsg_get_pd_file_head file head length != Standarg size.");
        fclose(fd);
        return;
    }
    memset(&stRealtion, 0x00, sizeof(ST_DESIVE_REALTION));
    bool ret = iSerachEquimentRelation(stListFile, stFileHead, stRealtion);
    if (!ret) {
        memset(&stRealtion, 0x00, sizeof(ST_DESIVE_REALTION));
    }
    set_csg_print_pdfile_header(stListFile, stFileHead, stRealtion,ret);

    int m = stFileHead.iFdPhaseNum_m;
    int n = stFileHead.iAmplitude_n;
    int p = stFileHead.iFrequencyCycle_p;
    int cnt = 0;
    int counter = 0;

    if (stFileHead.cSpectrogramType == CSG_SPECTROGRAM_PRPD)  // 二维谱图
    {
        int dat = 0;
        cnt = m*n;
        for (int i = 0; i < m; i++)
        {
            ST_DB_INSERT_LIST stSql;
            stSql.pBuf = (char*)calloc(DEF_BUFFER_2K, sizeof(char));
            if (stSql.pBuf == NULL) {
                vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", DEF_BUFFER_2K);
                continue;
            }
            memset(szGuuid, 0x00, sizeof(szGuuid));
            getuuid((char*)szGuuid, sizeof(szGuuid));
            snprintf(stSql.pBuf, DEF_BUFFER_2K, "insert into iec_pd_file_data(id,fhid,record_id,point,hbase_rowkey) value('%s','%s', '%d','",
                szGuuid,stListFile.id, i + 1);
            for (int r = 0; r < n; r++)
            {
                counter = fread(&dat, sizeof(char), sizeof(int), fd);
                if (counter == sizeof(int))
                {
                    sprintf(szTmpData, "%d,", dat);
                    strcat(stSql.pBuf, szTmpData);
                }
                else vPrtLogMsg(LOG_WARNG, counter, "icsg_get_pd_file_data File:[%s] counter=%d != %d.", stListFile.szFileName, counter, sizeof(int));
            }
            stSql.pBuf[strlen(stSql.pBuf) -1 ] = 0x00;
            memset(szTmpData, 0x00, sizeof(szTmpData));
            sprintf(szTmpData, "','%s')", szGuuid);
            strcat(stSql.pBuf, szTmpData);

            stSql.cOpt = DB_OPT_INSERT;
            stSql.iLen = strlen(stSql.pBuf);
            mutex_lock(g_list_dbsql_mutex);
            g_list_dbsql.push_front(stSql);
            mutex_unlock(g_list_dbsql_mutex);
        }
        vPrtLogMsg(LOG_DEBUG, RET_OK, "File:%s,2D,record_num=[%dx%d]...OK!", stListFile.szFileName, m,n);
    }
    else if (stFileHead.cSpectrogramType == CSG_SPECTROGRAM_PRPS)  // 三维谱图
    {
        float fm = 0.0f;
        cnt = p*m * 4;
        for (int i = 0; i < p; i++)
        {
            ST_DB_INSERT_LIST stSql;
            stSql.pBuf = (char*)calloc(DEF_BUFFER_2K, sizeof(char));
            if (stSql.pBuf == NULL) {
                vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", DEF_BUFFER_2K);
                continue;
            }
            memset(szGuuid, 0x00, sizeof(szGuuid));
            getuuid((char*)szGuuid, sizeof(szGuuid));
            snprintf(stSql.pBuf, DEF_BUFFER_2K, "insert into iec_pd_file_data(id,fhid,record_id,point,hbase_rowkey) value('%s','%s', '%d','",
                szGuuid,stListFile.id, i + 1);
            for (int r = 0; r < m; r++)
            {
                counter = fread(&fm, 1, sizeof(float), fd);
                if (counter == sizeof(float))
                {
                    sprintf(szTmpData, "%.4f,", fm);
                    strcat(stSql.pBuf, szTmpData);
                }
                else vPrtLogMsg(LOG_WARNG, counter, "icsg_get_pd_file_data File:[%s] counter=%d != %d.", stListFile.szFileName, counter, sizeof(float));
            }
            stSql.pBuf[strlen(stSql.pBuf) -1 ] = 0x00;
            memset(szTmpData, 0x00, sizeof(szTmpData));
            sprintf(szTmpData, "','%s')", szGuuid);
            strcat(stSql.pBuf, szTmpData);

            stSql.iLen = strlen(stSql.pBuf);
            stSql.cOpt = DB_OPT_INSERT;
            mutex_lock(g_list_dbsql_mutex);
            g_list_dbsql.push_front(stSql);
            mutex_unlock(g_list_dbsql_mutex);
            //printf("SQL=%s\n", stSql.pBuf);
        }
        vPrtLogMsg(LOG_DEBUG, RET_OK, "File:%s,3D,record_num=[%dx%d]...OK!", stListFile.szFileName, p, m);
    }
    fclose(fd);
    return;
}
#endif

//static char static_sql[DEF_BUFFER_1K*DEF_BUFFER_1K] = { 0 };
int  unGenComtrad( char *pfile)
{
    CDBMySQL *pdbHandle = CDBMySQL::Instance();
    if (!pdbHandle) return -1;
    char *static_sql = NULL;
    FILE *fd = NULL;
    int n = 0;
    ST_COMTRAD_DATA stAlmi;

    static_sql = (char*)calloc((DEF_BUFFER_1K*DEF_BUFFER_1K), sizeof(char));
    if (static_sql == NULL) {
        vPrtLogMsg(LOG_ERROR, errno, "calloc buffer size=%d failed.", (DEF_BUFFER_1K*DEF_BUFFER_1K));
        return -1;
    }
    fd = fopen(pfile, "r+b");
    if (!fd) {
        vPrtLogMsg(LOG_ERROR, errno, "Open csg pdfile %s failed! msg:%s", pfile, strerror(errno));
        return errno;
    }
    int counter = 0;
    sprintf(static_sql, "INSERT into busi_ampli_comtrad(id, comtrad_file, d_time,comtrad_data) "
        "VALUES(guuid(),'%s',now(),'", pfile);
    while (!feof(fd))
    {
        memset(&stAlmi, 0x00, sizeof(ST_COMTRAD_DATA));
        n++;
        counter = fread(&stAlmi, sizeof(char), sizeof(ST_COMTRAD_DATA), fd);
        if (counter == sizeof(ST_COMTRAD_DATA))
        {
            sprintf(static_sql+strlen(static_sql),
                "%d,%d,%d,%d,"
                "%d,%d,%d,%d,"
                "%d,%d,%d,%d,"
                "%d,%d|",
                //"%d, %d, %d, %d}",
                (stAlmi.sno), (stAlmi.tme), (stAlmi.A1), (stAlmi.A2),
                (stAlmi.B1), (stAlmi.B2), (stAlmi.C1), (stAlmi.C2),
                (stAlmi.a1), (stAlmi.a2), (stAlmi.b1), (stAlmi.b2),
                (stAlmi.c1), (stAlmi.c2)); // , (stAlmi.nsi), (stAlmi.crt));
        }
    }
    fclose(fd);
    static_sql[strlen(static_sql) - 1] = 0x00;
    strcat(static_sql, "')");
    pdbHandle->InsertRecord((const char*)static_sql);

    printf("str_len = %d\n", strlen(static_sql));
    if (static_sql)
        free(static_sql);
    static_sql = NULL;
    return n;
}
//void genComtradBySjzd()
//{
//
//}
