package com.jpsoft.ehome.device;

import cn.hutool.core.io.IoUtil;
import com.sun.jna.Native;
import com.jpsoft.ehome.callback.*;
import com.jpsoft.ehome.common.EHomeResult;
import com.jpsoft.ehome.config.EHomeParamConfig;
import com.jpsoft.ehome.sdk.HCISUPAlarm;
import com.jpsoft.ehome.sdk.HCISUPCMS;
import com.jpsoft.ehome.sdk.HCISUPSS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.UUID;

@Slf4j
public class EHomeSDK {
    protected HCISUPSS hCEhomeSS;
    protected HCISUPAlarm mHCEHomeAlarm;
    protected HCISUPCMS hCEhomeCMS;

    //回调函数定义不能放在方法中,否则设备掉线后无法重连
    protected FRegisterCallBack fRegisterCallBack;
    protected LocalRWCallBack localRWCallBack;
    protected AlarmMsgCallBack cbEHomeMsgCallBack;

    public boolean isLinux(){
        return File.separator.equals("/");
    }

    public int startESSListen(EHomeParamConfig eHomeParamConfig) throws Exception{
        String strLibDir = eHomeParamConfig.getLibPath();
        String strLogDir = eHomeParamConfig.getLogPath();
        String localIP = eHomeParamConfig.getLocalIP();
        short pictureServerPort = eHomeParamConfig.getPictureServerTcpPort();

        if (isLinux()) {
            hCEhomeSS = Native.loadLibrary(strLibDir + "libHCISUPSS.so", HCISUPSS.class);
        }
        else{
            hCEhomeSS = Native.loadLibrary( strLibDir + "HCISUPSS.dll", HCISUPSS.class);
        }

        boolean bRet =  hCEhomeSS.NET_ESS_Init();

        if (!bRet){
            log.warn("存储模块初始化失败!");
            return -1;
        }

        //存储服务器(SS)报警监听--用来接收报警信息联动的事件图片
        boolean logToFile = hCEhomeSS.NET_ESS_SetLogToFile(3, strLogDir, false);

        //设置libcrypto.so或libeay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArrayCrypto = new HCISUPCMS.BYTE_ARRAY(256);

        String strPathCrypto = strLibDir; //Linux版本是libcrypto.so库文件的路径

        if (isLinux()) {
            strPathCrypto += "libcrypto.so";
        }
        else {
            strPathCrypto += "libeay32.dll";
        }

        System.arraycopy(strPathCrypto.getBytes(), 0, ptrByteArrayCrypto.byValue, 0, strPathCrypto.length());
        ptrByteArrayCrypto.write();
        hCEhomeSS.NET_ESS_SetSDKInitCfg(4, ptrByteArrayCrypto.getPointer());

        //设置libssl.so或ssleay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArraySsl = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathSsl = strLibDir;    //Linux版本是libssl.so库文件的路径

        if (isLinux()) {
            strPathSsl += "libssl.so";
        }
        else{
            strPathSsl += "ssleay32.dll";
        }

        System.arraycopy(strPathSsl.getBytes(), 0, ptrByteArraySsl.byValue, 0, strPathSsl.length());
        ptrByteArraySsl.write();
        hCEhomeSS.NET_ESS_SetSDKInitCfg(5, ptrByteArraySsl.getPointer());

        HCISUPCMS.NET_EHOME_IPADDRESS struIPaddr = new HCISUPCMS.NET_EHOME_IPADDRESS();
        String strOutSSIP = localIP;//服务器内网IP地址

        System.arraycopy(strOutSSIP.getBytes(), 0, struIPaddr.szIP, 0, strOutSSIP.length());
        struIPaddr.wPort = pictureServerPort;//服务器内网端口
        struIPaddr.write();
        hCEhomeSS.NET_ESS_SetSDKInitCfg(3, struIPaddr.getPointer());

        HCISUPSS.NET_EHOME_SS_LISTEN_PARAM pSSListenParam = new HCISUPSS.NET_EHOME_SS_LISTEN_PARAM();

        byte[] byIP = localIP.getBytes("UTF-8");

        System.arraycopy(byIP, 0, pSSListenParam.struAddress.szIP, 0, byIP.length);

        pSSListenParam.struAddress.wPort = pictureServerPort;

        String strKMS_UserName = "test";
        System.arraycopy(strKMS_UserName.getBytes(), 0, pSSListenParam.szKMS_UserName, 0, strKMS_UserName.length());

        String strKMS_Password = "12345";
        System.arraycopy(strKMS_Password.getBytes(), 0, pSSListenParam.szKMS_Password, 0, strKMS_Password.length());

        String strAccessKey = "test";
        System.arraycopy(strAccessKey.getBytes(), 0, pSSListenParam.szAccessKey, 0, strAccessKey.length());

        String strSecretKey = "12345";
        System.arraycopy(strSecretKey.getBytes(), 0, pSSListenParam.szSecretKey, 0, strSecretKey.length());

        if(localRWCallBack==null) {
            localRWCallBack = new LocalRWCallBack(eHomeParamConfig.getPicPath());
        }
//      StorageCallBack storageCallBack = new StorageCallBack();

        pSSListenParam.byHttps = 0;
        pSSListenParam.fnSSMsgCb = null; //pSS_Message_Callback;
        pSSListenParam.fnSStorageCb = null; //pSS_Storage_Callback;
        pSSListenParam.fnSSRWCb = localRWCallBack;
        pSSListenParam.fnSSRWCbEx = null; //fEHomeSSRWCallBackEx;
        pSSListenParam.bySecurityMode = 1;
        pSSListenParam.write();

        int listenSS  = hCEhomeSS.NET_ESS_StartListen(pSSListenParam);

        if (listenSS == -1) {
            int err = hCEhomeSS.NET_ESS_GetLastError();
            log.warn("NET_ESS_StartListen启动监听失败,错误号:" + err);
            return listenSS;
        } else {
            log.warn("NET_ESS_StartListen启动监听成功!");
            log.warn("启动存储服务器监听成功，监听端口：" + pSSListenParam.struAddress.wPort);
        }

        return listenSS;
    }

