unit frmMainUnit;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls,
  Vcl.ExtCtrls,
  Vcl.Mask, RzEdit, System.Net.URLClient, System.Net.HttpClient,
  System.Net.HttpClientComponent;

type
  hTask = class(TThread)
  protected
    RunTime: string; // 执行时间
    ApiURL, ID, PWD: string; // 接口地址及验证信息
    procedure Execute; override;
  end;

  TfrmMain = class(TForm)
    Panel1: TPanel;
    Memo1: TMemo;
    StatusBar1: TStatusBar;
    LabeledEdit1: TLabeledEdit;
    LabeledEdit2: TLabeledEdit;
    LabeledEdit3: TLabeledEdit;
    RzDateTimeEdit1: TRzDateTimeEdit;
    CheckBox1: TCheckBox;
    Label1: TLabel;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure Memo1Change(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
    vStartTime: TDateTime; // 程序启动时间
    vTask: hTask; // 任务线程
    procedure wLog(vContent: string);
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}


uses rtcLog, System.DateUtils;

procedure hTask.Execute;
var
  i: Integer;
  vHttp: TNetHTTPClient;
  vS: TStringStream;
  vList: TStrings;
begin
  FreeOnTerminate := False;
  while not Terminated do // 被执行终止时退出循环
  begin
    for i := 1 to 10 do
      if not Terminated then
        Sleep(10) // 减轻CPU压力，延时
      else
        exit;
    if (FormatDateTime('hh:mm:ss', Time) = RunTime)
      and (Trim(ID) <> '') then
    begin
      frmMain.wLog('开始执行任务...');
      vHttp := TNetHTTPClient.Create(nil);
      vS := TStringStream.Create('', TEncoding.GetEncoding(65001));
      vList := TStringList.Create;
      try
        with vHttp do
        begin
          vS.Clear;
          ConnectionTimeout := 2000; // 2秒
          ResponseTimeout := 10000; // 10秒
          AcceptCharSet := 'utf-8';
          AcceptEncoding := '65001';
          AcceptLanguage := 'zh-CN';
          ContentType := 'text/html';
          UserAgent := 'Restart/1.0';
          vList.Clear;
          if (Trim(PWD) <> '')
            and (ID <> PWD) then
          begin
            vList.Values['id'] := ID;
            vList.Values['pwd'] := PWD;
          end
          else
            vList.Values['rtt'] := ID;
          try
            Post(ApiURL, vList, vS);
            if vS.DataString = 'Success' then
              frmMain.wLog('任务执行成功。')
            else
              frmMain.wLog('任务执行失败，提示：' + vS.DataString);
          except
            on E: Exception do
              frmMain.wLog('任务执行失败，提示：' + E.Message);
          end;
        end;
      finally
        vS.Free;
        vHttp.Free;
        vList.Free;
        frmMain.wLog('结束执行任务。');
      end;
    end;
  end;
end;

procedure TfrmMain.CheckBox1Click(Sender: TObject);
begin
  LabeledEdit1.Enabled := not TCheckBox(Sender).Checked;
  LabeledEdit2.Enabled := not TCheckBox(Sender).Checked;
  LabeledEdit3.Enabled := not TCheckBox(Sender).Checked;
  RzDateTimeEdit1.Enabled := not TCheckBox(Sender).Checked;
  Label1.Enabled := not TCheckBox(Sender).Checked;
  if TCheckBox(Sender).Checked then
  begin
    wLog('进入任务模式...');
    if RzDateTimeEdit1.Time = null then
      RzDateTimeEdit1.Time := StrToTime('00:00:00');
    vTask.RunTime := FormatDateTime('hh:mm:ss', RzDateTimeEdit1.Time);
    vTask.ApiURL := LabeledEdit1.Text;
    vTask.ID := LabeledEdit2.Text;
    vTask.PWD := LabeledEdit3.Text;
    vTask.Suspended := False;
  end
  else
  begin
    if not vTask.Suspended then
      vTask.Suspended := True;
    wLog('退出任务模式...');
  end;
end;

procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  wLog('开始退出软件...');
  if CheckBox1.Checked then
    CheckBox1.Checked := False;
  wLog('卸载日志模块中...');
  StopLog;
end;

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  // 初始化日期格式
  FormatSettings.DateSeparator := '-';
  FormatSettings.TimeSeparator := ':';
  FormatSettings.ShortDateFormat := 'YYYY-MM-DD';
  FormatSettings.ShortTimeFormat := 'HH:mm:ss';
  FormatSettings.LongDateFormat := 'YYYY-MM-DD';
  FormatSettings.LongTimeFormat := 'HH:mm:ss';
  // 改变hint弹出时间
  application.HintPause := 0;
  application.HintHidePause := 5000;
  vStartTime := Now;
  Memo1.Lines.Clear;
  StartLog;
  wLog('日志模块已加载...');
  RzDateTimeEdit1.Time := StrToTime('00:00:00');
  LabeledEdit1.Text := 'http://localhost/restart';
  vTask := hTask.Create(True);
  vTask.RunTime := FormatDateTime('hh:mm:ss', RzDateTimeEdit1.Time);
  wLog('默认参数已配置...');
  wLog('请设置接口地址和重启解密，并进行勾选，以执行任务。');
end;

procedure TfrmMain.Memo1Change(Sender: TObject);
begin
  if Memo1.Lines.Count > 255 then
    Memo1.Lines.Delete(0);
  Memo1.SelStart := Length(Memo1.Text); // 光标指向最后
  Memo1.SelLength := Length(Memo1.Text); // 边框滚动条到底
end;

procedure TfrmMain.Timer1Timer(Sender: TObject);
var
  s: string;
begin
  s := ' 连续工作了：';
  if Trunc(Now) - Trunc(vStartTime) > 0 then
    s := s + FormatFloat('#,##0天',
      Trunc(Now) - Trunc(vStartTime));
  if HoursBetween(vStartTime, Now) > 0 then
    s := s + FormatFloat('#,##0小时', HoursBetween(vStartTime,
      Now)
      mod 24);
  if MinutesBetween(vStartTime, Now) > 0 then
    s := s + FormatFloat('#,##0分',
      MinutesBetween(vStartTime, Now)
      mod 60);
  if SecondsBetween(vStartTime, Now) > 0 then
    s := s + FormatFloat('#,##0秒',
      SecondsBetween(vStartTime, Now)
      mod 60);
  if s = ' 连续工作了：' then
    s := ' 连续工作了：0秒';
  StatusBar1.Panels[1].Text := FormatDateTime('[yyyy-MM-DD HH:mm:ss]', Now) + s;
end;

procedure TfrmMain.wLog(vContent: string);
begin
  if Trim(vContent) = '' then
    exit;
  Memo1.Lines.Add(FormatDateTime('yyyy-MM-DD HH:mm:ss.zzz ', Now) + vContent);
  xlog(vContent, '任务日志');
end;

end.
