#include "remote.h"
#include "module_wrapper.h"
#include "TypeDefine.h"
#include "SystemAlarm.h"
#include "string.h"
#include "sys.h"
#include "DrawLCDGUI.h"
#include "ProgramData.h"
#include "cJSON.h"
#include "AES.h"
#include <stdlib.h>

#define REMOTE_CH 1

uint8_t remote_flag = 0;

extern uint8_t mcu_id[8];              //mcu ID号缓冲区
extern uint16_t Version_data;  //版本号

extern unsigned char key[17];
extern unsigned char expansionkey[15 * 16];

static int remoteModuleStartCou = 0; //注册是模块启动次数
static char remoteData[200] = {0};   

static void remoteModuleKeepLine(void)
{
	if(module_start_status == MODULE_OK && module_init_status == MODULE_OK)
  {
		if(module_channel[REMOTE_CH].connect_status == TCP_CLOSED && tcp_connect_status == TCP_OPEN)
		{
			at_module_channel_open(REMOTE_SERVER,REMOTE_PORT,TCP,REMOTE_CH);
		}
	}
}

static void packRemotetDataAndSend(void)
{
	int i=0;
	int datalen = 0;
	const char *method = "getRemoteConf";
	memset(remoteData,0, sizeof(remoteData));
	char* dataPtr = remoteData+2;
	memcpy(dataPtr,method,strlen(method));
	memcpy(dataPtr+strlen(dataPtr),"&",1);
	
	byteToHexStr(mcu_id, dataPtr+strlen(dataPtr), sizeof(mcu_id));
	
	datalen = ECBAesEncrypt((unsigned char*)dataPtr, expansionkey, 10);		//2、AES 加密
	remoteData[0] = datalen>>8;
	remoteData[1] = datalen;	
	at_module_send_ch(remoteData,datalen+2,REMOTE_CH,KEPP_RRC);
}

static void packRemotetDataJSONAndSend(void)
{
	int i=0;
	int datalen = 0;
	uint8_t mcuid_str[20]={0};
	const char *method = "getRemoteConf";
	char* dataPtr = remoteData+2;
	byteToHexStr(mcu_id, (char*)mcuid_str, sizeof(mcu_id));
	
	cJSON *jsonData = cJSON_CreateObject();
	cJSON *jsonParam = cJSON_CreateObject();
	cJSON_AddStringToObject(jsonData,"method","getRemoteConf");
	cJSON_AddStringToObject(jsonParam,"devive",(char*)mcuid_str);
	cJSON_AddItemToObject(jsonData,"params",jsonParam);
	char *ptrs = cJSON_PrintUnformatted(jsonData);
	memcpy(dataPtr,ptrs,strlen(ptrs));
	
	UsartPrintf(USART_DEBUG, "craete json:%s \r\n",ptrs);
	datalen = ECBAesEncrypt((unsigned char*)dataPtr, expansionkey, 10);
	remoteData[0] = datalen>>8;
	remoteData[1] = datalen;	
	at_module_send_ch(remoteData,datalen+2,REMOTE_CH,KEPP_RRC);
	
	end:
	  cJSON_Delete(jsonData);
	  free(ptrs);
}

//处理Coap注册信息,0: 成功, 1: 失败
static int handleRemoteInfo(void)
{
	int flag = 1;
	uint64_t hosnum = 0;
	//char str_mcu_id[20]={0};
	cJSON *json = NULL,
	*json_code = NULL,
	*json_type = NULL,
	*json_hosnum=NULL,
	*json_total=NULL,
	*json_limit = NULL,
	*json_add = NULL,
	*json_lock = NULL,
	*json_flow = NULL,
	*json_first = NULL;
	
	json = cJSON_Parse(module_channel[REMOTE_CH].valid_data.buf);
	if(!json)
	{
		UsartPrintf(USART_DEBUG, "json parse error,%s\r\n",cJSON_GetErrorPtr());
		goto end;
	}
	//UsartPrintf(USART_DEBUG, "json parse data,%s\r\n",module_channel[REMOTE_CH].valid_data.buf);
	json_code = cJSON_GetObjectItem(json,"code");
	json_type = cJSON_GetObjectItem(json,"type");
	json_hosnum = cJSON_GetObjectItem(json,"hosnum");
	json_total = cJSON_GetObjectItem(json,"total");
  json_limit = cJSON_GetObjectItem(json,"limit");
	json_add = cJSON_GetObjectItem(json,"add");
	json_flow = cJSON_GetObjectItem(json,"flow");
	json_first = cJSON_GetObjectItem(json,"first");
	UsartPrintf(USART_DEBUG, "json_code:%d\r\n",json_code->valueint);
	if(json_code && (json_code->valueint == 0))
	{
		if(json_type->valueint == 0x15)
		{
			if(json_hosnum)
			{
				UsartPrintf(USART_DEBUG, "json_hosnum:%d\r\n",json_hosnum->valuestring);
				hosnum = my_atoui64(json_hosnum->valuestring);
				verifyInfo.hospitalNO = hosnum;
			}
			if(json_total)
			{
				
				UsartPrintf(USART_DEBUG, "json_total:%d\r\n",json_total->valueint);
				setParamInfo.totalDose = json_total->valueint;
			}
			if(json_limit)
			{
				UsartPrintf(USART_DEBUG, "json_limit:%d\r\n",json_limit->valueint);
				setParamInfo.limitDose1=json_limit->valueint;
			}
			if(json_add)
			{
				UsartPrintf(USART_DEBUG, "json_add:%d\r\n",json_add->valueint);
				setParamInfo.superaddition1=json_add->valueint;
			}
			if(json_flow)
			{
				UsartPrintf(USART_DEBUG, "json_flow:%d\r\n",json_flow->valueint);
				setParamInfo.continueDose1 = json_flow->valueint;
			}
			if(json_first)
			{
				UsartPrintf(USART_DEBUG, "json_first:%d\r\n",json_first->valueint);
				setParamInfo.firstDose = json_first->valueint;
			}
		}
		
	}
	
	end:
	    cJSON_Delete(json);
	return flag;
}


void remoteHandle()
{
	static uint8_t send_flag = 1;
	static uint8_t remote_flag = 0; //远程配置结果， 0:未配置,1:已配置
	if(remote_flag) return;
	remoteModuleKeepLine();
	if(module_channel[REMOTE_CH].connect_status == TCP_OPEN && send_flag)
	{
		send_flag = 0;
		ScheduleKey(key, expansionkey, 4, 10);	//1、密钥扩展生成
		//packRemotetDataAndSend();
		packRemotetDataJSONAndSend();
	}
	at_module_handle_event();
	if(module_channel[REMOTE_CH].valid_data.len>0)
	{
		if(module_channel[REMOTE_CH].valid_data.len%AES_BLOCK_SIZE == 0)
		{
			remote_flag = 1;
			ECBAesDecrypt((unsigned char*)module_channel[REMOTE_CH].valid_data.buf,module_channel[REMOTE_CH].valid_data.len, expansionkey, 10);//AES 解密
			UsartPrintf(USART_DEBUG, "AesDecrypt valid_data,%s\r\n",module_channel[REMOTE_CH].valid_data.buf);
			handleRemoteInfo();
			channel_data_clear(REMOTE_CH);
		}
		else
		{
			UsartPrintf(USART_DEBUG, "AesDecrypt valid_data length error\r\n");
		}
		at_module_channel_close(REMOTE_CH);
	}
}