    public int startAlarmListen(EHomeParamConfig eHomeParamConfig, MsgNoticeCallBack msgNoticeCallBack) throws Exception{
        String strLibDir = eHomeParamConfig.getLibPath();
        String strLogDir = eHomeParamConfig.getLogPath();
        String localIP = eHomeParamConfig.getLocalIP();
        short alarmUdpPort= eHomeParamConfig.getAlarmUdpPort();

        if(isLinux()) {
            log.warn(strLibDir + "libHCISUPAlarm.so");
            mHCEHomeAlarm = Native.loadLibrary(strLibDir + "libHCISUPAlarm.so", HCISUPAlarm.class);
        }
        else {
            mHCEHomeAlarm = Native.loadLibrary(strLibDir + "HCISUPAlarm.dll", HCISUPAlarm.class);
        }

        log.warn("loadLibrary:" + mHCEHomeAlarm);

        //报警库初始化
        boolean bRet = mHCEHomeAlarm.NET_EALARM_Init();

        log.warn("NET_EALARM_Init:" + bRet);

        if (!bRet){
            log.warn("报警模块初始化失败!");
            return -1;
        }

        log.warn("NET_EALARM_SetLogToFile:" + strLogDir);

        mHCEHomeAlarm.NET_EALARM_SetLogToFile(3, strLogDir, false);

        //设置libcrypto.so或libeay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArrayCrypto = new HCISUPCMS.BYTE_ARRAY(256);

        String strPathCrypto = strLibDir; //Linux版本是libcrypto.so库文件的路径

        if (isLinux()) {
            strPathCrypto += "libcrypto.so";
        }
        else {
            strPathCrypto += "libeay32.dll";
        }

        System.arraycopy(strPathCrypto.getBytes(), 0, ptrByteArrayCrypto.byValue, 0, strPathCrypto.length());
        ptrByteArrayCrypto.write();
        mHCEHomeAlarm.NET_EALARM_SetSDKLocalCfg(0, ptrByteArrayCrypto.getPointer());

        //设置libssl.so或ssleay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArraySsl = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathSsl = strLibDir;    //Linux版本是libssl.so库文件的路径

        if (isLinux()) {
            strPathSsl += "libssl.so";
        }
        else{
            strPathSsl += "ssleay32.dll";
        }

        System.arraycopy(strPathSsl.getBytes(), 0, ptrByteArraySsl.byValue, 0, strPathSsl.length());
        ptrByteArraySsl.write();
        mHCEHomeAlarm.NET_EALARM_SetSDKInitCfg(1, ptrByteArraySsl.getPointer());

        //设置HCAapSDKCom组件库文件夹所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArrayCom = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathCom = strLibDir;

        System.arraycopy(strPathCom.getBytes(), 0, ptrByteArrayCom.byValue, 0, strPathCom.length());
        ptrByteArrayCom.write();
        mHCEHomeAlarm.NET_EALARM_SetSDKLocalCfg(5, ptrByteArrayCom.getPointer());

        log.warn("NET_EALARM_Init!");
        if (cbEHomeMsgCallBack==null){
            cbEHomeMsgCallBack = new AlarmMsgCallBack(msgNoticeCallBack);
        }

        HCISUPAlarm.NET_EHOME_ALARM_LISTEN_PARAM net_ehome_alarm_listen_param = new HCISUPAlarm.NET_EHOME_ALARM_LISTEN_PARAM();
        net_ehome_alarm_listen_param.struAddress.szIP = localIP.getBytes("UTF-8");
        net_ehome_alarm_listen_param.struAddress.wPort = alarmUdpPort;  //和注册回调函数下发给设备的端口需要一致
        net_ehome_alarm_listen_param.fnMsgCb = cbEHomeMsgCallBack;
        net_ehome_alarm_listen_param.pUserData= null;
        net_ehome_alarm_listen_param.byProtocolType = 1; //协议类型：0- TCP，1- UDP
        net_ehome_alarm_listen_param.byUseCmsPort = 0; //是否复用CMS端口：0- 不复用，非0- 复用
        //如果复用cms端口，协议类型字段无效，此时AMS的本地监听信息struAddress填本地回环地址，
        //本地回环地址通过NET_ECMS_GetSDKLocalCfg、NET_ECMS_SetSDKLocalCfg获取和设置）

        int ARMListen = mHCEHomeAlarm.NET_EALARM_StartListen(net_ehome_alarm_listen_param);

        if(ARMListen < 0)
        {
            log.warn("NET_EALARM_StartListen失败");
            return ARMListen;
        }
        else
        {
            log.warn("启动报警监听成功，监听端口：" + net_ehome_alarm_listen_param.struAddress.wPort);
        }

        log.warn("NET_EALARM_StartListen:"+ARMListen);

        return ARMListen;
    }

