#include "DevAuthorize.h"
#include "Runtime.h"

extern "C"{
	#include "HW_config.h"
	#include "user_eeprom.h"
}

#define dWdClr		clSkyBlue
#define dWdDisabelClr	clNearWhite

#define dWWidth	24
#define dWHeigh	24
#define dRoundR	7

#define genNumValidTime (24*60*60) // 1 day  uint:1s
#define validAuthTimeMax (90*24*60*60)//90day

void TDevAuthorize::Init()
{
	unsigned int i = 0;
	unsigned char numChar = 0;
	
	IsPermission =0;
	
	
	
	Tag.Reset();
	SaveSta = 0;
	
	for(i=0;i<12;i++){
		AuthCfg.prm.serNum[i] = uid_value.val_8[i];
		
		if((uid_value.val_8[i] & 0xF0) > 0x90){
			MainCtl.Sn[i*2] = 'A' + ((uid_value.val_8[i]>>4) & 0x0F) - 0x0A;
		}else{
			MainCtl.Sn[i*2] = '0' + ((uid_value.val_8[i]>>4) & 0x0F);
		}
		
		if((uid_value.val_8[i] & 0x0F) > 0x09){
			MainCtl.Sn[i*2+1] = 'A' + (uid_value.val_8[i] & 0x0F) - 0x0A;
		}else{
			MainCtl.Sn[i*2+1] = '0' + (uid_value.val_8[i] & 0x0F);
		}
	}
	MainCtl.Sn[24] = 0;
	MainCtl.Sn[25] = 0;
	CommonDelayMs(10);
	eeprom_read_byte(0, (dEepAddrAuthorizePrm + 0), ((unsigned char *)(&AuthCfg.prm.workTime)),4);
	CommonDelayMs(1);
	eeprom_read_byte(0, (dEepAddrAuthorizePrm + 4), ((unsigned char *)(&AuthCfg.prm.genNum)), 4);
	CommonDelayMs(1);
	eeprom_read_byte(0, (dEepAddrAuthorizePrm + 8), ((unsigned char *)(&AuthCfg.prm.genNumTime)), 4);
	CommonDelayMs(1);
	eeprom_read_byte(0, (dEepAddrAuthorizePrm +12), ((unsigned char *)(&AuthCfg.prm.validAuthTime)), 4);
	
	if(0xFFFFFFFF == AuthCfg.prm.genNumTime){
		AuthCfg.prm.genNumTime = 0;
	}
	
	if(0xFFFFFFFF == AuthCfg.prm.workTime){
		AuthCfg.prm.genNumTime = 0;
	}
	
	if((AuthCfg.prm.validAuthTime > 0)&&(AuthCfg.prm.validAuthTime <= 0xAA55AA55)){
		if(0xAA55AA55 == AuthCfg.prm.validAuthTime){
			SysIsAuthState = 2;
			SysAuthorize.fDa.Done = 1;
		}else
		if((AuthCfg.prm.validAuthTime > AuthCfg.prm.workTime) && ((AuthCfg.prm.validAuthTime - AuthCfg.prm.workTime) <= validAuthTimeMax)){
			SysIsAuthState = 1;
			SysAuthorize.fDa.Done = 1;
			SysRemainAuthTimeHour = (AuthCfg.prm.validAuthTime - AuthCfg.prm.workTime)/3600%1000000;
		}else{
			SysAuthorize.fDa.Done = 0;
			SysIsAuthState = 0;
		}
	}else{
		SysAuthorize.fDa.Done = 0;
	}
	
	if((AuthCfg.prm.genNumTime + genNumValidTime > AuthCfg.prm.workTime)&&(AuthCfg.prm.genNum)&&(AuthCfg.prm.genNum < 0xFFFFFFFF)){
		for(i=0;i<8;i++){
			numChar = (AuthCfg.prm.genNum >> (28-i*4)) & 0x0F;
			if(numChar > 0x9){
				MainCtl.GenSn[i] = 'A' + numChar - 0x0A;
			}else{
				MainCtl.GenSn[i] = '0' + numChar;
			}
		}
		MainCtl.GenSn[8] = 0;
		MainCtl.GenSn[9] = 0;
	}else{
		MainCtl.GenSn[0] = 0;
		MainCtl.GenSn[1] = 0;
	}
	
	TimeSecHasRun = AuthCfg.prm.workTime / 3600;
}

