//---------------------------------------------------------------------------
// For SELMA200, 20180223, moon, 변경사항 없음
//---------------------------------------------------------------------------

#include <vcl.h>
#include <FileCtrl.hpp>
#include <Inifiles.hpp>
#pragma hdrstop

#include "InspectionReport_Form.h"
#include "Environment.h"
#include "InspectionResultInsert_Form.h"
#include "NavigateDefectImage_Form.h"
#include "Message_Form.h"
#include "CalendarDialog_Form.h"
#include "PrintInspectionResult_Form.h"
#include "PrintInspectionResult_Ajanta_Form.h"
#include "Progress_Form.h"
#include "MultiLanguage.h"
#include "Main_Form.h"        
#include "Waiting_Form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntButtons"
#pragma link "TntExtCtrls"
#pragma link "TntGrids"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TInspectionReportForm *InspectionReportForm;
//---------------------------------------------------------------------------
__fastcall TInspectionReportForm::TInspectionReportForm(TComponent* Owner)
	: TTntForm(Owner)
{
	if (DefaultLCID == 1028 || DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		ComponentSetFontName(this, "SimSun");
	else if (DefaultLCID == 1041)
		ComponentSetFontName(this, "Meiryo UI");
  else if(DefaultLCID == 3082)
  {
    ComponentSetFontName(this, "Segoe UI");
    ComponentSetMultiLine(this);
  }

	GetDefaultString();
	ThroughputChartList = NULL;
	ThroughputChartListSize = 0;
	ThroughputChartCount = 0;

	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
	{
		RightMenuPanel->Visible = true;
		BrowseStartTime = Now();
		BrowseEndTime = Now();
		BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
		BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
		BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
		BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();
		StartDateTime = BrowseStartTime.DateString() + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
		EndDateTime = BrowseEndTime.DateString() + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();

		TntGroupBox2->Caption = AUDITTRAILFORM_GROUPBOX_CAPTION_01;
		TntGroupBox3->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_01;
		BrowseStartDateButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_02;
		BrowseEndDataButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_02;
		PeriodButton4->Caption = AUDITTRAILFORM_BUTTON_CAPTION_03;
		PeriodButton2->Caption = AUDITTRAILFORM_BUTTON_CAPTION_04;
		PeriodButton1->Caption = AUDITTRAILFORM_BUTTON_CAPTION_05;
		PeriodButton3->Caption = AUDITTRAILFORM_BUTTON_CAPTION_06;
		TntButton1->Caption = AUDITTRAILFORM_BUTTON_CAPTION_01;
		AllProductRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_03;
		SpecifiedProductRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_05;
		TntLabel2->Caption = AUDITTRAILFORM_LABEL_CAPTION_01;
		TntLabel3->Caption = AUDITTRAILFORM_LABEL_CAPTION_02;
	}
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::GetDefaultString()
{
	if (DefaultLCID == 1042 || DefaultLCID == 2066)
	{
		ThroughputChart->Title->Text->Strings[0] = "검사 속도(Tablet/Hour)";
		ThroughputChart->BottomAxis->Title->Caption = "시간";
		ThroughputChart->LeftAxis->Title->Caption = "수량";
		ThroughputChart->BottomAxis->AxisValuesFormat = "#O초";

		DefectChart->Title->Text->Strings[0] = "불량 분포";
	}
	else
	{
		ThroughputChart->Title->Text->Strings[0] = "Inspection Speed(Tablet/Hour)";
		ThroughputChart->BottomAxis->Title->Caption = "Time";
		ThroughputChart->LeftAxis->Title->Caption = "Quantity";
		ThroughputChart->BottomAxis->AxisValuesFormat = "#Osec";

		DefectChart->Title->Text->Strings[0] = "Defect distribution";
	}

	OkBitBtn->Caption = INSPECTIONREPORTFORM_BITBTN_CAPTION_01;
	NavigateDefectImageButton->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_02;
	DeleteInspectResultButton->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_03;
	EditInspectResultButton->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_04;
	InsertInspectResultButton->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_05;
	PrintButton->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_06;
	GroupBox6->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_01;
	GroupBox1->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_02;
	GroupBox3->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_03;
	GroupBox7->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_04;
	GroupBox4->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_05;
	GroupBox5->Caption = INSPECTIONREPORTFORM_GROUPBOX_CAPTION_06;
	Label50->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_01;
	Label1->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_02;
	Label40->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_03;
	Label48->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_04;
	Label17->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_06;
	Label3->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_07;
	Label12->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_08;
	Label34->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_09;
	Label44->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_10;
	Label52->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_11;
	Label10->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_12;
	Label71->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_13;
	Label47->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_14;
	Label15->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_15;
	Label53->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_16;
	Label4->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_17;
	Label9->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_18;
	Label54->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_19;
	Label28->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_20;
	Label13->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_21;
	Label11->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_22;
	GroupBox2->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_23;
	Label42->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_24;
	Label46->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_25;
	Label8->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_26;

	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
		Panel7->Caption = "Inspection History Each Batch";
	else
		Panel7->Caption = INSPECTIONREPORTFORM_PANEL_CAPTION_01;

	//add
	PrintButton2->Caption = INSPECTIONREPORTFORM_BUTTON_CAPTION_06;

	if (DefaultLCID != 1042)
		ProgressPanel->Caption = "Loading information. Please wait a second.";
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::FormCreate(TObject *Sender)
{
	InspectionReportStringGrid->ColCount = 11;
	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
		InspectionReportStringGrid->Cells[0][0] = "Batch";
	else
		InspectionReportStringGrid->Cells[0][0] = INSPECTIONSETUPFORM_LABEL_CAPTION_03; //"LOT";

	InspectionReportStringGrid->Cells[1][0] = INSPECTIONREPORTFORM_STRGRID_CELL_02;
	InspectionReportStringGrid->Cells[2][0] = INSPECTIONREPORTFORM_STRGRID_CELL_03;
	InspectionReportStringGrid->Cells[3][0] = INSPECTIONREPORTFORM_STRGRID_CELL_01;
	InspectionReportStringGrid->Cells[4][0] = INSPECTIONREPORTFORM_STRGRID_CELL_06;
	InspectionReportStringGrid->Cells[5][0] = INSPECTIONRESULTINSERTFORM_LABEL_CAPTION_19; // 임시
	InspectionReportStringGrid->Cells[6][0] = INSPECTIONREPORTFORM_STRGRID_CELL_04;
	InspectionReportStringGrid->Cells[7][0] = INSPECTIONREPORTFORM_STRGRID_CELL_05;
	InspectionReportStringGrid->Cells[8][0] = INSPECTIONREPORTFORM_STRGRID_CELL_08;
	InspectionReportStringGrid->Cells[9][0] = INSPECTIONREPORTFORM_STRGRID_CELL_09;
	InspectionReportStringGrid->Cells[10][0] = INSPECTIONREPORTFORM_STRGRID_CELL_07;
	InspectionReportStringGrid->ColWidths[1] = 200;
	InspectionReportStringGrid->ColWidths[2] = 200;

	InitInspectionReportList();
	beforeRowIndex = 0;
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::InitInspectionReportList(bool Option)
{
	// make inspection result list
	TSearchRec sr;
	int iAttributes = faAnyFile;

  try
  {
    InspectionReportList.clear();
    AnsiString resultDir = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Result";
    if (FindFirst(resultDir + "\\*.dat", iAttributes, sr) == 0)
    {
      do
      {
        if (Option)
        {
          if (SpecifiedProductRadioButton->Checked)
          {
            if (!AvailableLotNumCheck(sr.Name.SubString(0, sr.Name.Length() - 4)))
              continue;
          }
        }


        AnsiString inspectionReportFileName = resultDir + "\\" + sr.Name;

        NFA_INSPECTION_REPORT_STRUCT Report;
        bool Result = Read_InspectionReportData(inspectionReportFileName,Report);
        if(Result == false) continue;

        TInspectionListUnit inspectionListUnit;
        if (sr.Name.SubString(0, sr.Name.Length() - 4) == "123456_7891011") continue;

        // NEW START
        inspectionListUnit.ProductCode = ProductData.ProductCode;
        inspectionListUnit.LotName = sr.Name.SubString(0, sr.Name.Length() - 4);
        inspectionListUnit.InspectionStartTime.Val = Report.Data.InspectionStartTime;
        inspectionListUnit.InspectionEndTime.Val = Report.Data.InspectionEndTime;
        inspectionListUnit.InspectionCount = Report.Data.GoodTabletCount + Report.Data.DefectTabletCount + Report.Data.UnInsTabletCount;
        inspectionListUnit.GoodCount = Report.Data.GoodTabletCount;
        inspectionListUnit.DefectCount = Report.Data.DefectTabletCount;
        inspectionListUnit.UnInsCount = Report.Data.UnInsTabletCount;

        inspectionListUnit.UnPrintTabletCount = Report.Data.UnPrintTabletCount;
        inspectionListUnit.PrintMisMatchCount = Report.Data.PrintMisMatchCount;
        inspectionListUnit.SPBProcessingNCTabletCount = Report.Data.SPBProcessingNCTabletCount;
        inspectionListUnit.SPBTOTabletCount = Report.Data.SPBTOTabletCount;
        inspectionListUnit.SPBUnInsTabletCount = Report.Data.SPBUnInsTabletCount;
        inspectionListUnit.DisappearedTabletCount = Report.Data.DisappearedTabletCount;
        inspectionListUnit.InsertedTabletCount = Report.Data.InsertedTabletCount;
        inspectionListUnit.ClosedTabletUninsCount = Report.Data.ClosedTabletUninsCount;
        inspectionListUnit.ClosedTabletDefectCount = Report.Data.ClosedTabletDefectCount;
        inspectionListUnit.ClosedTabletCount = Report.Data.ClosedTabletCount;
        inspectionListUnit.WrongNumberTabletCount = Report.Data.WrongNumberTabletCount;
        inspectionListUnit.NumberUndefTabletCount = Report.Data.NumberUndefTabletCount;
        inspectionListUnit.CaptureNotReadyTabletCount = Report.Data.CaptureNotReadyTabletCount;
        inspectionListUnit.BufferFullTabletCount = Report.Data.BufferFullTabletCount;
        inspectionListUnit.CaptureTimoutTabletCount = Report.Data.CaptureTimoutTabletCount;
        inspectionListUnit.ProcessingTimoutTabletCount = Report.Data.ProcessingTimoutTabletCount;
        inspectionListUnit.CPBFullTabletCount = Report.Data.CPBFullTabletCount;
        inspectionListUnit.ProcessingErrorTabletCount = Report.Data.ProcessingErrorTabletCount;
        inspectionListUnit.UnInsTabletPositionCount = Report.Data.UnInsTabletPositionCount;
        inspectionListUnit.UnInsBrightnessDropCount = Report.Data.UnInsBrightnessDropCount;
        inspectionListUnit.UnInsBrightnessChaseCount = Report.Data.UnInsBrightnessChaseCount;
        inspectionListUnit.Sensor1MisFeedingTabletCount = Report.Data.Sensor1MisFeedingTabletCount;
        inspectionListUnit.Sensor2MisFeedingTabletCount = Report.Data.Sensor2MisFeedingTabletCount;
        inspectionListUnit.Sensor1MultiTabletCount = Report.Data.Sensor1MultiTabletCount;
        inspectionListUnit.Sensor2MultiTabletCount = Report.Data.Sensor2MultiTabletCount;
        inspectionListUnit.NozzErrorDefectTabletCount = Report.Data.NozzErrorDefectTabletCount;
	 inspectionListUnit.NozzErrorUnInsTabletCount = Report.Data.NozzErrorUnInsTabletCount;
        if (Report.Data.GoodTabletCount + Report.Data.DefectTabletCount > 0)
        {
          inspectionListUnit.DefectRatio = Report.Data.GoodTabletCount * 100.0 / (Report.Data.GoodTabletCount + Report.Data.DefectTabletCount);
        }
        else
        {
          inspectionListUnit.DefectRatio = 0;
        }
        inspectionListUnit.ProductionCount = Report.Data.ProductionCount;
        if (Report.Data.ProductionCount > 0)
        {
          inspectionListUnit.ProductionDefectRatio = Report.Data.GoodTabletCount * 100.0 / Report.Data.ProductionCount;
        }
        else
        {
          inspectionListUnit.ProductionDefectRatio = 0;
        }
        inspectionListUnit.OperatorName = AnsiString(Report.Data.OperatorName);

        InspectionReportList.push_back(inspectionListUnit);
      } while (FindNext(sr) == 0);

      FindClose(sr);
    }
    SortInspectionList(Option);
    ShowInspectionList();
  }
  catch(...)
  {
  }
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::SortInspectionList(bool Option)
{
	if (InspectionReportList.size() < 2) return;

	int ReportListSize = InspectionReportList.size();
	int Count = 0;
	if (Option)
	{
		vector<TInspectionListUnit>::iterator it;
		it = InspectionReportList.begin();

		while (true)
		{
			if (it->InspectionStartTime.Val >= (int)BrowseStartTime.Val &&
				it->InspectionStartTime.Val < (int)BrowseEndTime.Val + 1)
			{
				it++;
			}
			else
			{
				it = InspectionReportList.erase(it);
				Count++;
			}

			if (it == InspectionReportList.end())
				break;
		}
		ReportListSize = InspectionReportList.size();
		/*for(it =InspectionReportList.begin() ; it != InspectionReportList.end();)
		{
		if (it->InspectionStartTime.Val >= (int)BrowseStartTime .Val &&
		it->InspectionStartTime.Val < (int)BrowseEndTime.Val + 1)
		{
		it++;
		}
		else
		{
		it = InspectionReportList.erase(it);
		}
		}*/

		if (InspectionReportList.size() < 2) return;

		vector<TInspectionListUnit>::iterator it1, it2;
		for (it1 = InspectionReportList.end() - 1; it1 >= InspectionReportList.begin(); it1--)
		{
			for (it2 = InspectionReportList.begin(); it2 < it1; it2++)
			{
				if (it2->InspectionEndTime < (it2 + 1)->InspectionEndTime)
				{
					swap(*it2, *(it2 + 1));
				}
			}
		}
	}
	else
	{
		vector<TInspectionListUnit>::iterator it1, it2;
		for (it1 = InspectionReportList.end() - 1; it1 >= InspectionReportList.begin(); it1--)
		{
			for (it2 = InspectionReportList.begin(); it2 < it1; it2++)
			{
				if (it2->InspectionEndTime < (it2 + 1)->InspectionEndTime)
				{
					swap(*it2, *(it2 + 1));
				}
			}
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::ShowInspectionList(void)
{
	vector<TInspectionListUnit>::iterator it;

	for (int i = 1; i < InspectionReportStringGrid->RowCount; ++i)
	{
		InspectionReportStringGrid->Rows[i]->Clear();
	}

	int rowIndex = 1;
	if (InspectionReportList.size() == 0)
	{
		InspectionReportStringGrid->RowCount = 2;
	}
	else
	{
		InspectionReportStringGrid->RowCount = InspectionReportList.size() + 1;
	}
	for (it = InspectionReportList.begin(); it < InspectionReportList.end(); it++)
	{
		InspectionReportStringGrid->Cells[0][rowIndex] = it->LotName;
		InspectionReportStringGrid->Cells[1][rowIndex] = it->InspectionStartTime.DateTimeString();
		InspectionReportStringGrid->Cells[2][rowIndex] = it->InspectionEndTime.DateTimeString();
		InspectionReportStringGrid->Cells[3][rowIndex] = FloatToStrF(it->InspectionCount, ffNumber, 10, 0);
		InspectionReportStringGrid->Cells[4][rowIndex] = FloatToStrF(it->GoodCount, ffNumber, 10, 0);
		InspectionReportStringGrid->Cells[5][rowIndex] = FloatToStrF(it->DefectCount, ffNumber, 10, 0);
		InspectionReportStringGrid->Cells[6][rowIndex] = FloatToStrF(it->UnInsCount, ffNumber, 10, 0);
		InspectionReportStringGrid->Cells[7][rowIndex] = FloatToStrF(it->DefectRatio, ffGeneral, 4, 2) + "%";
		InspectionReportStringGrid->Cells[8][rowIndex] = FloatToStrF(it->ProductionCount, ffNumber, 10, 0);
		InspectionReportStringGrid->Cells[9][rowIndex] = FloatToStrF(it->ProductionDefectRatio, ffGeneral, 4, 2) + "%";
		InspectionReportStringGrid->Cells[10][rowIndex] = it->OperatorName;
		rowIndex++;
	}

	int listIndex = InspectionReportStringGrid->Row - 1;
	if (listIndex < 0 || listIndex >= InspectionReportList.size())
	{
		PrintButton->Enabled = false;
		PrintButton2->Enabled = false;
		BatchEndBtn->Enabled = false;
	}
	else
	{
		PrintButton->Enabled = true;
		PrintButton2->Enabled = true;

		Ajanta_BatchStatusControl();
	}
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::InsertInspectResultButtonClick(
	TObject *Sender)
{
	TInspectionResultInsertForm *inspectionResultInsertForm = new TInspectionResultInsertForm(this);
	try
	{
		if (inspectionResultInsertForm->ShowModal() == mrOk)
		{
			AnsiString resultDir = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Result";
			if (!DirectoryExists(resultDir))
			{
				ForceDirectories(resultDir);
			}
			AnsiString inspectionReportFileName = resultDir + "\\" + inspectionResultInsertForm->LOTName + ".dat";

      NFA_INSPECTION_REPORT_STRUCT Report;
      memset(&Report,0,sizeof(NFA_INSPECTION_REPORT_STRUCT));

      // DATA
      Report.Data = inspectionResultInsertForm->TabletInspectReport;

      char Temp[64] = {0,};
      WideCharToMultiByte(CP_ACP,0,ProductData.ProductName.c_bstr(),-1,Temp,64,NULL,NULL);
      strncpy(Report.Data.ProductName,Temp, 64);
		  strncpy(Report.Data.OperatorName, UserInfo.Name.c_str(), 32);

      // GRADE
      Report.GradeData = inspectionResultInsertForm->TabletInspectGradeData;

      Create_Report_Data(Report,inspectionReportFileName);
		}
		delete inspectionResultInsertForm;
		InitInspectionReportList();
	}
	catch (...)
	{
		WritePCProgramErrorLog(this->Name, __LINE__);
		if (inspectionResultInsertForm) delete inspectionResultInsertForm;
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::NavigateDefectImageButtonClick(
	TObject *Sender)
{
	int listIndex = InspectionReportStringGrid->Row - 1;
	if (listIndex < 0 || listIndex >= InspectionReportList.size()) return;
	AnsiString productCode = InspectionReportList[listIndex].ProductCode;
	AnsiString lotName = InspectionReportList[listIndex].LotName;

	NavigateDefectImageButton->Enabled = false;
	PrintButton->Enabled = false;
	InsertInspectResultButton->Enabled = false;
	EditInspectResultButton->Enabled = false;
	DeleteInspectResultButton->Enabled = false;
	PrintButton2->Enabled = false;
	OkBitBtn->Enabled = false;
	InspectionReportStringGrid->Enabled = false;

	WaitingForm->SetMessage(MAINFORM_MSG_13);
	WaitingForm->Show();
	Application->ProcessMessages();

	TNavigateDefectImageForm *navigateDefectImageForm = new TNavigateDefectImageForm(this);
	WaitingForm->Hide();

	NavigateDefectImageButton->Enabled = true;
	PrintButton->Enabled = true;
	InsertInspectResultButton->Enabled = true;
	EditInspectResultButton->Enabled = true;
	DeleteInspectResultButton->Enabled = true;
	PrintButton2->Enabled = true;
	OkBitBtn->Enabled = true;
	InspectionReportStringGrid->Enabled = true;

	navigateDefectImageForm->SetProductData(productCode, lotName);
	navigateDefectImageForm->ShowModal();
	delete navigateDefectImageForm;
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::HiddenPanelDblClick(TObject *Sender)
{
	if (UserInfo.AccessLevel == SYSTEM_HIGHEST_ACCESS_LEVEL)
	{
		if (ComplexPanel->Visible)
		{
			ComplexPanel->Visible = false;
			SimplePanel->Visible = true;
			UnInsInfoPanel->Visible = false;
		}
		else
		{
      ComplexPanel->Visible = true;
			SimplePanel->Visible = false;
			UnInsInfoPanel->Visible = true;
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::EditInspectResultButtonClick(
	TObject *Sender)
{
	int listIndex = InspectionReportStringGrid->Row - 1;
	if (listIndex < 0 || listIndex >= InspectionReportList.size()) return;
	AnsiString productCode = InspectionReportList[listIndex].ProductCode;
	AnsiString lotName = InspectionReportList[listIndex].LotName;

	TInspectionResultInsertForm *inspectionResultInsertForm = new TInspectionResultInsertForm(this);


  NFA_INSPECTION_REPORT_STRUCT Report;

	AnsiString resultDir = ProgramPath.Product + "\\" + productCode + "\\Result";
	AnsiString inspectionReportFileName = resultDir + "\\" + lotName + ".dat";

	try
	{
    bool Result = Read_InspectionReportData(inspectionReportFileName,Report);
    if(Result == false)
    {
      ShowMessageFA("Report data file can't read");
      return;
    }

		inspectionResultInsertForm->SetReportEdit(lotName, Report.Data, Report.GradeData);

		if (inspectionResultInsertForm->ShowModal() == mrOk)
		{
			DeleteFile(inspectionReportFileName.c_str());
      Report.Data = inspectionResultInsertForm->TabletInspectReport;
      Report.GradeData = inspectionResultInsertForm->TabletInspectGradeData;

			AnsiString newReportFileName = resultDir + "\\" + inspectionResultInsertForm->LOTName + ".dat";

      Create_Report_Data(Report,newReportFileName);
		}
		delete inspectionResultInsertForm;
		InitInspectionReportList();
	}
	catch (...)
	{
		WritePCProgramErrorLog(this->Name, __LINE__);
		if (inspectionResultInsertForm) delete inspectionResultInsertForm;
	}

}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::DeleteInspectResultButtonClick(
	TObject *Sender)
{
	int listIndex = InspectionReportStringGrid->Row - 1;
	if (listIndex < 0 || listIndex >= InspectionReportList.size()) return;

	AnsiString productCode = InspectionReportList[listIndex].ProductCode;
	AnsiString lotName = InspectionReportList[listIndex].LotName;

	if (MessageDlgFA(INSPECTIONREPORTFORM_MSG_06, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		AnsiString resultDir = ProgramPath.Product + "\\" + productCode + "\\Result";
		AnsiString inspectionReportFileName = resultDir + "\\" + lotName + ".dat";
		DeleteFile(inspectionReportFileName.c_str());
	}
	InitInspectionReportList();
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::PrintButtonClick(TObject *Sender)
{
	NavigateDefectImageButton->Enabled = false;
	PrintButton->Enabled = false;
	InsertInspectResultButton->Enabled = false;
	EditInspectResultButton->Enabled = false;
	DeleteInspectResultButton->Enabled = false;
	PrintButton2->Enabled = false;
	OkBitBtn->Enabled = false;
	InspectionReportStringGrid->Enabled = false;

	ProgressPanel->Visible = true;

	int listIndex = InspectionReportStringGrid->Row - 1;

	WideString productCode = InspectionReportList[listIndex].ProductCode;
	WideString lotName = InspectionReportList[listIndex].LotName;

	NFA_INSPECTION_REPORT_STRUCT Report;

	AnsiString resultDir = ProgramPath.Product + "\\" + productCode + "\\Result";
	AnsiString inspectionReportFileName = resultDir + "\\" + lotName + ".dat";
	TFileStream *fileStream = NULL;

	try
	{
    bool Result = Read_InspectionReportData(inspectionReportFileName,Report);
    if(Result == false)
    {
      ShowMessageFA("Report data file can't read");
      return;
    }

    if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
    {
      TPrintInspectionResult_Ajanta_Form *printInspectResultForm = new TPrintInspectionResult_Ajanta_Form(this);
      printInspectResultForm->SetReport(Report.Data.ProductName, lotName,Report,
      (ProductData.EngraveType == ENGRAVE_TYPE_PRINT), PCProgramOption.PrintModeOption, PCProgramOption.PrintThreeDHeightOption, PCProgramOption.HIprogram);
      printInspectResultForm->ShowModal();
      delete printInspectResultForm;
    }
    else
    {
      /*wchar_t WideTemp[64]={0,};
      MultiByteToWideChar(CP_ACP,0,tabletInspectReport.ProductName,strlen(tabletInspectReport.ProductName),WideTemp,64);*/
      TPrintInspectionResultForm *printInspectResultForm = new TPrintInspectionResultForm(this);
      printInspectResultForm->SetReport(productCode, lotName,Report, (ProductData.EngraveType == ENGRAVE_TYPE_PRINT),
        PCProgramOption.PrintModeOption, PCProgramOption.PrintThreeDHeightOption, PCProgramOption.HIprogram);
      printInspectResultForm->ShowModal();
      delete printInspectResultForm;
    }

    NavigateDefectImageButton->Enabled = true;
    PrintButton->Enabled = true;
    InsertInspectResultButton->Enabled = true;
    EditInspectResultButton->Enabled = true;
    DeleteInspectResultButton->Enabled = true;
    PrintButton2->Enabled = true;
    OkBitBtn->Enabled = true;
    InspectionReportStringGrid->Enabled = true;

    ProgressPanel->Visible = false;

    LoadInspectionResultData(listIndex + 1);
	}
	catch (...)
	{
		WritePCProgramErrorLog(this->Name, __LINE__);

		if (fileStream) delete fileStream;

    NavigateDefectImageButton->Enabled = true;
    PrintButton->Enabled = true;
    InsertInspectResultButton->Enabled = true;
    EditInspectResultButton->Enabled = true;
    DeleteInspectResultButton->Enabled = true;
    PrintButton2->Enabled = true;
    OkBitBtn->Enabled = true;
    InspectionReportStringGrid->Enabled = true;

    ProgressPanel->Visible = false;

    LoadInspectionResultData(listIndex + 1);
	}
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::InspectionReportStringGridSelectCell(
	TObject *Sender, int ACol, int ARow, bool &CanSelect)
{
	LoadInspectionResultData(ARow);
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::RefreshDefectsInfo(void)
{
	const int DISPLAY_DEFECT_COUNT = 10;
	int DefectCountList[MAX_DEFECT_SERIES_COUNT + 1];
	int DefectSeriesList[MAX_DEFECT_SERIES_COUNT + 1];

	for (int defectSeriesIndex = 0; defectSeriesIndex < MAX_DEFECT_SERIES_COUNT + 1; defectSeriesIndex++)
	{
		DefectCountList[defectSeriesIndex] = DefectSeriesCount[defectSeriesIndex];
		if (defectSeriesIndex < MAX_CPB_DEFECT_SERIES_COUNT)
		{
			DefectSeriesList[defectSeriesIndex] = defectSeriesIndex;
		}
		else
		{
			DefectSeriesList[defectSeriesIndex] = defectSeriesIndex - MAX_CPB_DEFECT_SERIES_COUNT + THIN_TALBET;
		}
	}

	// sort
	for (int i = 0; i < MAX_DEFECT_SERIES_COUNT; i++)
	{
		for (int j = i; j < MAX_DEFECT_SERIES_COUNT; j++)
		{
			if (DefectCountList[i] < DefectCountList[j])
			{
				int temp = DefectCountList[i];
				DefectCountList[i] = DefectCountList[j];
				DefectCountList[j] = temp;

				temp = DefectSeriesList[i];
				DefectSeriesList[i] = DefectSeriesList[j];
				DefectSeriesList[j] = temp;
			}
		}
	}

	double defectCountList[DISPLAY_DEFECT_COUNT];
	int defectSeriesList[DISPLAY_DEFECT_COUNT];
	int defectSeriesCount = 0;
  memset(defectCountList, 0, sizeof(double) * DISPLAY_DEFECT_COUNT);
  memset(defectSeriesList, 0, sizeof(int) * DISPLAY_DEFECT_COUNT);

	for (int defectSeriesIndex = 0; defectSeriesIndex < MAX_DEFECT_SERIES_COUNT; defectSeriesIndex++)
	{
		if (DefectCountList[defectSeriesIndex] > 0)
		{
			if (defectSeriesCount < DISPLAY_DEFECT_COUNT - 1)
			{
				defectCountList[defectSeriesCount] = DefectCountList[defectSeriesIndex];
				defectSeriesList[defectSeriesCount] = DefectSeriesList[defectSeriesIndex];
				defectSeriesCount++;
			}
			else
			{
				defectCountList[DISPLAY_DEFECT_COUNT - 1] += DefectCountList[defectSeriesIndex];
			}
		}
	}

	defectCountList[defectSeriesCount] = defectCountList[DISPLAY_DEFECT_COUNT - 1];
	//	DefectChart->Series[0]->AddArray(defectCountList, defectSeriesCount + 1);

	TColor defectColorList[DISPLAY_DEFECT_COUNT] = { clLime, clRed, clYellow, clBlue, clFuchsia,
		(TColor)0x808040, (TColor)0x0080FF, clOlive, (TColor)0xFFFF80, clPurple };

	DefectChart->Series[0]->Clear();
	for (int defectSeriesIndex = 0; defectSeriesIndex < defectSeriesCount + 1; defectSeriesIndex++)
	{
		if (defectCountList[defectSeriesIndex] > 0)
		{
			DefectChart->Series[0]->Add(defectCountList[defectSeriesIndex], IntToStr(defectSeriesIndex), defectColorList[defectSeriesIndex]);
		}
	}

	for (int defectSeriesIndex = 0; defectSeriesIndex < DISPLAY_DEFECT_COUNT; defectSeriesIndex++)
	{
		TTntShape *defectSeriesShape = (TTntShape *)FindComponent("DefectSeriesShape" + IntToStr(defectSeriesIndex + 1));
		TTntLabel *defectNameLabel = (TTntLabel *)FindComponent("DefectNameLabel" + IntToStr(defectSeriesIndex + 1));
		TTntLabel *defectCountLabel = (TTntLabel *)FindComponent("DefectCountLabel" + IntToStr(defectSeriesIndex + 1));
		if (defectCountList[defectSeriesIndex] > 0 && defectSeriesIndex <= defectSeriesCount)
		{
			if (defectSeriesShape)
			{
				defectSeriesShape->Brush->Color = defectColorList[defectSeriesIndex];
				defectSeriesShape->Visible = true;
			}
			if (defectNameLabel)
			{
				if (defectSeriesIndex == defectSeriesCount)
				{
					defectNameLabel->Caption = INSPECTIONREPORTFORM_LABEL_CAPTION_05;
				}
				else
				{
					defectNameLabel->Caption = GetDefectSeriesStr(defectSeriesList[defectSeriesIndex]);
				}
				defectNameLabel->Visible = true;
			}
			if (defectCountLabel)
			{
				defectCountLabel->Caption = FloatToStr(defectCountList[defectSeriesIndex]);
				defectCountLabel->Visible = true;
			}
		}
		else
		{
			if (defectSeriesShape)
			{
				defectSeriesShape->Brush->Color = defectColorList[defectSeriesIndex];
				defectSeriesShape->Visible = false;
			}
			if (defectNameLabel)
			{
				defectNameLabel->Caption = GetDefectSeriesStr(defectSeriesList[defectSeriesIndex]);
				defectNameLabel->Visible = false;
			}
			if (defectCountLabel)
			{
				defectCountLabel->Caption = FloatToStr(defectCountList[defectSeriesIndex]);
				defectCountLabel->Visible = false;
			}
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::FormDestroy(TObject *Sender)
{
	if (ThroughputChartList) delete[] ThroughputChartList;
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::RefreshThroughputChart(void)
{
	ThroughputChart->Series[0]->Clear();
	ThroughputChart->Series[0]->AddArray(ThroughputChartList, ThroughputChartCount);
	if (ThroughputChartCount >= 100)
	{
		ThroughputChart->BottomAxis->SetMinMax(ThroughputChartCount - 99, ThroughputChartCount + 1);
	}
	ThroughputChart->Refresh();
	if (ThroughputChartCount + 1 >= ThroughputChartListSize)
	{
		double *tempArray = new double[ThroughputChartListSize];
		memcpy(tempArray, ThroughputChartList, ThroughputChartListSize);
		delete[] ThroughputChartList;
		ThroughputChartList = new double[ThroughputChartListSize * 2];
		memcpy(ThroughputChartList, tempArray, ThroughputChartListSize);
		delete[] tempArray;
		ThroughputChartListSize *= 2;
	}
	//	ThroughputChart->BottomAxis->AxisValuesFormat
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::ThroughputChartMouseDown(
	TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
	int Y)
{
	ThroughputChartDownX = X;
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::ThroughputChartMouseMove(
	TObject *Sender, TShiftState Shift, int X, int Y)
{
	if (Shift.Contains(ssLeft))
	{
		int ScrollValue = (ThroughputChartDownX - X);
		if (ThroughputChart->BottomAxis->Minimum + ScrollValue < 0)
		{
			ScrollValue = -ThroughputChart->BottomAxis->Minimum;
		}
		if (ThroughputChart->BottomAxis->Maximum + ScrollValue > max(100, ThroughputChartCount + 1))
		{
			ScrollValue = max(100, ThroughputChartCount + 1) - ThroughputChart->BottomAxis->Maximum;
		}

		ThroughputChart->BottomAxis->SetMinMax(ThroughputChart->BottomAxis->Minimum + ScrollValue,
			ThroughputChart->BottomAxis->Maximum + ScrollValue);
		ThroughputChartDownX = X;
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::setDefectSeriesCount(AnsiString productCode, AnsiString lotName)
{
	memset(DefectSeriesCount, 0, (MAX_DEFECT_SERIES_COUNT + 1) * sizeof(int));

	TDefectInfoForm *SubDefectInfoForm;
	SubDefectInfoForm = new TDefectInfoForm(this);
	SubDefectInfoForm->InitDefectInfo(productCode, lotName);

	memcpy(DefectSeriesCount, SubDefectInfoForm->DefectSeriesCount, sizeof(int) * (MAX_DEFECT_SERIES_COUNT + 1));

	delete SubDefectInfoForm;
}

//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::BatchEndBtnClick(TObject *Sender)
{
	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
	{
		int listIndex = InspectionReportStringGrid->Row - 1;
		if (listIndex < 0 || listIndex >= InspectionReportList.size()) return;
		AnsiString productCode = InspectionReportList[listIndex].ProductCode;
		AnsiString lotName = InspectionReportList[listIndex].LotName;

    NFA_INSPECTION_REPORT_STRUCT Report;
		AnsiString resultDir = ProgramPath.Product + "\\" + productCode + "\\Result";
		AnsiString inspectionReportFileName = resultDir + "\\" + lotName + ".dat";

    bool Result = Read_InspectionReportData(inspectionReportFileName,Report);
    if(Result == false)
    {
      ShowMessageFA("Report data file can't read");
      TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\UserSetting.ini");
      iniFile->WriteInteger("Quick Start", "Batch End", 1);
      delete iniFile;
      return;
    }

    Report.SubData.BatchEndFlag[0] = 1;

		DeleteFile(inspectionReportFileName.c_str());

    AnsiString EndOperName = UserInfo.Name;
    strncpy(Report.SubData.EndOperatorName, EndOperName.c_str(), 32);
    Report.Data.InspectionEndTime =Now().Val;

		AnsiString newReportFileName = resultDir + "\\" + lotName + ".dat";

		Create_Report_Data(Report,newReportFileName);

    TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\UserSetting.ini");
    iniFile->WriteInteger("Quick Start", "Batch End", 1);
    delete iniFile;

    AddCSVActionLog(ECSV_ACTION_INSPECTION_BATCH_END, UserInfo.Name, Report.Data.ProductName, lotName.c_str(), lotName.Length() + 1);
	}


	InitInspectionReportList();

	BatchStatusLabel->Caption = "Batch Status : End";
	BatchEndBtn->Visible = false;
  PrintButton2->Visible = true;
}
//---------------------------------------------------------------------------
void __fastcall TInspectionReportForm::Ajanta_BatchStatusControl()
{
	// Batch Check
	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
	{
		BatchStatusLabel->Visible = true;
		if (InspectionReportStringGrid->RowCount > 1)
		{
			int listIndex = InspectionReportStringGrid->Row - 1;
			if (listIndex < 0 || listIndex >= InspectionReportList.size()) return;

      if(InspectionReportList[listIndex].ProductCode == NULL || InspectionReportList[listIndex].LotName == NULL) return;

			AnsiString productCode = InspectionReportList[listIndex].ProductCode;
			AnsiString lotName = InspectionReportList[listIndex].LotName;

			AnsiString resultDir = ProgramPath.Product + "\\" + productCode + "\\Result";
			AnsiString inspectionReportFileName = resultDir + "\\" + lotName + ".dat";

      NFA_INSPECTION_REPORT_STRUCT Report;
      Read_InspectionReportData(inspectionReportFileName,Report);

			if (Report.SubData.BatchEndFlag == NULL || Report.SubData.BatchEndFlag[0] == 0)
			{
				BatchStatusLabel->Caption = "Batch Status : Live";
				BatchEndBtn->Visible = true;
				BatchEndBtn->Enabled = true;
        PrintButton2->Visible = false;

			}
			else
			{
				BatchStatusLabel->Caption = "Batch Status : End";
				BatchEndBtn->Visible = false;
        PrintButton2->Visible = true;
			}
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::InspectionReportStringGridClick(
	TObject *Sender)
{
	Ajanta_BatchStatusControl();
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::BrowseStartHourEditClick(
	TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;
	unsigned short year, month, day, Starthour, Startmin, Endhour, Endmin;
	int time;
	TDateTime start, end;
	double diff;

	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		if (theEdit->Tag == 0)
		{
			theEdit->Text = KeyboardForm->Text;
			return;
		}

		time = StrToInt(KeyboardForm->Text);
		switch (theEdit->Tag)
		{
		case 1:
			if (time > 23)
			{
				ShowMessageFA("Wrong start hour");
				return;
			}
			Starthour = time;
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 2:
			if (time > 59)
			{
				ShowMessageFA("Wrong start minute");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = time;
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 3:
			if (time > 23)
			{
				ShowMessageFA("Wrong end hour");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = time;
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 4:
			if (time > 59)
			{
				ShowMessageFA("Wrong end minute");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = time;
			break;
		}

		BrowseStartTime.DecodeDate(&year, &month, &day);
		start = TDateTime(year, month, day) + TDateTime(Starthour, Startmin, 0, 0);

		BrowseEndTime.DecodeDate(&year, &month, &day);
		end = TDateTime(year, month, day) + TDateTime(Endhour, Endmin, 0, 0);

		diff = end - start;
		if (diff <= 0)
		{
			ShowMessageFA("Wrong time setting");
			return;
		}

		theEdit->Text = KeyboardForm->Text;
	}

}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::BrowseStartHourEditChange(
	TObject *Sender)
{
	double diff;
	int nStartHour, nStartMin, nEndHour, nEndMin;
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);

	BrowseStartTimeLabel->Caption = StartDateTime.TimeString();
	BrowseEndTimeLabel->Caption = EndDateTime.TimeString();
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::ProductNameEditClick(
	TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;

	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::BrowseStartDateButtonClick(
	TObject *Sender)
{
	TCalendarDialogForm *calendarDialogForm = new TCalendarDialogForm(this);
	if (mrOk == calendarDialogForm->ShowModal())
	{
		if (!CheckDateTime(calendarDialogForm->MonthCalendar->Date, 0))
		{
			ShowMessageFA("Wrong time setting");
			return;
		}
		BrowseStartTime = calendarDialogForm->MonthCalendar->Date;
	}
	delete calendarDialogForm;
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();

	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::BrowseEndDataButtonClick(
	TObject *Sender)
{
	TCalendarDialogForm *calendarDialogForm = new TCalendarDialogForm(this);
	if (mrOk == calendarDialogForm->ShowModal())
	{
		if (!CheckDateTime(0, calendarDialogForm->MonthCalendar->Date))
		{
			ShowMessageFA("Wrong time setting");
			return;
		}
		BrowseEndTime = calendarDialogForm->MonthCalendar->Date;
	}
	delete calendarDialogForm;
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();

	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------
bool __fastcall TInspectionReportForm::CheckDateTime(TDateTime StartDate, TDateTime EndDate)
{
	double diff;
	TDateTime start, end;
	unsigned short year, month, day;
	int time;

	time = StrToInt(BrowseStartHourEdit->Text);
	if (time > 23)
	{
		ShowMessageFA("Wrong start hour");
		return false;
	}

	time = StrToInt(BrowseStartMinEdit->Text);
	if (time > 59)
	{
		ShowMessageFA("Wrong start minute");
		return false;
	}

	time = StrToInt(BrowseEndHourEdit->Text);
	if (time > 23)
	{
		ShowMessageFA("Wrong end hour");
		return false;
	}

	time = StrToInt(BrowseEndMinEdit->Text);
	if (time > 59)
	{
		ShowMessageFA("Wrong end minute");
		return false;
	}

	if (!StartDate.Val)
		StartDate = BrowseStartTime;
	StartDate.DecodeDate(&year, &month, &day);
	start = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	if (!EndDate.Val)
		EndDate = BrowseEndTime;
	EndDate.DecodeDate(&year, &month, &day);
	end = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);

	diff = end - start;
	if (diff <= 0)
	{
		ShowMessageFA("Wrong time setting");
		return false;
	}

	return true;
}
//-------------------------------------------------------------------------
void __fastcall TInspectionReportForm::PeriodButton1Click(TObject *Sender)
{
	BrowseStartTime.Val = Now().Val - 7;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::PeriodButton2Click(TObject *Sender)
{
	BrowseStartTime.Val = Now().Val - 30;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::PeriodButton3Click(TObject *Sender)
{
	BrowseStartTime.Val = Now().Val - 90;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::PeriodButton4Click(TObject *Sender)
{
	BrowseStartTime.Val = 0;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = "~";
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0).TimeString();
	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::ViewBtnClick(TObject *Sender)
{
	InitInspectionReportList(true);
}
//---------------------------------------------------------------------------
bool __fastcall TInspectionReportForm::AvailableLotNumCheck(AnsiString sr_Name)
{
	AnsiString Name = ProductNameEdit->Text;
	if (Name != "")
	{
		int n_Length = sr_Name.Length();
		int p_Length = Name.Length();

		if (p_Length > n_Length)
		{
			return false;
		}
		else
		{
			int p_nameIndex = 0;
			for (int i = 0; i < n_Length; ++i)
			{
				if (p_nameIndex > p_Length) p_nameIndex -= 1;
				if (p_nameIndex > 0 && sr_Name.LowerCase().c_str()[i] != Name.LowerCase().c_str()[p_nameIndex])
				{
					if (p_nameIndex == p_Length)
						break;
					else
					{
						p_nameIndex = 0;
						continue;
					}
				}

				if (sr_Name.LowerCase().c_str()[i] == Name.LowerCase().c_str()[p_nameIndex])
					p_nameIndex++;
			}

			if (p_nameIndex == p_Length)
			{
				return true;
			}
			else
				return false;
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TInspectionReportForm::LoadInspectionResultData(int ARow)
{
  try
  {
    beforeRowIndex = ARow - 1;
    if (UnInsInfoPanel->Visible)
    {
      if (ARow > 0 && ARow <= InspectionReportList.size())
      {
        UnPrintTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].UnPrintTabletCount);
        EngraveMisMatchingCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].PrintMisMatchCount);
        SPBPNCCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].SPBProcessingNCTabletCount);
        SPBTOCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].SPBTOTabletCount);
        ClosedTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].ClosedTabletCount);
        DisappearedTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].DisappearedTabletCount);
        InsertedTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].InsertedTabletCount);
		
        ClosedTabletUninsCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].ClosedTabletUninsCount);
        ClosedTabletDefectCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].ClosedTabletDefectCount);
        WrongNumberTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].WrongNumberTabletCount);
        NumberUndefTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].NumberUndefTabletCount);
        CaptureNotReadyTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].CaptureNotReadyTabletCount);
        BufferFullTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].BufferFullTabletCount);
        CaptureTimeoutTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].CaptureTimoutTabletCount);
        ProcessingTimeoutTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].ProcessingTimoutTabletCount);
        CPBFullTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].CPBFullTabletCount);
        ProcErrorTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].ProcessingErrorTabletCount);
        UnInsTabletPositionCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].UnInsTabletPositionCount);
        UnInsBrightnessDropCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].UnInsBrightnessDropCount);
        UnInsBrightnessChaseCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].UnInsBrightnessChaseCount);
        TotalUnInsCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].UnInsCount);

        MissFeedingTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].Sensor1MisFeedingTabletCount + InspectionReportList[ARow - 1].Sensor2MisFeedingTabletCount);
        MultiTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].Sensor1MultiTabletCount + InspectionReportList[ARow - 1].Sensor2MultiTabletCount);
        NozzErrorDefectTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].NozzErrorDefectTabletCount);
        NozzErrorUnInsTabletCountLabel->Caption = IntToStr(InspectionReportList[ARow - 1].NozzErrorUnInsTabletCount);
		

        // read throughput list

        AnsiString resultDir = ProgramPath.Product + "\\" + InspectionReportList[ARow - 1].ProductCode + "\\Result";
        AnsiString resultFileName = resultDir + "\\" + InspectionReportList[ARow - 1].LotName + ".dat";

        NFA_INSPECTION_REPORT_STRUCT Report;
        Read_InspectionReportData(resultFileName,Report);

        TFileStream *fileStream = NULL;

        if (FileExists(resultFileName))//fileStream)
        {
          TInspectionListUnit inspectionListUnit;

          memset(DefectSeriesCount, 0, (MAX_DEFECT_SERIES_COUNT + 1) * sizeof(int));
          memcpy(DefectSeriesCount,Report.DefectSeriesCount.DefectSeriesCount,(MAX_DEFECT_SERIES_COUNT + 1) * sizeof(int));

          RefreshDefectsInfo();
        }
        else
        {
          DefectChart->Series[0]->Clear();
        }

        try
        {
          fileStream = NULL;
          AnsiString throughputFileName = resultDir + "\\" + InspectionReportList[ARow - 1].LotName + ".trp";
          if (!FileExists(throughputFileName)) throw Exception("Throughput File Does Not Exist");
          fileStream = new TFileStream(throughputFileName, fmOpenRead);
          unsigned int thorughputFileVerion;
          fileStream->Read(&thorughputFileVerion, sizeof(unsigned int));
          if (thorughputFileVerion != THROUGHPUT_FILE_VERSION) throw Exception("Throughput File Version Is Not Matched");

          fileStream->Read(&ThroughputChartCount, sizeof(int));
          if (ThroughputChartCount <= 0) throw Exception("Wrong Throughput Data Count");
          if (ThroughputChartListSize == 0) ThroughputChartListSize = THROUGHPUT_CHART_DEFAULT_SIZE;
          while (ThroughputChartListSize < ThroughputChartCount)
          {
            ThroughputChartListSize *= 2;
          }
          if (ThroughputChartList) delete[] ThroughputChartList;
          ThroughputChartList = new double[ThroughputChartListSize];
          memset(ThroughputChartList, 0, sizeof(double) * ThroughputChartListSize);
          fileStream->Read(ThroughputChartList, ThroughputChartCount * sizeof(double));
          delete fileStream;
          RefreshThroughputChart();
        }
        catch (...)
        {
          if (fileStream) delete fileStream;

          if (ThroughputChartList) delete[] ThroughputChartList;
          ThroughputChartList = new double[THROUGHPUT_CHART_DEFAULT_SIZE];
          ThroughputChartListSize = THROUGHPUT_CHART_DEFAULT_SIZE;
          ThroughputChartCount = 0;
          ThroughputChart->Series[0]->Clear();

          NavigateDefectImageButton->Enabled = true;
          PrintButton->Enabled = true;
          InsertInspectResultButton->Enabled = true;
          EditInspectResultButton->Enabled = true;
          DeleteInspectResultButton->Enabled = true;
          PrintButton2->Enabled = true;
          OkBitBtn->Enabled = true;
          InspectionReportStringGrid->Enabled = true;

          ProgressPanel->Visible = false;

        }
      }
    }
  }
  catch(...)
  {
  }
}
//-----------------------------------------------------------------
void __fastcall TInspectionReportForm::OnUserChange(void)
{
  OkBitBtn->Click();
}
void __fastcall TInspectionReportForm::TntFormActivate(TObject *Sender)
{
  SetScreenPosition(this);
}
//---------------------------------------------------------------------------