    public int startCMSListen(EHomeParamConfig eHomeParamConfig, DeviceRegisterCallBack deviceRegisterCallBack) throws Exception {
        String strLibDir = eHomeParamConfig.getLibPath();
        String strLogDir = eHomeParamConfig.getLogPath();
        String localIP = eHomeParamConfig.getLocalIP();
        String remoteIP= eHomeParamConfig.getRemoteIP();

        short cmsPort= eHomeParamConfig.getCmsUdpPort();
        short alarmUdpPort = eHomeParamConfig.getAlarmUdpPort();
        short alarmTcpPort = eHomeParamConfig.getAlarmTcpPort();
        short pictureServerPort = eHomeParamConfig.getPictureServerTcpPort();

        if(isLinux()) {
            hCEhomeCMS = Native.loadLibrary(strLibDir + "libHCISUPCMS.so", HCISUPCMS.class);
        }
        else {
            hCEhomeCMS = Native.loadLibrary(strLibDir + "HCISUPCMS.dll", HCISUPCMS.class);
        }

        //CMS注册模块初始化
        boolean bRet = hCEhomeCMS.NET_ECMS_Init();

        if (!bRet){
            log.warn("CMS注册模块初始化失败!");
            return -1;
        }

        //设置libcrypto.so或libeay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArrayCrypto = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathCrypto = strLibDir; //Linux版本是libcrypto.so库文件的路径

        if (isLinux()) {
            strPathCrypto += "libcrypto.so";
        }
        else {
            strPathCrypto += "libeay32.dll";
        }

        System.arraycopy(strPathCrypto.getBytes(), 0, ptrByteArrayCrypto.byValue, 0, strPathCrypto.length());
        ptrByteArrayCrypto.write();
        hCEhomeCMS.NET_ECMS_SetSDKLocalCfg(0, ptrByteArrayCrypto.getPointer());

        //设置libssl.so或ssleay32.dll所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArraySsl = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathSsl = strLibDir;    //Linux版本是libssl.so库文件的路径

        if (isLinux()) {
            strPathSsl += "libssl.so";
        }
        else{
            strPathSsl += "ssleay32.dll";
        }

        System.arraycopy(strPathSsl.getBytes(), 0, ptrByteArraySsl.byValue, 0, strPathSsl.length());
        ptrByteArraySsl.write();

        hCEhomeCMS.NET_ECMS_SetSDKInitCfg(1, ptrByteArraySsl.getPointer());

        //设置HCAapSDKCom组件库文件夹所在路径
        HCISUPCMS.BYTE_ARRAY ptrByteArrayCom = new HCISUPCMS.BYTE_ARRAY(256);
        String strPathCom = strLibDir;
        System.arraycopy(strPathCom.getBytes(), 0, ptrByteArrayCom.byValue, 0, strPathCom.length());
        ptrByteArrayCom.write();

        hCEhomeCMS.NET_ECMS_SetSDKLocalCfg(5, ptrByteArrayCom.getPointer());

        hCEhomeCMS.NET_ECMS_SetLogToFile(3, strLogDir, false);

        HCISUPCMS.NET_EHOME_CMS_LISTEN_PARAM struCMSListenPara = new HCISUPCMS.NET_EHOME_CMS_LISTEN_PARAM();

        struCMSListenPara.struAddress.szIP = localIP.getBytes("UTF-8");
        struCMSListenPara.struAddress.wPort = cmsPort;

        //回调函数定义不能放在方法中,否则设备掉线后无法重连，与内存回收机制有关
//      FRegisterCallBack fRegisterCallBack = new FRegisterCallBack(remoteIP, alarmUdpPort, alarmTcpPort, pictureServerTcpPort);

        if(fRegisterCallBack==null) {
            fRegisterCallBack = new FRegisterCallBack(remoteIP, alarmUdpPort, alarmTcpPort, pictureServerPort,deviceRegisterCallBack);
        }

        struCMSListenPara.fnCB = fRegisterCallBack;

        //启动监听，接收设备注册信息
        int lListen = hCEhomeCMS.NET_ECMS_StartListen(struCMSListenPara);

        if(lListen < -1)
        {
            hCEhomeCMS.NET_ECMS_Fini();
            return lListen;
        }

        log.warn("启动注册监听成功，监听端口："+ struCMSListenPara.struAddress.wPort);

        return lListen;
    }