void TDevAuthorize::GetGenSn()
{
	unsigned int i = 0;
	unsigned char numChar = 0;
	
	for(i=0;i<8;i++){
		numChar = (AuthCfg.prm.genNum >> (28-i*4)) & 0x0F;
		if(numChar > 0x9){
			MainCtl.GenSn[i] = 'A' + numChar - 0x0A;
		}else{
			MainCtl.GenSn[i] = '0' + numChar;
		}
	}
	MainCtl.GenSn[8] = 0;
	MainCtl.GenSn[9] = 0;
}

void TDevAuthorize::DelayMs(unsigned int aMs)
{
	volatile unsigned int mTick;
	volatile unsigned int Tick;
	for(Tick=0; Tick<aMs; Tick++){
		for(mTick=0; mTick<160000; mTick++);
	}
}

void TDevAuthorize::RenderBackGround(void)
{
	RectFillRender(ContentGeometry.Left, ContentGeometry.Top, ContentGeometry.Right, ContentGeometry.Bottom, ContentColor);
}

void TDevAuthorize::RenderBackGround(unsigned int aClr)
{
	RectFillRender(ContentGeometry.Left, ContentGeometry.Top, ContentGeometry.Right, ContentGeometry.Bottom, aClr);
}

void TDevAuthorize::DrawSelf(void)
{
	RectFillRender(Lv.Caption.Left, Lv.Caption.Top, Lv.Caption.Right, Lv.Caption.Bottom, CaptionColor);

	
	for(int i=0; i<Lv.Grid.UsingCount; i++)RectFillRender(Lv.Grid.Left[i], Lv.Grid.Top[i], Lv.Grid.Right[i], Lv.Grid.Bottom[i], ItemColor);

	if(LanguageEnCn==0){
		TextRender_string24(Lv.Caption.Left + 10, Lv.Caption.Top +4, clNearWhite,  "工程->系统授权");
		TextRender_string24(Lv.Grid.Left[0] + 6, Lv.Grid.Top[0] +8, clNearWhite,  "工程名称");
		TextRender_string24(Lv.Grid.Left[0] + 520, Lv.Grid.Top[0] +8, clNearWhite,  "运行时长:");
		TextDigitRender5Right24(Lv.Grid.Left[0] + 636, Lv.Grid.Top[0] +8, clNearWhite, TimeSecHasRun / 24);
		TextRender_string24(Lv.Grid.Left[0] + 698, Lv.Grid.Top[0] +8, clNearWhite,  "天");
		TextDigitRender2Right24(Lv.Grid.Left[0] + 722, Lv.Grid.Top[0] +8, clNearWhite, TimeSecHasRun % 24);
		TextRender_string24(Lv.Grid.Left[0] + 746, Lv.Grid.Top[0] +8, clNearWhite,  "小时");
		TextRender_string24(Lv.Grid.Left[1] + 6, Lv.Grid.Top[1] +8, clNearWhite,  "系统授权");
		//TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +50, clNearWhite,  "正常运行");
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] +8, clNearWhite,  "产品序列号:");
		TextRender_string24(Lv.Grid.Left[2] + 138, Lv.Grid.Top[2] +8, clNearWhite,  MainCtl.Sn);
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] +46, clNearWhite,  "产品生成码:");
		TextRender_string24(Lv.Grid.Left[2] + 280, Lv.Grid.Top[2] +46, clNearWhite,  MainCtl.GenSn);
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] + 82, clNearWhite,  "产品授权码:");
	}else{
		TextRender_string24(Lv.Caption.Left + 10, Lv.Caption.Top +4, clNearWhite,  "Project->Authorization");
		TextRender_string24(Lv.Grid.Left[0] + 6, Lv.Grid.Top[0] +8, clNearWhite,  "PrjName");
		TextRender_string24(Lv.Grid.Left[0] + 520, Lv.Grid.Top[0] +8, clNearWhite,  "Duration:");
		TextDigitRender5Right24(Lv.Grid.Left[0] + 636, Lv.Grid.Top[0] +8, clNearWhite, TimeSecHasRun / 24);
		TextRender_string24(Lv.Grid.Left[0] + 698, Lv.Grid.Top[0] +8, clNearWhite,  "D");
		TextDigitRender2Right24(Lv.Grid.Left[0] + 722, Lv.Grid.Top[0] +8, clNearWhite, TimeSecHasRun % 24);
		TextRender_string24(Lv.Grid.Left[0] + 746, Lv.Grid.Top[0] +8, clNearWhite,  "Hour");
		
		TextRender_string24(Lv.Grid.Left[1] + 6, Lv.Grid.Top[1] +8, clNearWhite,  "Authoriza");
		//TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +50, clNearWhite,  "正常运行");
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] +8, clNearWhite,  "Ser Number:");
		TextRender_string24(Lv.Grid.Left[2] + 138, Lv.Grid.Top[2] +8, clNearWhite,  MainCtl.Sn);
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] +46, clNearWhite,   "Reg Code  ");
		TextRender_string24(Lv.Grid.Left[2] + 280, Lv.Grid.Top[2] +46, clNearWhite,  MainCtl.GenSn);
		TextRender_string24(Lv.Grid.Left[2] + 6, Lv.Grid.Top[2] + 82, clNearWhite,  "Activation");		
	}
	
	ShowIfDone();
}

