#include "communication_cmd.hpp"
#include <zlog.h>
#include "common/global.hpp"
#include "mqttclient/mqtt_client.h"
#include "dbaccess/sql_db.hpp"
#include "platform/platform_init.hpp"
#include "scheduler/schedule.hpp"
#include "utility/md5.h"

extern zlog_category_t *zct;
extern const char *JSON_FIELD_CMD;
extern const char *JSON_FIELD_NAME;
extern const char *JSON_FIELD_dataNodeGatewayNo;
extern const char *JSON_FIELD_ASSETID;
extern const char *JSON_FIELD_ADDEDBY;
extern const char *JSON_FIELD_DEVICETYPE;
extern const char *JSON_FIELD_ADDEDDATE;
extern const char *JSON_FIELD_IPADDRESS;
extern const char *JSON_FIELD_SN;
extern const char *JSON_FIELD_VERSION;
extern const char *JSON_FIELD_TIMEZONE;


std::string JsonData::JsonCmd_Cgi_01(Param_01 &param) {
    Json::Value jsonVal;
    Json::Value jsBody;
    jsonVal.clear();
    std::string userName = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "UserName");
    std::string adminPassword = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "adminPassword");
    std::string userPassword = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "userPassword");
    std::string message = " ";
    bool success = true;

    if (0 == param.mMode) {
        jsBody["type"] = "login";
        if (0 != param.mUserName.compare(userName)) {
            message = "0101";
            success = false;
        } else {
            if (0 == param.mPassWord.compare(adminPassword) || 0 == param.mPassWord.compare(userPassword)) {
            } else {
                message = "0102";
                success = false;
            }
        }
    } else if (1 == param.mMode) {
        jsBody["type"] = "upDate";
        if (0 != param.mUserName.compare(userName)) {
            message = "0101";
        } else {
            if (0 == param.mPassWord.compare(adminPassword) || 0 == param.mPassWord.compare(userPassword)) {
                WriteStr2Config(SYSTEMINFOFILE, "UserInfo", "userPassword", param.mPassWordNew);
            } else {
                message = "0103";
                success = false;
            }
        }
    } else {
        message = "格式错误";
        success = false;
    }

    jsonVal["cmd"] = "01";
    jsonVal["success"] = success;
    jsonVal["message"] = message;
    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_02(Param_02 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["success"] = true;
    jsonVal["message"] = "校时成功";

    jsonVal["cmd"] = "02";
    if (0 == param.mMode) {
        jsonVal["type"] = "SET";
        if (param.mSetType == 0) { //本地校时
            unsigned long set_timestamp = (unsigned long)param.mTimeStamp;
            char localtimestamp[32] = {0};
            GetTimeNet(localtimestamp, 1);
            std::string current_system_timestamp = std::string(localtimestamp);
            unsigned long current_timestamp = boost::lexical_cast<unsigned long>(current_system_timestamp);
            unsigned long diff_seconds = abs(current_timestamp - set_timestamp);
            if (diff_seconds > 5) {
                SetTime((unsigned long)param.mTimeStamp);
                mssleep(200);
                system("hwclock -w");
                scheduler::instance().ModifyScheduleTs(set_timestamp - current_timestamp);
            } else {
                zlog_warn(zct, "diff seconds:%ld lesser than 5, not to modify", diff_seconds);
            }
        } else if (param.mSetType == 1) { //与服务器校时
            char buf[256] = {0};
            sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", GlobalConfig::MacAddr_G.c_str());
            std::string str = std::string(buf);
            data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
        }
    }else if (1 == param.mMode) {
        char localtimestamp[32] = { 0 };
        GetTimeNet(localtimestamp, 1);	
        std::string nowTimetamp = std::string(localtimestamp);   
        jsonVal["type"] = "GET";     
        jsonVal["timeStamp"] = atoi(nowTimetamp.c_str());
    }
    jsonVal["timezone"] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone");
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_07() {
    Json::Value jsonVal;
    jsonVal.clear();
    Json::Value jsData;
    std::string sysStatus = GetSysStatus(jsData);

    zlog_info(zct, "sysStatus : %s", sysStatus.c_str());
    Json::Features f = Json::Features::strictMode();
    Json::Reader recvReader(f);
    Json::Value recvSys;
    jsonVal[JSON_FIELD_CMD] = "07";
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    if (recvReader.parse(sysStatus, recvSys)) {
        jsonVal["content"] = recvSys;
    } else {
        jsonVal["success"] = false;
        jsonVal["message"] = "状态获取失败";
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_08() {
    Json::Value jsonVal;
    jsonVal.clear();
    Json::Value jsData;
    std::string sysStatus = GetSysStatus(jsData);

    Json::Features f = Json::Features::strictMode();
    Json::Reader recvReader(f);
    Json::Value recvSys;
    jsonVal[JSON_FIELD_CMD] = "08";
    jsonVal["success"] = true;
    jsonVal["message"] = " ";

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_09(Param_09 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal[JSON_FIELD_CMD] = "09";
    jsonVal["success"] = true;
    jsonVal["message"] = " ";

    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    std::string nowTimetamp = std::string(localtimestamp);
    char looseValue[10] = {0x00};
    readStringValue("config", "loose", looseValue, (char *)GlobalConfig::Config_G.c_str());

    array_t arrResAll = sqlite_db_ctrl::instance().GetDataMultiLine(T_SENSOR_INFO(TNAME), " dataNodeNo,MeasurementID,zigbeeShortAddr ", NULL);
    int nSize = arrResAll.size();
    if (nSize > 0) {
        int packgeNo = param.mPackageFlag;
        int packgeMax = 0;
        int packgeNum = 0;
        jsonVal["package"] = packgeNo;
        int lastSize = nSize % 10;
        int index = nSize / 10;
        if (lastSize > 0 && index > 0) {
            packgeMax = index + 1;
            if (packgeNo + 1 == packgeMax) {
                packgeNum = nSize;
                jsonVal["packageMax"] = index + 1;
            } else {
                packgeNum = (packgeNo + 1) * 10;
                jsonVal["packageMax"] = index + 1;
            }
        } else if (lastSize == 0 && index > 0) {
            packgeNum = (packgeNo + 1) * 10;
            packgeMax = index;
            jsonVal["packageMax"] = index;
        } else if (lastSize > 0 && index == 0) {
            packgeNum = lastSize;
            packgeMax = index + 1;
            jsonVal["packageMax"] = index + 1;
        }

        zlog_info(zct, "09  packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d", packgeNo, packgeNum, lastSize, index);
        for (int i = packgeNo * 10; i < packgeNum; i++) {
            Json::Value jsSensor;
            std::string strMeasurementID = arrResAll[i][1];
            std::string strShortAddr = arrResAll[i][2];
            char whereCon[512] = {};
            sprintf(whereCon, "channelID like '%%%s%%' ORDER BY timeStamp DESC  LIMIT 0,3", strMeasurementID.c_str());
            // 自数据库获取传感器特征数据
            array_t arrRes;
            arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon);
            int iResult = arrRes.size();
            if (iResult > 0) {
                for (int j = 0; j < iResult; j++) {
                    Json::Value jsChannelData;
                    jsChannelData["ChannelId"] = arrRes[j][1];
                    jsChannelData["ShortAddr"] = strShortAddr;
                    jsChannelData["ChannelType"] = "ACCELEROMETER";
                    jsChannelData["DiagnosisPeak"] = atof(arrRes[j][2].c_str());
                    jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str());
                    jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str());
                    jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str());
                    jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str());
                    jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str());
                    jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str());
                    jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str());
                    jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str());
                    jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str());
                    jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str());
                    jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str());
                    jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str());
                    jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str());
                    jsChannelData["kurtosis"] = atof(arrRes[j][21].c_str());
                    jsChannelData["IntegratRMSMENS"] = atof(arrRes[j][22].c_str());
                    jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str());
                    jsSensor.append(jsChannelData);
                }
            }

            char selectCon[128] = {0};
            char column[128] = {0};
            char tablename[256] = {0};
            sprintf(selectCon, " t_sensor_info.MeasurementID='%s' ", strMeasurementID.c_str());
            sprintf(column, " %s.*,t_sensor_info.status,t_sensor_info.LooseValue,t_sensor_info.batteryPower ", T_DATASTATIC_INFO(TNAME));
            sprintf(tablename, " %s LEFT JOIN t_sensor_info \
					ON %s.channelID like '%%%s%%' ",
                    T_DATASTATIC_INFO(TNAME), T_DATASTATIC_INFO(TNAME), strMeasurementID.c_str());

            vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(tablename, column, selectCon);
            Json::Value jsStaticData;
            if (vecRes.size() > 0) {
                jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str());
                jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str());
                jsStaticData["Dip"] = atof(vecRes[4].c_str());
                jsStaticData["Voltage"] = atof(vecRes[5].c_str());
                jsStaticData["ChannelType"] = "STATUS";
                jsStaticData["ChannelId"] = vecRes[1];
                jsStaticData["TimeStamp"] = vecRes[8];
                jsStaticData["battery"] = vecRes[14];
                jsStaticData["MeasurementID"] = strMeasurementID;
                jsStaticData["dataNodeNo"] = arrResAll[i][0];
                jsStaticData["ShortAddr"] = strShortAddr;
                jsStaticData["status"] = vecRes[12];
                jsStaticData["loose"] = "0";

            } else {
                jsStaticData["TemperatureTop"] = "";
                jsStaticData["TemperatureBot"] = "";
                jsStaticData["Dip"] = "";
                jsStaticData["Voltage"] = "";
                jsStaticData["ChannelType"] = "STATUS";
                jsStaticData["ChannelId"] = "";
                jsStaticData["TimeStamp"] = "";
                jsStaticData["battery"] = "";
                jsStaticData["MeasurementID"] = strMeasurementID;
                jsStaticData["dataNodeNo"] = arrResAll[i][0];
                jsStaticData["status"] = "0";
                jsStaticData["loose"] = "0";
            }
            jsSensor.append(jsStaticData);
            jsonVal["content"].append(jsSensor);
        }

    } else {
        jsonVal["success"] = true;
        jsonVal["content"].resize(0);
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_10(Param_10 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal[JSON_FIELD_CMD] = "10";
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    vec_t vetRes = sqlite_db_ctrl::instance().GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(DATANODENO), NULL);
    int nSize = vetRes.size();
    if (nSize > 0) {
        char selectCon[256] = {0}, szTableName[100] = {0x00}, whereCon[256] = {0x00};

        sprintf(selectCon, "%s,channelID,timeStamp", param.strStatic.c_str());

        if (param.straxis == "S") {
            sprintf(szTableName, "t_dataStatic_%s", param.MeasurementID.c_str());
        } else {
            sprintf(szTableName, "t_data_%s", param.MeasurementID.c_str());
        }
        if (param.timeEnd == "") {
            sprintf(whereCon, "channelID  like '%%%s%%' and %s <> ''", param.MeasurementID.c_str(), param.strStatic.c_str());

        } else {
            sprintf(whereCon, " channelID  like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' and nodeResend = 0 ", param.MeasurementID.c_str(), param.strStatic.c_str(), param.timeEnd.c_str(), param.timeStart.c_str());
        }

        int rows = sqlite_db_ctrl::instance().GetTableRows(szTableName, whereCon);
        int packgeNo = param.mPackageFlag;
        int packgeMax = 0;
        int packgeNum = 0;
        jsonVal["package"] = packgeNo;
        int lastSize = rows % 550;
        int index = rows / 550;
        if (lastSize > 0 && index > 0) {
            packgeMax = index + 1;
            if (packgeNo + 1 == packgeMax) {
                packgeNum = rows - lastSize;
                jsonVal["packageMax"] = index + 1;
            } else {
                packgeNum = (packgeNo)*550;
                jsonVal["packageMax"] = index + 1;
            }
        } else if (lastSize == 0 && index > 0) {
            packgeNum = (packgeNo + 1) * 550;
            packgeMax = index;
            jsonVal["packageMax"] = index;
        } else if (lastSize > 0 && index == 0) {
            packgeNum = 0;
            packgeMax = index + 1;
            jsonVal["packageMax"] = index;
        }

        memset(whereCon, 0x00, sizeof(whereCon));

        if (param.timeEnd == "") {
            sprintf(whereCon, "channelID  like '%%%s%%' and %s <> ''  order by timeStamp asc LIMIT %d OFFSET %d", param.MeasurementID.c_str(), param.strStatic.c_str(), 550, packgeNum);
        } else {
            sprintf(whereCon, "channelID  like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' and nodeResend = 0 order by timeStamp asc LIMIT %d OFFSET %d", param.MeasurementID.c_str(), param.strStatic.c_str(), param.timeEnd.c_str(), param.timeStart.c_str(), 550, packgeNum);
        }
        array_t vecRes;

        vecRes = sqlite_db_ctrl::instance().GetDataMultiLine(szTableName, selectCon, whereCon);
        zlog_info(zct, "vecRes = %d", vecRes.size());
        if (vecRes.size() > 0) {
            Json::Value jsStaticData;
            for (size_t i = 0; i < vecRes.size(); i++) {
                Json::Value iTem;
                if (vecRes[i][1] == param.MeasurementID + "-X") {
                    iTem.append(vecRes[i][0]);
                    iTem.append(vecRes[i][2]);
                    jsStaticData["X"].append(iTem);
                }
                if (vecRes[i][1] == param.MeasurementID + "-Y") {
                    iTem.append(vecRes[i][0]);
                    iTem.append(vecRes[i][2]);
                    jsStaticData["Y"].append(iTem);
                }
                if (vecRes[i][1] == param.MeasurementID + "-Z") {
                    iTem.append(vecRes[i][0]);
                    iTem.append(vecRes[i][2]);
                    jsStaticData["Z"].append(iTem);
                }
                if (vecRes[i][1] == param.MeasurementID + "-S") {
                    iTem.append(vecRes[i][0]);
                    iTem.append(vecRes[i][2]);
                    jsStaticData["S"].append(iTem);
                }
            }
            if (jsStaticData.size() == 0) {
                jsonVal["success"] = false;
                jsonVal["content"].resize(0);
            } else {
                jsonVal["content"] = (jsStaticData);
            }
            jsonVal["Static"] = param.strStatic;
            zlog_info(zct, "vecRes = %d,channelID = %s", vecRes.size(), vecRes[0][0].c_str());
        } else {
            jsonVal["success"] = false;
            jsonVal["content"].resize(0);
        }
    } else {
        jsonVal["success"] = false;
        jsonVal["content"].resize(0);
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_20(Param_20 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    if (0 == param.mMode) {
        char localtimestamp[32] = {0};
        GetTimeNet(localtimestamp, 1);
        std::string nowTimetamp = std::string(localtimestamp);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName", param.mDataWatchName);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId", param.mDataWatchAssetId);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", param.mDataWatchAddedBy);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate", nowTimetamp);
    }

    std::string ip = IpAddrInit();
    jsonVal[JSON_FIELD_CMD] = "20";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsonVal["cmdSerial"] = param.mCmdSerial;

    Json::Value jsSystemInfo;
    Json::Value jsBody;

    jsSystemInfo[JSON_FIELD_NAME] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName");
    jsSystemInfo["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsSystemInfo[JSON_FIELD_ASSETID] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId");
    jsSystemInfo[JSON_FIELD_ADDEDBY] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy");
    jsSystemInfo[JSON_FIELD_ADDEDDATE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate");
    jsSystemInfo[JSON_FIELD_IPADDRESS] = ip;
    jsSystemInfo[JSON_FIELD_VERSION] = GlobalConfig::Version;
    jsSystemInfo[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone");
    jsSystemInfo["zigbeePanId"] = GlobalConfig::ZigbeeInfo_G.PanID;
    jsSystemInfo["zigbeeChannel"] = GlobalConfig::ZigbeeInfo_G.Channel;
    jsSystemInfo["zigbeeAddr"] = GlobalConfig::ZigbeeInfo_G.MyAddr;
    jsSystemInfo["GateWayVersion"] = GlobalConfig::Version;
    jsSystemInfo["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion");
    jsSystemInfo["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion");
    jsSystemInfo["GateWayHwVesion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion");
    jsSystemInfo["GateWayProduct"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct");
    jsSystemInfo["serverStatus"] = GlobalConfig::serverStatus;

    if (GlobalConfig::NetType == "\"NR5G-SA\"" || GlobalConfig::NetType == "\"NR5G-NSA\"" || GlobalConfig::NetType == "\"NR5G\"") {
        GlobalConfig::NetType = "5G";
    } else if (GlobalConfig::NetType == "\"LTE\"") {
        GlobalConfig::NetType = "4G";
    }
    if (GlobalConfig::NetStatus == "\"NOCONN\"" || GlobalConfig::NetStatus == "\"CONNECT\"") {
        if (GlobalConfig::NetSignal == 0) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",未知";
        } else if (GlobalConfig::NetSignal > -80) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",优";
        } else if (GlobalConfig::NetSignal > -90 && GlobalConfig::NetSignal < -80) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",良";
        } else if (GlobalConfig::NetSignal > -105 && GlobalConfig::NetSignal < -90) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",一般";
        } else if (GlobalConfig::NetSignal < -105) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",弱";
        } else if (GlobalConfig::NetSignal < -115) {
            jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",不稳定";
        }

    } else if (GlobalConfig::NetStatus == "\"SEARCH\"") {
        jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",搜索网络";
    } else if (GlobalConfig::NetStatus == "\"LIMSRV\"") {
        jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",未插卡";
    } else {
        jsSystemInfo["communicationSignal"] = "未知";
    }

    jsBody["SystemInfo"] = jsSystemInfo;

    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_22(Param_22 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    if (0 == param.mMode) {
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "timezone", param.mTimeZone);
    }

    jsonVal[JSON_FIELD_CMD] = "22";
    jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";

    Json::Value jsSystemSetting;
    Json::Value jsBody;
    jsSystemSetting[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone");
    jsBody["SystemSettings"] = jsSystemSetting;

    jsonVal["content"] = jsBody;

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_23(Param_23 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal[JSON_FIELD_CMD] = "23";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    // SET 指令，则param.mMode = 0,将设置的数据写入配置文件中 SERVERCONFIG "/opt/configenv/ServerConfig.json"

    if (0 == param.mMode && CheckIP(param.mServerIp.c_str())) {
        WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", param.mServerIp);
        WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", param.mPort);
        WriteStr2Config(SERVERCONFIG, "Server", "CommMode", /*param.mCommMode*/ "2");
        WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName);
        WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword);
        WriteStr2Config(SERVERCONFIG, "Server", "APN", param.mAPN);
        char APN[100] = {0x00};
        sprintf(APN, "sed -i '15c \t\t\t\t/opt/quectel-CM/quectel-CM -s %s > /dev/null &' /etc/init.d/S95check5G", param.mAPN.c_str());
        system(APN);
        system("reboot");
    } else if (0 == param.mMode && !(CheckIP(param.mServerIp.c_str()))) {
        jsonVal["success"] = false;
    }

    Json::Value jsSystemSetting;
    Json::Value jsBody;

    jsSystemSetting["ServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress");
    jsSystemSetting["ServerPort"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str());
    jsSystemSetting["CommMode"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str());
    jsSystemSetting["ServerStatus"] = 1;
    jsSystemSetting["UserName"] = ReadStrByOpt(SERVERCONFIG, "Server", "UserName");
    jsSystemSetting["Password"] = ReadStrByOpt(SERVERCONFIG, "Server", "Password");
    jsSystemSetting["APN"] = ReadStrByOpt(SERVERCONFIG, "Server", "APN");
    jsBody["SystemSettings"] = jsSystemSetting;
    jsonVal["content"] = jsBody;

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_25(Param_25 &param) {
    Json::Value jsonVal;
    Json::Value jsonValnet;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    jsonVal["cmd"] = "25";
    std::string strNet = "";
    bool bFlag1 = CheckIP(param.mGateway.c_str());
    bool bFlag2 = IsValidMask(param.mSubnetMask);
    bool bFlag3 = CheckIP(param.mIp.c_str());
    bool bFlag4 = false;
    if (param.mDnsName.size() > 0) {
        bFlag4 = CheckIP(param.mDnsName.c_str());
    } else {
        bFlag4 = true;
    }
    zlog_info(zct, "bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d", bFlag1, bFlag2, bFlag3, bFlag4);
    strNet = param.mNet;
    param.mNet = "Net";

    if (0 == param.mMode && (bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") {
        WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", param.mGateway);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", param.mSubnetMask);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", param.mIp);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", param.mHostName);

        char GateWay[100] = {0x00};
        sprintf(GateWay, "sed -i '7c route add default gw %s' /etc/init.d/S90start_userapp.sh", param.mGateway.c_str());
        zlog_info(zct, "GateWay = %s", GateWay);
        system(GateWay);
        PlatformInit::EquipIpInit(param.mNet);

    } else if (0 == param.mMode && param.mNetworkPortStatus == "DHCP") {
        WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", "");

        system("sed -i '7c udhcpc -i eth0  > /dev/null &' /etc/init.d/S90start_userapp.sh");
        PlatformInit::EquipIpInit(param.mNet);

    } else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") {
        jsonVal["success"] = false;
    }

    jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "dnsName");
    jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "networkPortStatus");
    jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "gateway");
    jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "subnetMask");
    jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "ipAddress");
    jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "hostName");
    jsonVal["content"]["eth0"] = jsonValnet;
    jsonVal["content"]["gatewaytype"] = 0;

#ifdef G2UL_GATEWAY
    jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "dnsName");
    jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "networkPortStatus");
    jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "gateway");
    jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "subnetMask");
    jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "ipAddress");
    jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "hostName");
    jsonVal["content"]["eth1"] = jsonValnet;
    jsonVal["content"]["gatewaytype"] = 1;
#endif
    return show_value_.write(jsonVal);
}