    public boolean stopESSListen(int listenHandle){
        if(hCEhomeSS!=null){
            return hCEhomeSS.NET_ESS_StopListen(listenHandle);
        }
        else{
            return false;
        }
    }

    public boolean stopAlarmListen(int listenHandle){
        if(mHCEHomeAlarm!=null){
            return mHCEHomeAlarm.NET_EALARM_StopListen(listenHandle);
        }
        else{
            return false;
        }
    }

    public boolean stopCMSListen(int listenHandle){
        if(hCEhomeCMS!=null){
            return hCEhomeCMS.NET_ECMS_StopListen(listenHandle);
        }
        else{
            return false;
        }
    }

    public EHomeResult<String> ptXMLConfig(String method, int loginID, String url, String configXML, String inputXML) throws UnsupportedEncodingException {
        HCISUPCMS.NET_EHOME_PTXML_PARAM struISAPXML = new HCISUPCMS.NET_EHOME_PTXML_PARAM();

        struISAPXML.dwRecvTimeOut = 10000;

        HCISUPCMS.BYTE_ARRAY stringRequest = new HCISUPCMS.BYTE_ARRAY(2*1024);
        stringRequest.read();
        String strRequest = url;         //请求URL
        stringRequest.byValue = strRequest.getBytes("UTF-8");
        stringRequest.write();

        struISAPXML.pRequestUrl = stringRequest.getPointer();
        struISAPXML.dwRequestUrlLen = stringRequest.byValue.length;
        struISAPXML.write();

        //条件参数
        if (StringUtils.isNotEmpty(configXML)) {
            HCISUPCMS.BYTE_ARRAY struConfigXML = new HCISUPCMS.BYTE_ARRAY(2 * 1024);
            struConfigXML.read();
            struConfigXML.byValue = configXML.getBytes("UTF-8");
            struConfigXML.write();

            struISAPXML.pCondBuffer = struConfigXML.getPointer();
            struISAPXML.dwCondSize = struConfigXML.size();
            struISAPXML.write();
        }

        //输入参数
        if (StringUtils.isNotEmpty(inputXML)) {
            HCISUPCMS.BYTE_ARRAY struInputXML = new HCISUPCMS.BYTE_ARRAY(2 * 1024);
            struInputXML.read();
            struInputXML.byValue = inputXML.getBytes("UTF-8");
            struInputXML.write();

            struISAPXML.pInBuffer = struInputXML.getPointer();
            struISAPXML.dwInSize = struInputXML.byValue.length;
            struISAPXML.write();
        }

        HCISUPCMS.BYTE_ARRAY stringXMLOut = new HCISUPCMS.BYTE_ARRAY(8*1024);
        struISAPXML.pOutBuffer = stringXMLOut.getPointer();
        struISAPXML.dwOutSize = stringXMLOut.size();

        EHomeResult<String> EHomeResult = new EHomeResult<String>();

        boolean result = false;

        if ("GET".equals(method)){
            log.warn("NET_ECMS_GetPTXMLConfig");
            result = hCEhomeCMS.NET_ECMS_GetPTXMLConfig(loginID,struISAPXML);
        }
        else if ("POST".equals(method)){
            log.warn("NET_ECMS_PostPTXMLConfig");
            result = hCEhomeCMS.NET_ECMS_PostPTXMLConfig(loginID,struISAPXML);
        }
        else if ("PUT".equals(method)){
            log.warn("NET_ECMS_PutPTXMLConfig");
            result = hCEhomeCMS.NET_ECMS_PutPTXMLConfig(loginID,struISAPXML);
        }
        else{
            log.warn("不支持的method:" + method);
        }

        if(result){
            stringXMLOut.read();
            String strOutXML = new String(stringXMLOut.byValue).trim();

            EHomeResult.setSuccess(true);
            EHomeResult.setData(strOutXML);
        }
        else{
            int iErr = hCEhomeCMS.NET_ECMS_GetLastError();

            EHomeResult.setSuccess(false);
            EHomeResult.setCode(iErr);
            EHomeResult.setMessage("NET_ECMS_" + method + "_PTXMLConfig 失败，错误号：" + iErr);
        }

        return EHomeResult;
    }