void TDevAuthorize::Show(void)
{	
	RenderBackGround();
	DrawSelf();
}

void TDevAuthorize::FullRedraw(int Prm)
{	
	if(Prm == 0){
		RenderBackGround();
		DrawSelf();
		aPanel->ReDrawItems();
		Check4Selected();
	}else
	if(Prm == 1){
		RectFillRender(GuiRedrawDataList[1][0], GuiRedrawDataList[1][1], GuiRedrawDataList[1][2], GuiRedrawDataList[1][3], ContentColor);
		DrawSelf();
		aPanel->ReDrawItems();
		Check4Selected();
		
		//if(IsPermission)PmsIntervene4Gui.ReDraw4GuiRecall();
	}
}


//______________________________________________________________________________________________________________________________
void TDevAuthorize::ClearSelected(void)
{
	if(Tag.Inx0 == 0){
		aPanel->Btn[1].Selected = 0;
		aPanel->Btn[1].Show();
	}else
	if(Tag.Inx0 == 1){
		aPanel->Btn[0].Selected = 0;
		aPanel->Btn[0].Show();
	}else
	if(Tag.Inx0 == 2){
		aPanel->Edit[1].Selected = 0;
		aPanel->Edit[1].Show();
	}
}


void TDevAuthorize::Check4Selected(void)
{
	if(Tag.Inx0 == 0){
		aPanel->Btn[1].Selected = 1;
		aPanel->Btn[1].Show();
	}else
	if(Tag.Inx0 == 1){
		aPanel->Btn[0].Selected = 1;
		aPanel->Btn[0].Show();
	}else
	if(Tag.Inx0 == 2){
		aPanel->Edit[1].Selected = 1;
		aPanel->Edit[1].SetPstTail();
		aPanel->Edit[1].Show();
	}
}

void TDevAuthorize::ShowIfDone()
{
	if(LanguageEnCn==0){
		if(SysAuthorize.fDa.Done){
			TCircle::sRender(Lv.Grid.Left[1] + 24, Lv.Grid.Top[1] +54, 12, clDeepGreen, 1);
			TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +42, clNearWhite, ItemColor, "系统已授权");
			if(0xAA55AA55 == AuthCfg.prm.validAuthTime){
				TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite,  ItemColor,	"永久使用                               ");
			}else{
				TMyString::sFromStr("剩余使用时间:",Text);
				TMyString::sAddOn4Dg(((AuthCfg.prm.validAuthTime - AuthCfg.prm.workTime)/3600%1000000),Text);
				TMyString::sAddOnStr("小时",Text);
				TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite, ItemColor,  Text);
			}
		}else{
			TCircle::sRender(Lv.Grid.Left[1] + 24, Lv.Grid.Top[1] +54, 12, clRed, 1);
			TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +42, clNearWhite, ItemColor, "系统未授权");
			
			TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite,  	ItemColor,	"剩余使用时间:   0小时    ");
		}
	}else{
		if(SysAuthorize.fDa.Done){
			TCircle::sRender(Lv.Grid.Left[1] + 24, Lv.Grid.Top[1] +54, 12, clDeepGreen, 1);
			TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +42, clNearWhite, ItemColor, "Licensed");
			if(0xAA55AA55 == AuthCfg.prm.validAuthTime){
				TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite,  ItemColor,	"Forever                                ");
			}else{
				TMyString::sFromStr("Remaining usage",Text);
				TMyString::sAddOn4Dg(((AuthCfg.prm.validAuthTime - AuthCfg.prm.workTime)/3600%1000000),Text);
				TMyString::sAddOnStr("Hours",Text);
				TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite, ItemColor,  Text);
			}
		}else{
			TCircle::sRender(Lv.Grid.Left[1] + 24, Lv.Grid.Top[1] +54, 12, clRed, 1);
			TextRender_string24(Lv.Grid.Left[1] + 46, Lv.Grid.Top[1] +42, clNearWhite, ItemColor, "Unlicensed");
			TextRender_string24(Lv.Grid.Left[1] + 186, Lv.Grid.Top[1] +42, clNearWhite,  	ItemColor,	"Remaining:      0Hours    ");
		}
	}
}

void TDevAuthorize::ShowMth()
{

}

void TDevAuthorize::ShowVision()
{

}

void TDevAuthorize::ShowSound()
{

}

void TDevAuthorize::PermissionCmdReturnDraw()
{
	//PmsIntervene4Gui.Show4Gui(Lv.Grid.Left[3] + 200, Lv.Grid.Top[3] + 12, 400, 120, 2);
	RectFillRender(Lv.Grid.Left[3] + 200-10, Lv.Grid.Top[3] + 14 -10, Lv.Grid.Left[3] + 200-10 + 420, Lv.Grid.Top[3] + 14 -10 + 138, ContentColor);	
}

//_____________________________________________________________________________________________________________________________

TGuiMsgReturn TDevAuthorize::KeyIn(unsigned char aKey)
{
	TGuiMsgReturn aMsg = guiMsgNone;
	TGuiMsgReturn MBoxMsg = guiMsgNone;
	int iVal;
	
	TGuiMsgReturn PmsRtnMsg;
	if(IsPermission){
		PmsRtnMsg = PmsIntervene4Gui.KeyIn(aKey);
		if(PmsRtnMsg == guiMsgOkAndReturn){
			//Enter And Run Go
			IsPermission = 0;
			PermissionCmdReturnDraw();
			PermissionCmdGO();
		}else
		if(PmsRtnMsg == guiMsgReturn){
			//Not Enter Redraw
			IsPermission = 0;
			PermissionCmdReturnDraw();
		}
		return aMsg;
	}else{
		switch(aKey){
			case VK_DELETE: 
			case  VK_0:	
			case  VK_1:
			case  VK_2:
			case  VK_3:
			case  VK_4:
			case  VK_5:
			case  VK_6:	
			case  VK_7:
			case  VK_8:
			case  VK_9:
			case  VK_LEFT:
			case  VK_RIGHT:
				if(Tag.Inx0 ==2){
					aPanel->Edit[1].KeyIn(aKey);
					aPanel->Edit[1].Show();
					aPanel->Edit[1].ShowCursor();
				}
				break;
			case VK_UP:
				if(IfShowAuthorizeButton){
					if(Tag.Inx0 >0){
						ClearSelected();
						Tag.Inx0--;
						Check4Selected();
					}
				}else{
					if(Tag.Inx0 >1){
						ClearSelected();
						Tag.Inx0--;
						Check4Selected();
					}
				}
				break;
			case VK_DOWN:
				if(Tag.Inx0 <2){
					ClearSelected();
					Tag.Inx0++;
					Check4Selected();
				}
				break;
			case VK_F1:
				break;
			case VK_EXECUTE:
				if(Tag.Inx0 == 0){
					//Do DisShow
					set_auth_function_able(1);
					Check2IfShowAuthorizeButton();
					if(IfShowAuthorizeButton == 0){
						IfShowAuthorizeButton = 0;
						aPanel->Btn[1].Enable = 0;
						ClearSelected();
						Tag.Inx0 =1;
						Check4Selected();
					}
				}else
				//Save Data Here
				if(Tag.Inx0 ==1){
					PermissionCmd = 1;
					if(SystemPermission > 1){
						PermissionCmdGO();
					}else{
						IsPermission =1;
						PmsIntervene4Gui.Show4Gui(Lv.Grid.Left[3] + 200, Lv.Grid.Top[3] + 14, 400, 116, 2);
					}
				}else
				if(Tag.Inx0 == 2){
					PermissionCmd = 2;
					if(SystemPermission > 1){
						PermissionCmdGO();
					}else{
						IsPermission =1;
						PmsIntervene4Gui.Show4Gui(Lv.Grid.Left[3] + 200, Lv.Grid.Top[3] + 14, 400, 116, 2);
					}
				}
				break;
			case VK_RETURN:
				aMsg = guiMsgReturn;
				break;
		}
		if( (aKey != VK_EXECUTE) && (aKey != VK_RETURN) ){
			ShowSta(0);
		}
	}
	
	return aMsg;	
}