    public EHomeResult<String> deviceXMLConfig(int loginID, String cmd, String inputXML) throws UnsupportedEncodingException {
        HCISUPCMS.NET_EHOME_XML_CFG struXMLCfg = new HCISUPCMS.NET_EHOME_XML_CFG();
        HCISUPCMS.NET_EHOME_XML_REMOTE_CTRL_PARAM struRemoteCtrl = new HCISUPCMS.NET_EHOME_XML_REMOTE_CTRL_PARAM();
        HCISUPCMS.NET_DVR_STRING_POINTER stringRequestCard = new HCISUPCMS.NET_DVR_STRING_POINTER();
        stringRequestCard.read();

        stringRequestCard.byString =cmd.getBytes("UTF-8");
        stringRequestCard.write();

        struXMLCfg.pCmdBuf = stringRequestCard.getPointer();
        struXMLCfg.dwCmdLen = stringRequestCard.byString.length;
        struXMLCfg.write();

        HCISUPCMS.NET_DVR_STRING_POINTER struConfigXMLInput = new HCISUPCMS.NET_DVR_STRING_POINTER();
        struConfigXMLInput.read();
        struConfigXMLInput.byString = inputXML.getBytes("UTF-8");
        struConfigXMLInput.write();

        log.warn("InPut:"+ inputXML);

        struXMLCfg.pInBuf = struConfigXMLInput.getPointer();
        struXMLCfg.dwInSize = struConfigXMLInput.byString.length;
        struXMLCfg.dwRecvTimeOut = 5000;
        struXMLCfg.dwSendTimeOut = 5000;
        struXMLCfg.write();

        HCISUPCMS.NET_DVR_STRING_POINTER struConfigXMLOutput = new HCISUPCMS.NET_DVR_STRING_POINTER();
        struConfigXMLOutput.write();
        struXMLCfg.pOutBuf = struConfigXMLOutput.getPointer();
        struXMLCfg.dwOutSize = struConfigXMLOutput.size();
        struXMLCfg.write();

        HCISUPCMS.NET_DVR_STRING_POINTER stringXMLStatus = new HCISUPCMS.NET_DVR_STRING_POINTER();
        stringXMLStatus.write();
        struXMLCfg.pStatusBuf = stringXMLStatus.getPointer();
        struXMLCfg.dwStatusSize = stringXMLStatus.size();
        struXMLCfg.write();

        EHomeResult<String> EHomeResult = new EHomeResult<>();

        if(!hCEhomeCMS.NET_ECMS_XMLConfig(loginID, struXMLCfg, struXMLCfg.size()))
        {
            int iErr = hCEhomeCMS.NET_ECMS_GetLastError();

            EHomeResult.setSuccess(false);
            EHomeResult.setCode(iErr);
            EHomeResult.setMessage("NET_ECMS_XMLConfig失败，错误号：" + iErr);
        }
        else
        {
            struXMLCfg.read();
            struConfigXMLOutput.read();

            String outXML = (new String(struConfigXMLOutput.byString,0,struXMLCfg.dwOutSize));  //输出XML

            EHomeResult.setSuccess(true);
            EHomeResult.setData(outXML.trim());
        }

        return EHomeResult;
    }