void TDevAuthorize::PermissionCmdGO()
{
	if(PermissionCmd == 2){
		WriteData();
	}else
	if(PermissionCmd == 1){
		GenRandomCode();
	}
	IsPermission = 0;
}

void TDevAuthorize::InitPanel(void)
{
	int i;
	aPanel->Init(400,400,10,10,0,0,clFrmFace, bvRaised);
	
	aPanel->Edit[0].Init(Lv.Grid.Left[0] +104, Lv.Grid.Top[0] + 2, 400, 	32, 	0,0,	1,ItemColor);
	aPanel->Btn[0].Init(Lv.Grid.Left[2] + 138, Lv.Grid.Top[2] + 40,120,	34,	0,0,	1,clFrmFace);
	aPanel->Edit[1].Init(Lv.Grid.Left[2] + 138, Lv.Grid.Top[2] + 76,300,	30,	0,0,	1,ItemColor);
	
	for(i=0; i<1; i++){
		aPanel->Edit[i].IsShowCursor = 0;
		aPanel->Edit[i].Enable = 1;
		aPanel->Edit[i].Visible = 1;
	}
	aPanel->Btn[0].Color = clFrmFace;
	aPanel->Btn[0].Enable = 1;
	aPanel->Btn[0].Visible = 1;
	aPanel->Btn[0].SetCaptionLeftSpacing(6);
	if(LanguageEnCn==0)aPanel->Btn[0].SetCaption(	"确认生成",24); 
	else aPanel->Btn[0].SetCaption(			"Generate",24); 
	aPanel->Btn[0].SelectedColor = clBlue;
	aPanel->Btn[0].SelectedTextColor = clNearWhite;
	for(i=1; i<2; i++){
		aPanel->Edit[i].IsShowCursor = 1;
		aPanel->Edit[i].Enable = 1;
		aPanel->Edit[i].Visible = 1;
		aPanel->Edit[i].MaxLen = 24;
		aPanel->Edit[i].IsShowCursor = 1;
		aPanel->Edit[i].Str.Clear();
	}
	Check2IfShowAuthorizeButton();
	aPanel->Btn[1].Init(Lv.Grid.Left[1] + 138, Lv.Grid.Top[1] + 6,120,	34,	0,0,	1,clFrmFace);
	aPanel->Btn[1].Color = clFrmFace;
	aPanel->Btn[1].Enable =1;
	aPanel->Btn[1].Visible = 1;
	aPanel->Btn[1].SetCaptionLeftSpacing(6);
	if(LanguageEnCn==0)aPanel->Btn[1].SetCaption("使能授权",24);
	else aPanel->Btn[1].SetCaption("Register",24);
	aPanel->Btn[1].SelectedColor = clBlue;
	aPanel->Btn[1].SelectedTextColor = clNearWhite;
}