    public void logout(int loginID) {
        hCEhomeCMS.NET_ECMS_ForceLogout(loginID);
    }

    public EHomeResult<String> clientUpload(String remoteIP, short port, String filePath, String urlPrefix){
        EHomeResult<String> EHomeResult = new EHomeResult<>();

        HCISUPSS.NET_EHOME_SS_CLIENT_PARAM pClientParam = new HCISUPSS.NET_EHOME_SS_CLIENT_PARAM();
        pClientParam.enumType = HCISUPSS.NET_EHOME_SS_CLIENT_TYPE_KMS;
        pClientParam.struAddress.szIP = remoteIP.getBytes();
        pClientParam.struAddress.wPort = port;
        pClientParam.byHttps = 0;

        int lPssClientHandle = hCEhomeSS.NET_ESS_CreateClient(pClientParam);
        hCEhomeSS.NET_ESS_ClientSetTimeout(lPssClientHandle,60 * 1000, 60 * 1000);

        hCEhomeSS.NET_ESS_ClientSetParam(lPssClientHandle, "File-Path", filePath);
        hCEhomeSS.NET_ESS_ClientSetParam(lPssClientHandle, "KMS-Username", "test");
        hCEhomeSS.NET_ESS_ClientSetParam(lPssClientHandle, "KMS-Password", "12345");

        byte[] szUrl = null;
        szUrl = new byte[HCISUPSS.MAX_URL_LEN_SS];

        boolean doUpload = hCEhomeSS.NET_ESS_ClientDoUpload(lPssClientHandle, szUrl, HCISUPSS.MAX_URL_LEN_SS -1);

        EHomeResult.setSuccess(doUpload);

        if (!doUpload) {
            int err = hCEhomeSS.NET_ESS_GetLastError();
            EHomeResult.setCode(err);
            EHomeResult.setMessage("NET_ESS_ClientDoUpload失败，错误号：" + err);
        }
        else
        {
            String url = urlPrefix + new String(szUrl).trim();
            EHomeResult.setData(url);
            EHomeResult.setSuccess(true);
            log.warn("NET_ESS_ClientDoUpload成功！返回的图片url为:" + url);
        }

        return EHomeResult;
    }