void TDevAuthorize::LoadData()
{
	Setting.IsNormal = RunState;
	//Setting.Hours = RunModeData.Hours;

	for(int i=0; i<32; i++){
		aPanel->Edit[0].Str.Text[i] = PrjName[i];
	}
	aPanel->Edit[0].Str.Text[32] = '\0';
	aPanel->Edit[0].Str.Text[33] = '\0';
	
	if(IfShowAuthorizeButton){
		aPanel->Btn[1].Enable =1;
		Tag.Inx0 = 0;
	}else{
		aPanel->Btn[1].Enable =0;
		Tag.Inx0 = 1;
	}
	
	ShowIfDone();
	aPanel->ReDrawItems();
	
	Check4Selected();
}

void TDevAuthorize::WriteData()
{
	//RunModeData.IsNormal = Setting.IsNormal;
	
	unsigned int charLen= aPanel->Edit[1].Str.GetLength();
	if(0 == charLen){
		//请输入授权码
		ShowSta(-2);
	}else
	if(charLen > 5){
		//请输入正确长度的授权码
		ShowSta(-3);
	}else{
		AuthCfg.prm.authNum = aPanel->Edit[1].Str.ToInteger();
		
		if(CalcValidDay(&AuthCfg)){
			SysAuthorize.fDa.Done = 0;
			AuthCfg.prm.validAuthTime = 0;
			DelayMs(10);
			eeprom_write_byte_via_page(0, (dEepAddrAuthorizePrm +12), ((unsigned char *)(&AuthCfg.prm.validAuthTime)),4);
			DelayMs(10);
			
			ShowSta(-1);
		}else{
			if(0xA5C3 == AuthCfg.prm.validDay){//永久有效
				AuthCfg.prm.validAuthTime = 0xAA55AA55;
			}else{
				Setting.Hours = AuthCfg.prm.validDay * 24;
				AuthCfg.prm.validAuthTime = AuthCfg.prm.workTime + (AuthCfg.prm.validDay * 24 * 3600);
			}
			DelayMs(10);
			eeprom_write_byte_via_page(0, (dEepAddrAuthorizePrm +12), ((unsigned char *)(&AuthCfg.prm.validAuthTime)),4);
			DelayMs(10);
			
			SysAuthorize.fDa.Done = 1;
			
			ShowSta(1);
		}
		
		ShowIfDone();
		
		if(Setting.Hours == 0) Setting.Hours = 2;
		if(Setting.Hours > 99) Setting.Hours = 99;
		//RunModeData.Hours = Setting.Hours;
		
		LoadData();
	}
}

void TDevAuthorize::ShowSta()
{
	if(LanguageEnCn==0){
		if(SaveSta == 0){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "                      ");
		}else
		if(SaveSta == 1){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "授权成功              ");
			ShowIfDone();
		}else
		if(SaveSta == -1){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "授权失败              ");
			ShowIfDone();
		}else
		if(SaveSta == -2){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "请输入授权码          ");
			ShowIfDone();
		}else
		if(SaveSta == -3){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "请输入正确长度的授权码");
			ShowIfDone();
		}
	}else{
		if(SaveSta == 0){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "                        ");
		}else
		if(SaveSta == 1){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "Successfully Registered ");
			ShowIfDone();
		}else
		if(SaveSta == -1){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "Failed To Register      ");
			ShowIfDone();
		}else
		if(SaveSta == -2){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "Enter Activation Key    ");
			ShowIfDone();
		}else
		if(SaveSta == -3){
			TextRender_string24(ResultSavePoint.x, ResultSavePoint.y, clNearWhite, ItemColor, "Activation Key Error    ");
			ShowIfDone();
		}
	}
}

void TDevAuthorize::ShowSta(int aSta)
{
	SaveSta = aSta;
	ShowSta();
}

static const uint16_t crc16Table[256] = {
    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};

static const uint16_t crc16_xmodem_table[256] = {
    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
    0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
    0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
    0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
    0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
    0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
    0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
    0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
    0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
    0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
    0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
    0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
    0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
    0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
    0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
    0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
    0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
    0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
    0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
    0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
    0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
    0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
    0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
    0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
    0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
    0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
    0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
    0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
    0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
    0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
    0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
    0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};