    public EHomeResult<String> clientUpload(String remoteIP, short port, InputStream inputStream, String urlPrefix) throws FileNotFoundException {
        File curDir = new File(".");
        String dirPath = curDir.getAbsolutePath();
        dirPath = dirPath.substring(0, dirPath.length() - 1);

        String tempPath = dirPath + "temp";

        File tempDir = new File(tempPath);

        if (!tempDir.exists()) {
            tempDir.mkdir();
        }

        String newFileName = UUID.randomUUID().toString() + ".jpg";
        String filePath = tempPath + File.separator + newFileName;

        FileOutputStream output = new FileOutputStream(filePath);

        IoUtil.copy(inputStream, output);
        IoUtil.close(output);

        EHomeResult<String> EHomeResult = clientUpload(remoteIP,port,filePath,urlPrefix);

        //上传后，删除临时文件
        File tmpFile = new File(filePath);

        if (tmpFile.exists()){
            tmpFile.delete();
        }

        return EHomeResult;
    }

    public EHomeResult<String> remoteControl(int loginID, String inputXML) throws UnsupportedEncodingException {
        EHomeResult<String> EHomeResult = new EHomeResult<>();

        HCISUPCMS.NET_EHOME_XML_REMOTE_CTRL_PARAM struRemoteCtrl = new HCISUPCMS.NET_EHOME_XML_REMOTE_CTRL_PARAM();

        //输入参数
        if (StringUtils.isNotEmpty(inputXML)) {
            log.warn("InPut:"+ inputXML);

            HCISUPCMS.NET_DVR_STRING_POINTER struInputXML = new HCISUPCMS.NET_DVR_STRING_POINTER();
            struInputXML.read();
            struInputXML.byString = inputXML.getBytes("UTF-8");
            struInputXML.write();

            struRemoteCtrl.lpInbuffer = struInputXML.getPointer();
            struRemoteCtrl.dwInBufferSize = struInputXML.byString.length;
            struRemoteCtrl.write();
        }

        HCISUPCMS.NET_DVR_STRING_POINTER stringXMLOut = new HCISUPCMS.NET_DVR_STRING_POINTER();

        struRemoteCtrl.lpStatusBuffer = stringXMLOut.getPointer();
        struRemoteCtrl.dwStatusBufferSize = stringXMLOut.size();

        //必须设置dwSize否则报错误码:17,linux中错误信息显示更详细
        struRemoteCtrl.dwSize = struRemoteCtrl.size();
        struRemoteCtrl.dwRecvTimeOut = 50000;
        struRemoteCtrl.dwSendTimeOut = 50000;

        struRemoteCtrl.write();

        boolean result = hCEhomeCMS.NET_ECMS_XMLRemoteControl(loginID,struRemoteCtrl,struRemoteCtrl.size());

        if(!result)
        {
            int iErr = hCEhomeCMS.NET_ECMS_GetLastError();

            EHomeResult.setSuccess(false);
            EHomeResult.setCode(iErr);
            EHomeResult.setMessage("NET_ECMS_XMLConfig失败，错误号：" + iErr);
        }
        else
        {
            struRemoteCtrl.read();
            stringXMLOut.read();
            String strOutXML = new String(stringXMLOut.byString).trim();

            EHomeResult.setSuccess(true);
            EHomeResult.setData(strOutXML.trim());
        }

        return EHomeResult;
    }
}