unsigned short TDevAuthorize::myCrc16(unsigned char *pD, unsigned int len)
{
	uint16_t crc = 0x0000;  // 初始值，与标准算法一致
	unsigned int i,index;
	if (pD == NULL || len == 0) {
		return crc;  // 空数据返回初始值
	}

	for (i = 0; i < len; i++) {
		// 核心查表操作：(CRC左移8位) XOR 查表结果
		crc = (crc << 8) ^ crc16_xmodem_table[(crc >> 8) ^ pD[i]];
	}

	return crc;  // 无需异或输出，直接返回结果
}

/*
unsigned short TDevAuthorize::myCrc16(unsigned char *pD, unsigned int len)
{
    unsigned int i,index;
    unsigned short aCrc = 0xFFFF;

    for (i = 0; i < len; i++) {
        index = static_cast<uint8_t>(aCrc ^ pD[i]);
        aCrc = (aCrc >> 8) ^ crc16Table[index];
    }

    return aCrc;
}
*/
void TDevAuthorize::GenRandomCode()
{
	unsigned int aRandomCode;
	unsigned int aValue;
	
	aValue = LL_TIM_GetCounter(TIM7);
	aValue = aValue & 0xFFFF;
	aValue+= ((AuthCfg.prm.workTime>>16)&0xFFFF);
	aValue+= ((AuthCfg.prm.workTime<<16)&0xFFFF0000);
	
	aRandomCode = rand();
	aRandomCode ^= aValue;
	aRandomCode += aValue;
	
	if((0 == aRandomCode)||(0xFFFFFFFF == aRandomCode)){
		aRandomCode = rand();
		aRandomCode ^= aValue;
		aRandomCode += aValue;
	}
	
	AuthCfg.prm.genNum = aRandomCode;
	
	//---------------record genNum and gen time-----------------------------------
	DelayMs(10);
	eeprom_write_byte_via_page(0, (dEepAddrAuthorizePrm + 4), ((unsigned char *)(&AuthCfg.prm.genNum)),4);
	DelayMs(10);
	AuthCfg.prm.genNumTime = AuthCfg.prm.workTime;
	eeprom_write_byte_via_page(0, (dEepAddrAuthorizePrm + 8), ((unsigned char *)(&AuthCfg.prm.genNumTime)),4);
	DelayMs(10);
	
	GetGenSn();
	TextRender_string24(Lv.Grid.Left[2] + 280, Lv.Grid.Top[2] +46, clNearWhite, ItemColor, MainCtl.GenSn);
}	

unsigned int TDevAuthorize::CalcValidDay(TAuthCalc * aCalcNum)
{
	unsigned int res = 0;
	
	//生成码过期
	if((aCalcNum->prm.genNumTime + genNumValidTime) < aCalcNum->prm.workTime){
		res = 1;
		return res;
	}
	//先认证是否是长期有效，长期有效码是0xA5C3
	aCalcNum->prm.validDay = 0xA5C3;
	if(aCalcNum->prm.authNum == (myCrc16(aCalcNum->d8, 18))){
		return res;
	}
	//获取有效天数
	for(aCalcNum->prm.validDay = 1;aCalcNum->prm.validDay < 10000;aCalcNum->prm.validDay++){
		if(aCalcNum->prm.authNum == (myCrc16(aCalcNum->d8, 18))){
			return res;
		}
	}
	//成功返回0，失败返回1
	res = 1;
	return res;
}

void TDevAuthorize::Check2IfShowAuthorizeButton()
{
	//Value 1 to Show the Button to Active Function Authorizing
	if(!check_auth_function_isenable()){
		IfShowAuthorizeButton =1;
	}else{
		IfShowAuthorizeButton =0;
	}
}

void TDevAuthorize::Task1000Ms()
{
	AuthCfg.prm.workTime++;
	if(0 == (AuthCfg.prm.workTime % 600)){
		DelayMs(10);
		eeprom_write_byte_via_page(0, dEepAddrAuthorizePrm, ((unsigned char *)(&AuthCfg.prm.workTime)),4);
		HAL_Delay(10);
	}
	
	if(AuthCfg.prm.validAuthTime < AuthCfg.prm.workTime){//授权结束
		SysAuthorize.fDa.Done = 0;	
	}
}








