抓取服务器

 

线程通用Execute方法;

procedure TBDSFResultThd.Execute;
begin
  while (iNum < 4 ) and (not Terminated) do   //线程.Terminate时确保可以结束线程。
  begin
    if not Pause then                             //如果没有收到暂停信息
    begin
      if bPauseStatus <> Pause then
      begin
        MainForm.LogInfo('抓取线程***北单胜负赛果***已启动', True);
        bPauseStatus := Pause;
      end;
      MainForm.IsBDSFResultCatching := True;
      if CatchMatch then                                   //抓取成功
      begin
        MainForm.LogInfo('北单胜负赛果抓取成功,等待下一次抓取', True);
        while not Pause do
        begin
          Sleep(500);
          if SecondsBetween(Now, dtTemp) >iBdsfInv then Break;  
        end;
      end
      else begin
        MainForm.LogInfo('抓取北单胜负赛果失败,等待重试', True);
        Sleep(RETRY_INV);
      end;
    end
    else begin                                 //如果暂停抓取
      if bPauseStatus <> Pause then
      begin
        MainForm.LogInfo('抓取线程***北单胜负赛果***已暂停', True);
        bPauseStatus := Pause;
      end;
      MainForm.IsBDSFResultCatching := False;
      Sleep(500);
    end;
  end;
end;

  

  1 unit ThdBDSFResult;
  2 
  3 interface
  4 
  5 uses
  6   Classes,MyAccess,SysUtils,DateUtils, IdHTTP,StrUtils,IniFiles;
  7 
  8 type
  9   TBDSFResultThd = class(TThread)
 10   private
 11     mcMain: TMyConnection;
 12     mqMain: TMyQuery;
 13     iBDSFType : Integer;
 14     Pause:Boolean;
 15     iBdsfInv : integer;
 16     hsl_Result : Thashedstringlist;
 17     //
 18     function CatchMatch: Boolean;
 19     function GetBDSFResult : Boolean ;
 20     //
 21     function SaveData: Boolean;
 22     function GetMatchId(MacheNo:Integer;Term :string; var MatchId :string):Boolean;
 23   public
 24     procedure Execute; override;
 25     constructor Create(iType:integer;Finterval:integer);
 26     destructor Destroy; override;
 27     procedure SetPause(const aIsPause: Boolean);
 28   end ;
 29 
 30 implementation
 31 uses
 32   PubDefine,FrmMain;
 33 var
 34   DBSFResultList : array of TBDResult;
 35 
 36 { TBDSFResultThd }
 37 
 38 constructor TBDSFResultThd.Create(iType: integer;Finterval:integer);
 39 begin
 40   inherited Create(True);
 41   iBDSFType := iType;
 42   iBdsfInv := Finterval;
 43   //
 44   hsl_Result := Thashedstringlist.Create;
 45 
 46   FreeOnTerminate := True;
 47   mcMain := TMyConnection.Create(nil);
 48   mcMain.Server := ConnectionConfig.Server;
 49   mcMain.Username := ConnectionConfig.Username;
 50   mcMain.Password := ConnectionConfig.Password;
 51   mcMain.Port := ConnectionConfig.Port;
 52   mcMain.Database := ConnectionConfig.Database;
 53   mcMain.Options.UseUnicode := True;
 54   mcMain.LoginPrompt := False;
 55   try
 56      mcMain.Connect;
 57   except on ex:Exception do
 58     begin
 59       MainForm.LogInfo('初始化数据库连接超时:' + ex.Message, True);
 60       Exit;
 61     end;
 62   end;
 63   mqMain := TMyQuery.Create(nil);
 64   mqMain.Connection := mcMain;
 65   if iBDSFType = 0 then
 66     SetPause(True)
 67   else
 68     SetPause(false);
 69   Self.Resume;
 70 end;
 71 
 72 procedure TBDSFResultThd.Execute;
 73 var
 74   bPauseStatus: Boolean;
 75   dtTemp: TDateTime;
 76   iNum : Integer;
 77 begin
 78   bPauseStatus := Pause;
 79   iNum := 0;
 80   while (iNum < 4 ) and (not Terminated) do   //线程.Terminate时确保可以结束线程。
 81   begin
 82     if iBDSFType = 0 then
 83     begin
 84       iNum := 1;
 85       Sleep(iBdsfInv);
 86     end
 87     else
 88       iNum := iNum + 1;
 89     //
 90     BDSFResultRunTime := Now;
 91     if not Pause then                             //如果没有收到暂停信息
 92     begin
 93       if bPauseStatus <> Pause then
 94       begin
 95         MainForm.LogInfo('抓取线程***北单胜负赛果***已启动', True);
 96         bPauseStatus := Pause;
 97       end;
 98       MainForm.IsBDSFResultCatching := True;
 99       if CatchMatch then                                   //抓取成功
100       begin
101         MainForm.LogInfo('北单胜负赛果抓取成功,等待下一次抓取', True);
102         dtTemp := Now;
103         while not Pause do
104         begin
105           Sleep(500);
106           if SecondsBetween(Now, dtTemp) >iBdsfInv then Break;  
107         end;
108       end
109       else begin
110         MainForm.LogInfo('抓取北单胜负赛果失败,等待重试', True);
111         Sleep(RETRY_INV);
112       end;
113     end
114     else begin                                 //如果暂停抓取
115       if bPauseStatus <> Pause then
116       begin
117         MainForm.LogInfo('抓取线程***北单胜负赛果***已暂停', True);
118         bPauseStatus := Pause;
119       end;
120       MainForm.IsBDSFResultCatching := False;
121       Sleep(500);
122     end;
123   end;
124 end;
125 
126 function TBDSFResultThd.CatchMatch: Boolean;
127 begin
128   Result := False;
129   MainForm.LogInfo('开始抓取北单胜负赛果', True);
130   SetLength(DBSFResultList, 0);
131   if not GetBDSFResult then Exit;
132   Result := SaveData;  //  暂时屏蔽
133 end;
134 
135 function TBDSFResultThd.GetBDSFResult: Boolean;
136 var
137   idServer: TIdHTTP;
138   sResponse,sYear,sMonth,sDrawNo :string;
139   i,Pos1, Pos2: Integer;
140   Term,MatchResult,StatusStr,Urltmp : string ;
141   TotalMatchCount,MatchNo : Integer ;
142   SP: Double ;
143 begin
144   Result := False ;
145   idServer := TIdHTTP.Create(nil);
146   idServer.ConnectTimeout:=15000;
147   idServer.ReadTimeout:=15000;
148   try
149     try
150       try
151         //http://www.bjlot.com/ssm/sf/report.shtml从里面分析可知取当前年信息的地址 /data/270/control/drawyearlist.js
152         //取当前年[为了得到取当前月信息的地址]  //jsonString={"drawyears":[{"year":"2014"}]}
153         sResponse := UTF8Decode(idServer.Get(MainForm.BDSFResultAddress+'/data/270/control/drawyearlist.js'));
154         pos1 := posex('year":"',sResponse,1);
155         pos2 := posex('"}',sResponse,1);
156         sYear :=  copy(sResponse,pos1+length('year":"'),pos2-pos1-length('year":"')) ;
157         //取当前月[为了得到取当前彩期信息的地址] // jsonString={"monthlist":[{"month":"07"},{"month":"06"},...
158         sResponse := UTF8Decode(idServer.Get(MainForm.BDSFResultAddress+'/data/270/control/'+sYear+'.js'));
159         pos1 := posex('month":"',sResponse,1);
160         pos2 := posex('"}',sResponse,1);
161         sMonth :=  copy(sResponse,pos1+length('month":"'),pos2-pos1-length('month":"')) ;
162 
163         //取当前彩期 // jsonString={"drawnolist":[{"drawno":"40704"},{"drawno":"40703"},....
164         sResponse := UTF8Decode(idServer.Get(MainForm.BDSFResultAddress+'/data/270/control/drawnolist_'+sYear+sMonth+'.js'));
165         pos1 := posex('drawno":"',sResponse,1);
166         pos2 := posex('"}',sResponse,1);
167         sDrawNo :=  copy(sResponse,pos1+length('drawno":"'),pos2-pos1-length('drawno":"')) ;
168 
169         // 取当前彩期赛果数据
170         Urltmp:=MainForm.BDSFResultAddress+'/data/270/draw/'+sYear+'/'+sDrawNo+'.js';
171         sResponse := UTF8Decode(idServer.Get(Urltmp));
172         MainForm.EdtBDSF.Text:=Urltmp;
173       except on E : Exception do
174         begin
175           MainForm.LogInfo('idServer.Get获取北单胜负赛果失败'+ E.Message, True);
176           Exit;
177         end;
178       end;
179 
180       //赛果场次总数
181       Pos1 := 0;
182       TotalMatchCount:=0;
183       Pos1:= PosEx('Competitions', sResponse, Pos1+1);
184       if (Pos1 = 0)  then
185       begin
186         MainForm.LogInfo('获取北单胜负赛果时出错,找不到标识字符串Competitions ', True);
187         MainForm.LogInfo(sResponse, False);
188         Exit;
189       end;
190       while Pos1<> 0 do                            //循环算总场次
191       begin
192         Inc(TotalMatchCount);
193         Pos1:= PosEx('Competitions', sResponse, Pos1+1);
194       end;
195       //彩期[存入数据库的彩期格式]40704-->140704
196       Term := copy(sDrawNo,2,Length(sDrawNo)-1);   //0704
197       Term := FormatDateTime('Y',now) + Term ;     //140704
198 
199       if MainForm.IsSaveFile then
200       begin
201         Urltmp:='获取地址为:'+Urltmp+#13#10+'赛果彩期为'+Term+',共有'+inttostr(TotalMatchCount)+'场比赛结果。';
202         if MainForm.SaveFile(Urltmp+sResponse,'FileBDSFDate') then
203         begin
204           MainForm.LogInfo('保存北单胜负赛果页面成功', True);
205         end;
206       end;
207 
208       Pos1:=1;   //移位取信息,不用截短,这样更快捷   //以pos1为基准,pos1不断往后移
209       SetLength(DBSFResultList,TotalMatchCount);
210       for i := 0 to TotalMatchCount-1 do
211       begin
212         // 场次序号
213         pos1 := posex('matchno":"',sResponse,Pos1);
214         pos2 := posex('",',sResponse,Pos1) ;
215         MatchNo:= StrToInt(Copy(sResponse,pos1+length('matchno":"'),pos2-pos1-length('matchno":"')));//
216         // 赛果
217         pos1 := posex('result":"',sResponse,pos1);
218         pos2 := posex('",',sResponse,Pos1) ;
219         StatusStr :=Copy(sResponse,pos1+length('result":"'),pos2-pos1-length('result":"'));
220         if  StatusStr= '' then
221           MatchRESULT := '3'
222         else if StatusStr= '' then
223           MatchRESULT := '0';
224         //SP值
225         pos1 :=  posex('spvalue":"',sResponse,pos1);
226         pos2 := posex('",',sResponse,Pos1) ;
227         SP :=StrToFloat(Copy(sResponse,pos1+length('spvalue":"'),pos2-pos1-length('spvalue":"')));
228 
229         DBSFResultList[i].TERM := term ;
230         DBSFResultList[i].SCORE :='0:0';
231         DBSFResultList[i].MatchRESULT := MatchRESULT ;
232         DBSFResultList[i].SP := SP;
233         DBSFResultList[i].SingleBonus :=0;
234         DBSFResultList[i].MatchNo := MatchNo ;
235       end;
236       Result:=True;
237     except on E: Exception do
238       begin
239         MainForm.LogInfo('抓取北单胜负赛果出错!'+ E.Message, True);
240         Exit;
241       end;
242     end;
243   finally
244     idServer.Free;
245   end;
246 end;
247 
248 function TBDSFResultThd.SaveData: Boolean;
249 var
250   i,j,iBDSFResltCount, iReturnCode: Integer;
251   sSQLString: string;
252   MatchId : string ;
253   ResulCount,iNoChangeNum: Integer ;
254   iLotMacthId : Integer;
255   sMatchRet,sTmp : string;
256 begin
257   Result := False;
258   ResulCount := 0 ;
259   iNoChangeNum:=0;
260   iBDSFResltCount := Length(DBSFResultList);
261   if iBDSFResltCount<=0 then
262   begin
263     MainForm.LogInfo('准备写入北单胜负赛果的场数为 0 ', True);
264     Exit;
265   end;
266   MainForm.LogInfo('准备写入北单胜负赛果彩期为:'+DBSFResultList[0].TERM+'' + IntToStr(iBDSFResltCount) + '条数据。', True);
267   try
268     if hsl_Result.Count > 1000 then
269       hsl_Result.Clear;
270     for i := 0 to iBDSFResltCount - 1 do
271     begin
272       try
273         j := 0   ;
274         while j < 2 do
275         begin
276           if GetMatchId(DBSFResultList[i].MatchNo,DBSFResultList[i].TERM,MatchId) then
277            j :=2
278           else
279           begin
280             j:= j+ 1;
281             MainForm.LogInfo('获取北单胜负场次ID出错!第 '+IntToStr(j)+'', True);
282             Sleep(500);  //获取不到,稍后再获取,
283           end;
284         end;
285         if  trim(MatchId) = '' then
286         begin
287           MainForm.LogInfo('北单胜负对阵没有此场次   彩期:'+DBSFResultList[i].TERM +' 序号:'+ IntToStr(DBSFResultList[i].MatchNo), True);
288           continue;
289         end;
290       except on e:Exception do
291         begin
292           MainForm.LogInfo('准备北单数据时失败,原因:' + e.Message + ''+DBSFResultList[i].TERM +' '+ MatchId , True);
293           Continue;
294         end;
295       end;
296       // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
297       iLotMacthId := 35 * 10000 + StrToInt(matchid);
298       sMatchRet := IntToStr(DBSFResultList[i].MatchNo) +
299                    '^' + trim(MatchId)+
300                    '^' + Trim(DBSFResultList[i].SCORE) +
301                    '^' + Trim(DBSFResultList[i].MatchRESULT) +
302                    '^' + Trim(FloatTostr(DBSFResultList[i].SP)) +
303                    '^' + Trim(FloatTostr(DBSFResultList[i].SingleBonus));
304       // 判断hashed是否存在
305       sTmp := trim(hsl_Result.Values[IntToStr(iLotMacthId)]);
306       if sTmp = '' then
307         hsl_Result.Add(IntToStr(iLotMacthId) + '=' + sMatchRet)
308       else
309       begin
310         if sTmp = Trim(sMatchRet) then
311         begin
312           //MainForm.LogInfo('【北单胜负赛果】无变更:' + sMatchRet, True);
313           Inc(iNoChangeNum);
314           Continue;
315         end
316         else
317           hsl_Result.Values[IntToStr(iLotMacthId)] := Trim(sMatchRet);
318       end;
319       // -------------------------------------------------------------------------
320       try
321         sSQLString := 'CALL P_M_RESULT_BDSF_INS('
322              +  QuotedStr(IntToStr(35))
323              + ',' + QuotedStr(MatchId)               //  彩种35表示北单胜负过关
324              + ',' + QuotedStr(DBSFResultList[i].SCORE)
325              + ',' + QuotedStr(DBSFResultList[i].MatchRESULT)
326              + ',' + QuotedStr(FloatTostr(DBSFResultList[i].SP))
327              + ',' + QuotedStr(FloatTostr(DBSFResultList[i].SingleBonus));
328 
329              sSQLString := sSQLString +',@a); select @a;';
330         mqMain.Close;
331         mqMain.SQL.Text := sSQLString;
332         mqMain.Execute;
333         iReturnCode := mqMain.Fields.Fields[0].AsInteger;
334         mqMain.Close;
335       except on E:Exception do
336         begin
337           mqMain.Close;
338           MainForm.LogInfo('写入北单胜负彩果失败,原因:' + e.Message + ''+DBSFResultList[i].TERM +' '+ MatchId , True);
339           hsl_Result.Values[IntToStr(iLotMacthId)] :='';
340           Continue;
341         end;
342       end;
343       if iReturnCode = 1 then              //数据验证失败
344       begin
345         MainForm.LogInfo('写入北单胜负彩果失败,原因:数据验证失败'+DBSFResultList[i].TERM +' '+MatchId , True);
346         hsl_Result.Values[IntToStr(iLotMacthId)] :='';
347         Continue;
348       end else if iReturnCode = 100 then
349       begin
350         MainForm.LogInfo('写入北单胜负彩果失败,原因:未知错误'+DBSFResultList[i].TERM +' '+ MatchId , True);
351         hsl_Result.Values[IntToStr(iLotMacthId)] :='';
352        Continue;
353       end;
354       ResulCount := ResulCount +1 ;
355     end;
356     MainForm.LogInfo('已写入北单胜负赛果'+IntToStr(ResulCount)+'场;无变更'+ IntToStr(iNoChangeNum)+''+#13#10, True);
357     result := true;
358   except on E : Exception do
359     begin
360       MainForm.LogInfo('写入北单胜负过关赛果失败,原因:' + E.Message, True);
361       Exit;
362     end;
363   end;
364 end;
365 
366 function TBDSFResultThd.GetMatchId(MacheNo: Integer; Term: string; var MatchId: string): Boolean;
367 var
368   sSQLString : string ;
369 begin
370   result := false ;
371   try
372     sSQLString := ' SELECT ID FROM LOTTERY_MATCH_BDSF WHERE  TERM = '     // ''120914''
373              +  QuotedStr(Term)
374              + ' AND MATCH_NO= ' + inttostr(macheNo);
375     mqMain.Close;
376     mqMain.SQL.Text := sSQLString;
377     mqMain.Execute;
378     //
379     MatchId := mqMain.Fields.Fields[0].AsString;
380     mqMain.Close;
381     result := true;
382   except on e:Exception do
383     begin
384       MainForm.LogInfo('获取北单胜负场次ID出错! 原因:'+E.Message, True);
385       Exit;
386     end;
387   end;
388 end;
389 
390 procedure TBDSFResultThd.SetPause(const aIsPause: Boolean);
391 begin
392   Pause := aIsPause;
393 end;
394 
395 destructor TBDSFResultThd.Destroy;
396 begin
397   if Assigned(mcMain) then mcMain.Free;
398   if Assigned(mqMain) then mqMain.Free;
399   if Assigned(hsl_Result) then hsl_Result.Free;
400   inherited;
401 end;
402 end.
北单胜负赛果
unit ThdBDSFMatch;

interface

uses
  Classes,MyAccess,SysUtils,DateUtils, IdHTTP,StrUtils,IniFiles;

type
  TBDSFMatchThd = class(TThread)
  private
    mcMain: TMyConnection;
    mqMain: TMyQuery;
    iBDSFType : Integer;
    Pause:Boolean;
    iBdsfInv : integer;

    hsl_Match : Thashedstringlist;
    //
    function CatchMatch: Boolean;
    function GetBDSFMatch : Boolean ;
    //
    function SaveData: Boolean;

  public
    procedure Execute; override;
    constructor Create(iType:integer;Finterval:integer);
    destructor Destroy; override;
    procedure SetPause(const aIsPause: Boolean); 
  end ;

implementation
uses
  PubDefine,FrmMain;
var
  BDSFMatchList : array of TBDSFMatch ;


{ TBDSFMatchThd }

constructor TBDSFMatchThd.Create(iType: integer;Finterval:integer);
begin
  inherited Create(True);
  iBDSFType := iType;
  iBdsfInv := Finterval;

  hsl_Match := Thashedstringlist.Create;
  //
  FreeOnTerminate := True;
  mcMain := TMyConnection.Create(nil);
  mcMain.Server := ConnectionConfig.Server;
  mcMain.Username := ConnectionConfig.Username;
  mcMain.Password := ConnectionConfig.Password;
  mcMain.Port := ConnectionConfig.Port;
  mcMain.Database := ConnectionConfig.Database;
  mcMain.Options.UseUnicode := True;
  mcMain.LoginPrompt := False;
  try
     mcMain.Connect;
  except on ex:Exception do
    begin
      MainForm.LogInfo('初始化数据库连接超时:' + ex.Message, True);
      Exit;
    end;
  end;
  mqMain := TMyQuery.Create(nil);
  mqMain.Connection := mcMain;
  if iBDSFType = 0 then
    SetPause(True)
  else
    SetPause(false);
  Self.Resume;
end;

procedure TBDSFMatchThd.Execute;
var
  bPauseStatus: Boolean;
  dtTemp: TDateTime;
  iNum : Integer;
begin
  bPauseStatus := Pause;
  iNum := 0;
  while (iNum < 4 ) and (not Terminated) do   
  begin
    if iBDSFType = 0 then
    begin
      iNum := 1;
      Sleep(iBdsfInv);
    end
    else
      iNum := iNum + 1;
    //
    BDSFMatchRunTime := Now;
    if not Pause then                             //如果没有收到暂停信息
    begin
      if bPauseStatus <> Pause then
      begin
        MainForm.LogInfo('抓取线程***北单胜负过关对阵***已启动', True);
        bPauseStatus := Pause;
      end;
      MainForm.IsBDSFMatchCatching := True;
      if CatchMatch then                                   //抓取成功
      begin
        MainForm.LogInfo('北单胜负过关对阵抓取成功,等待下一次抓取', True);
        dtTemp := Now;
        while not Pause do
        begin
          Sleep(500);
          if SecondsBetween(Now, dtTemp) > iBdsfInv then Break;
        end;
      end
      else begin
        MainForm.LogInfo('抓取北单胜负过关对阵失败,等待重试', True);
        Sleep(RETRY_INV);
      end;
    end
    else begin                                 //如果暂停抓取
      if bPauseStatus <> Pause then
      begin
        MainForm.LogInfo('抓取线程***北单胜负过关对阵***已暂停', True);
        bPauseStatus := Pause;
      end;
      MainForm.IsBDSFMatchCatching := False;
      Sleep(500);
    end;
  end;
end;

function TBDSFMatchThd.CatchMatch: Boolean;
begin
  Result := False;
  MainForm.LogInfo('开始抓取北单胜负过关对阵', True);
  SetLength(BDSFMatchList, 0);
  if not GetBDSFMatch then
  begin
    Exit;
  end;
  Result := SaveData;
end;

function TBDSFMatchThd.GetBDSFMatch: Boolean;
var
    idServer: TIdHTTP;
    sResponse :string;
    i,Pos1, Pos2: Integer;
    Term ,RaceName,HomeTeam,VisitingTeam,StatusStr: string ;
    MatchNo : Integer ;
    Handicap :Double;
    StartDate : TDateTime;
    SellMatchCount , TotalMatchCount, StopMatchCount ,status: Integer;
begin
  Result := False ;
  idServer := TIdHTTP.Create(nil);
  idServer.ConnectTimeout:=15000;
  idServer.ReadTimeout:=15000;
  try
    try
      try     //2015-02-05 liping.chen
        if trim(MainForm.BDSFMatchAddress) = '' then Exit;
        sResponse := UTF8Decode(idServer.Get(MainForm.BDSFMatchAddress));
      except on E : Exception do
        begin
          MainForm.LogInfo('idServer.Get获取北单胜负对阵失败'+ E.Message, True);
          Exit;
        end;
      end;
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponse,'FileBDSFDZDate') then
        begin
          MainForm.LogInfo('保存北单胜负对阵页面成功', True);
        end;
      end;
      //------------------可以修改为不用截短-直接移位取[取赛果]---------
      //彩期
      pos1 := posex('<no>',sResponse,1);
      sResponse := copy(sResponse,pos1+length('<no>'),Length(sResponse)-Length('<no>')-pos1+1);
      pos2 := posex('</no>',sResponse,1);
      Term :=  copy(sResponse,2,pos2-2) ;
      Term := FormatDateTime('Y',now) + Term ;
      // 销售中场次数
      pos1 :=  posex('<selling>',sResponse,1);
      sResponse := copy(sResponse,pos1+length('<selling>'),Length(sResponse)-Length('<selling>')-pos1+1);
      pos2 := posex('</selling>',sResponse,1);
      SellMatchCount := StrToInt(Copy(sResponse,1,pos2-1));
      // 停止销售场次数
      pos1 :=  posex('<stopsell>',sResponse,1);
      sResponse := copy(sResponse,pos1+length('<stopsell>'),Length(sResponse)-Length('<stopsell>')-pos1+1);
      pos2 := posex('</stopsell>',sResponse,1);
      StopMatchCount := StrToInt(Copy(sResponse,1,pos2-1));
      TotalMatchCount := SellMatchCount+ StopMatchCount ;
      // 截取场次信息字符
      pos1 :=  posex('<matchelem>',sResponse,1);
      sResponse := Copy(sResponse,pos1+length('<matchelem>'),Length(sResponse)-Length('<matchelem>')-pos1+1);
      SetLength(BDSFMatchList,TotalMatchCount);   
      for i := 0 to TotalMatchCount-1 do
      begin
        // 场次序号
        pos1 := posex('<no>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<no>'),Length(sResponse)-Length('<no>')-pos1+1);
        pos2 := posex('</no>',sResponse,1);
        MatchNo:= StrToInt(Copy(sResponse,1 ,pos2-1)) ;//
        //   主队
        pos1 :=  posex('<host>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<host>'),Length(sResponse)-Length('<host>')-pos1+1);
        pos2 := posex('</host>',sResponse,1);
        HomeTeam := Copy(sResponse,1 ,pos2-1 ) ;
        //  客队
        pos1 :=  posex('<guest>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<guest>'),Length(sResponse)-Length('<guest>')-pos1+1);
        pos2 := posex('</guest>',sResponse,1);
        VisitingTeam := Copy(sResponse,1 ,pos2-1 );
        // 开赛时间
        pos1 := posex('<endTime>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<endTime>'),Length(sResponse)-Length('<endTime>')-pos1+1);
        pos2 := posex('</endTime>',sResponse,1) ;
        StartDate := TranDrawDateEx(Copy(sResponse,1,pos2-1));
        //  让分
        pos1 :=  posex('<handicap>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<handicap>'),Length(sResponse)-Length('<handicap>')-pos1+1);
        pos2 := posex('</handicap>',sResponse,1);
        Handicap := StrToFloat(Copy(sResponse,1 ,pos2-1 )) ;
        // 赛事
        pos1 :=  posex('<leagueName>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<leagueName>'),Length(sResponse)-Length('<leagueName>')-pos1+1);
        pos2 := posex('</leagueName>',sResponse,1);
        RaceName := Copy(sResponse,1 ,pos2-1 ) ;
        // 状态
        pos1 := posex('<matchandstate>',sResponse,1);
        sResponse := Copy(sResponse,pos1+length('<matchandstate>'),Length(sResponse)-Length('<matchandstate>')-pos1+1);
        pos2 := posex('</matchandstate>',sResponse,1) ;
        StatusStr :=Copy(sResponse,1,pos2-1);
        if  StatusStr= '销售中' then
        begin
          status := 1;
        end else
          status := 2;
        BDSFMatchList[i].TERM := term ;
        BDSFMatchList[i].Status := status;
        BDSFMatchList[i].StartDate := StartDate ;
        BDSFMatchList[i].RaceName := RaceName ;
        BDSFMatchList[i].HomeTeam := HomeTeam ;
        BDSFMatchList[i].VisitingTeam := VisitingTeam ;
        BDSFMatchList[i].MatchNo := MatchNo ;
        BDSFMatchList[i].Handicap := Handicap ;
      end;
      Result:=True;
    except on E: Exception do
      begin
       MainForm.LogInfo('抓取北单胜负过关对阵出错!'+ E.Message, True);
       Exit;
      end;
    end;
  finally
    idServer.Free;
  end;
end;

function TBDSFMatchThd.SaveData: Boolean;
var
  i,iRepeat, iBDSFMatchCount, iReturnCode: Integer;
  sSQLString: string;
  iLotMacthId : Integer;
  sMatchRet,sTmp : string;
  BDSFCount,iNoChangeNum : Integer;
begin
  Result := False;
  BDSFCount:=0;
  iNoChangeNum:=0;
  iBDSFMatchCount := Length(BDSFMatchList);
  if iBDSFMatchCount<=0 then
  begin
    MainForm.LogInfo('准备写入北单胜负过关 对阵的场数为0 ', True);
    Exit;
  end;
  MainForm.LogInfo('准备写入北单胜负过关对阵彩期:'+BDSFMatchList[0].TERM+'' +inttostr(iBDSFMatchCount)+'', True);
///////////////////////////////////////北单胜负过关对阵//////////////////////////////
  try
    if hsl_Match.Count > 1000 then
      hsl_Match.Clear;
    for i := 0 to iBDSFMatchCount - 1 do
    begin
      //
      // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
      iLotMacthId := 35 * 10000 + BDSFMatchList[i].MatchNo;
      sMatchRet := trim(BDSFMatchList[i].TERM) +
                   '^' + IntToStr(BDSFMatchList[i].MatchNo) +
                   '^' + BDSFMatchList[i].RaceName +
                   '^' + IntToStr(BDSFMatchList[i].Status) +
                   '^' + DateTimeToStr(BDSFMatchList[i].StartDate) +
                   '^' + trim(BDSFMatchList[i].HomeTeam) +
                   '^' + Trim(BDSFMatchList[i].VisitingTeam) +
                   '^' + FloatToStr(BDSFMatchList[i].Handicap);
      // 判断hashed是否存在
      sTmp := trim(hsl_Match.Values[IntToStr(iLotMacthId)]);
      if sTmp = '' then
        hsl_Match.Add(IntToStr(iLotMacthId) + '=' + sMatchRet)
      else
      begin
        if sTmp = Trim(sMatchRet) then
        begin
          //MainForm.LogInfo('【北单胜负赛程】无变更:' + sMatchRet, True);
          inc(iNoChangeNum);
          Continue;   // 退出
        end
        else
          hsl_Match.Values[IntToStr(iLotMacthId)] := Trim(sMatchRet);
      end;
      // ---------------------------------------------------------------------
      sSQLString := 'CALL P_MATCH_BD_SF_INSERT ('
           + QuotedStr(BDSFMatchList[i].TERM)
           + ',' + QuotedStr(IntToStr(BDSFMatchList[i].MatchNo))
           + ',' + QuotedStr(BDSFMatchList[i].RaceName)
           + ',' + QuotedStr(IntToStr(BDSFMatchList[i].Status))
           + ',' + QuotedStr(DateTimeToStr(BDSFMatchList[i].StartDate))
           + ',' + QuotedStr(BDSFMatchList[i].HomeTeam)
           + ',' + QuotedStr(BDSFMatchList[i].VisitingTeam)
           + ',' + QuotedStr(FloatToStr(BDSFMatchList[i].Handicap));
           sSQLString := sSQLString +',@a); select @a;';

      iRepeat:=0;
      while True do
      begin
        try    //2015-02-05 liping.chen
          mqMain.Close;
          mqMain.SQL.Text := sSQLString;
          mqMain.Execute;
          iReturnCode := mqMain.Fields.Fields[0].AsInteger;
          mqMain.Close;
          Break;
        except on E : Exception do
          begin
            inc(iRepeat);
            MainForm.LogInfo('北单胜负对阵'+BDSFMatchList[i].TERM +' '+IntToStr(BDSFMatchList[i].MatchNo)+'场次写入失败!第'+IntToStr(iRepeat)+''+E.Message, True);
            mqMain.Close;
            if iRepeat=2 then
            begin
              hsl_Match.Values[IntToStr(iLotMacthId)] :='';
              Break;
            end;
          end;
        end;
      end;
      if iRepeat=2 then
      begin
        Continue;
      end;

      if iReturnCode = 1 then              //数据验证失败
      begin
        MainForm.LogInfo('写入北单胜负过关对阵失败,原因:数据验证失败'+BDSFMatchList[i].TERM +' '+IntToStr(BDSFMatchList[i].MatchNo) , True);
        hsl_Match.Values[IntToStr(iLotMacthId)] :='';
        Continue;
      end else if iReturnCode = 100 then
      begin
        MainForm.LogInfo('写入北单胜负过关对阵失败,原因:未知错误'+BDSFMatchList[i].TERM +' '+IntToStr(BDSFMatchList[i].MatchNo) , True);
        hsl_Match.Values[IntToStr(iLotMacthId)] :='';
        Continue;
      end;
      BDSFCount := BDSFCount + 1;
    end;
    if BDSFCount>0 then
    begin
      // 更新北单胜负截止时间
      try
         mqMain.Close;
         sSQLString := ' CALL P_BDSF_TERM_UPDATE() '  ;
         mqMain.SQL.Text := sSQLString ;
         mqMain.Execute ;
         mqMain.Close;
      except on E: Exception do
        MainForm.LogInfo('更新北单胜负过关截止时间出错!'+ E.Message, True);
      end;
    end;
    MainForm.LogInfo('已写入北单胜负对阵'+IntToStr(BDSFCount)+'场;无变更'+ IntToStr(iNoChangeNum)+''+#13#10, True);
    result := true;
  except on E : Exception do
    begin
      MainForm.LogInfo('写入北单胜负过关对阵失败,原因:' + E.Message, True);
      Exit;
    end;
  end;
end;
procedure TBDSFMatchThd.SetPause(const aIsPause: Boolean);
begin
  Pause := aIsPause;
end;
destructor TBDSFMatchThd.Destroy;
begin
  if Assigned(mcMain) then mcMain.Free;
  if Assigned(mqMain) then mqMain.Free;
  if Assigned(hsl_Match) then hsl_Match.Free;
  inherited;
end;
end.
北单胜负赛程

 

{*******************************************************************************
  Copyright (C), 2011-2015, aicaipiao
  File name: 所在单元
  Author: rulinzhang
  Version: 版本
  Date: 日期
  Description: 基本描述
  Others:
  Function List:
  History:
   7. Date: 2015-03-23
        Author: liping.chen
        Modification: 竞篮让分和预设总分页面改版,和竞足让分改版一样。
        [右键-查看源代码,看不出所需数据了,找到Json格式的数据源],尽量少改动原有函数;
   6. Date: 2015-01-21
        Author: liping.chen
        Modification: 设置SET NAMES GB2312优化
                      竞篮让分、预设总分 取消 分多次抓取网页。
   5. Date: 2015-01-13
        Author: liping.chen
        Modification: 竞彩赛程全部单过关修改为全可投注
   4. Date: 2014-12-15
        Author: liping.chen
        Modification: 竞篮竞足赛程单过关状态修改,竞足取消原停赛函数
                      P_STOP_MATCH_FLAG存储过程在本线程不再使用
                      竞足让分默认为0
   3. Date: 2013-05-17
        Author: rulinzhang
        Modification: 针对竞彩新玩法胜平负
   2. Date: 2013-04-09
        Author: rulinzhang
        Modification: 针对混合过关,无法保存场次问题的处理
   1. Date: 2013-03-13
        Author: rulinzhang
        Modification: 获取场次唯一码的地址有误。原为.com ,现改为.cn
*******************************************************************************}
unit ThdJCMatch;

interface

uses              
  Dialogs,Classes, MyAccess, PubDefine, SysUtils, XMLDoc, XMLIntf, IniFiles,IdHTTP,
  ActiveX, oxmldom, xmldom, DateUtils,StrUtils;

type
  TJCMatchThd = class(TThread)
  private
    { Private declarations }
    Pause: Boolean;                                                                                
    mcMain: TMyConnection;
    mqMain: TMyQuery;
    LTypeList: THashedStringList;
    iJCType : Integer;

    function CatchMatch: Boolean;
    function GetBBMatch: Boolean;
 //   function GetBBSales: Boolean;
    function GetBBGivenScore(MatchID,HomeTeam,Response : string):Real ;             // 篮球让分
    function GetBBPresetScore(MatchID ,AwayTeam,Response:string):Real ;    // 篮球预设总分
    function GetFBMatch: Boolean;
    function GetFBGivenScore:Boolean ;  // 足球让分
  //  function GetFBSales: Boolean;
  //  function GetFBGoalLine :Boolean;
    function GetStopMatch : Boolean ;    //2014-12-15 liping.chen 已经不使用
    function SaveData: Boolean;
    function SaveDateStopMatch : Boolean ; //2014-12-15 liping.chen 已经不使用
    function GetLotteryType(aTypeName: string): string;
    function GetMatchNo(BusinessDate: string;MatchTime: string): string ;
    function TranMatchDateEx(const aMatchDate: string): TDateTime;

  protected

  public
    iJcInv : Integer;
    hsl_Match : THashedStringList;

    constructor Create(iType:integer;Finterval:integer);
    procedure Execute; override;
    destructor Destroy; override;
    procedure SetPause(const aIsPause: Boolean);
  end;

implementation

uses FrmMain;

var
  BBMatchList, FBMatchList   : array of TMatch;
  FBStopMatchList  : TStringList;

{ Important: Methods and properties of objects in visual components can only be
  used in a method called using Synchronize, for example,

      Synchronize(UpdateCaption);

  and UpdateCaption could look like,

    procedure JCMatchThd.UpdateCaption;
    begin
      Form1.Caption := 'Updated in a thread';
    end; }

{ JCMatchThd }

// 日期转换
function TJCMatchThd.TranMatchDateEx(const aMatchDate: string): TDateTime;
var
  FS:TFormatSettings;
  sTemp: string;
  aYear : string ;
begin
  FS.ShortDateFormat := 'yyyy-mm-dd';
  FS.LongTimeFormat := 'hh:mm:ss';
  FS.DateSeparator := '-';
  FS.TimeSeparator := ':';
  aYear := Copy(FormatDateTime('yyyy',Date),0,2);
  sTemp := aMatchDate;

  sTemp := aYear+ sTemp + ':00';
  Result := StrToDateTimeDef(sTemp, MinDateTime, FS);
end;

//  推算发布时间 方法
function TJCMatchThd.GetMatchNo(BusinessDate: string;MatchTime: string): string ;
var
  WeekList : THashedStringList ;
  BusinessInt,MatchTimeInt : Integer ;
  DayDiff : Integer ;
  MatchTimeTemp : TDateTime ;
begin
  WeekList := THashedStringList.Create ;
  try
    // 周转换
    WeekList.Add('周一=1');
    WeekList.Add('周二=2');
    WeekList.Add('周三=3');
    WeekList.Add('周四=4');
    WeekList.Add('周五=5');
    WeekList.Add('周六=6');
    WeekList.Add('周日=7');
    //
    BusinessInt := StrToInt(WeekList.Values[BusinessDate]);
    MatchTimeTemp := TranMatchDateEx(MatchTime);
    //  MatchTimeTemp := TranDrawDate()
    // MatchTimeTemp  := StrToDateTime(MatchTime)  ;

    MatchTimeInt := DayOfTheWeek(MatchTimeTemp);
    if   BusinessInt >  MatchTimeInt then
    begin
      DayDiff := 7-BusinessInt + MatchTimeInt;
    end else
    begin
      DayDiff :=  MatchTimeInt - BusinessInt ;
    end;
    // 返回处理
    Result :=  FormatDateTime('yymmdd',MatchTimeTemp - DayDiff);
    // 2013-05-17 rulinzhang 未做异常处理
  finally
    WeekList.Free;
  end;
end;

function TJCMatchThd.CatchMatch: Boolean;
begin
  Result := False;
  // 此stringlist 会在如下那个函数中运行
  FBStopMatchList :=  TStringList.Create ;
  try
    MainForm.LogInfo('开始抓取竞彩对阵', True);
    // 初始化列表
    SetLength(BBMatchList, 0);
    SetLength(FBMatchList, 0);
    //
    case iJCType of
      0 :begin
        if not GetBBMatch then
        begin
          MainForm.LogInfo('获取竞彩篮球对阵出错,等待重试!', True);
          // AddErrorSmsLog(9,'【获取竞彩篮球对阵出错】');
          // Exit;
        end;
        if not GetFBMatch then
        begin
          MainForm.LogInfo('获取竞彩足球对阵出错,等待重试!', True);
          // AddErrorSmsLog(9,'【获取竞彩足球对阵出错】' );
          //  Exit;
        end;
      end;
      4 :begin
        if not GetBBMatch then
        begin
          MainForm.LogInfo('获取竞彩篮球对阵出错,等待重试!', True);
          // AddErrorSmsLog(9,'【获取竞彩篮球对阵出错】');
          // Exit;
        end;
      end;
      7 : begin
        if not GetFBMatch then
        begin
          MainForm.LogInfo('获取竞彩足球对阵出错,等待重试!', True);
          // AddErrorSmsLog(9,'【获取竞彩足球对阵出错】' );
          //  Exit;
        end;
      end;
    end;
    {if not GetBBSales then
    begin
      MainForm.LogInfo('获取竞彩篮球开售情况出错,等待重试!', True);
    //  Exit;
    end;
    if not GetFBSales then
    begin
      MainForm.LogInfo('获取竞彩足球开售情况出错,等待重试!', True);
    //  Exit;
    end;}
    // 保存数据
    Result := SaveData;

    {case iJCType of    //2014-12-15 liping.chen 不需要了
      0,7 : begin
        if not GetStopMatch then
        begin
          MainForm.LogInfo('获取竞彩足球停赛情况出错,等待重试!', True);
          Exit;
        end;
        //
        if not SaveDateStopMatch then
        begin
          MainForm.LogInfo('更新竞足停赛和单关过关开售状态出错,等待重试!', True);
          Exit
        end;
      end;
    end;  }
  finally
     FBStopMatchList.Free ;
  end;
end;

constructor TJCMatchThd.Create(iType:integer;Finterval:integer);
begin
  inherited Create(True);
  FreeOnTerminate := True;
  iJCType := iType;
  iJcInv := Finterval;
  hsl_Match := THashedStringList.Create;
  // 1 数据连接池
  mcMain := TMyConnection.Create(nil);
  mcMain.Server := ConnectionConfig.Server;
  mcMain.Username := ConnectionConfig.Username;
  mcMain.Password := ConnectionConfig.Password;
  mcMain.Port := ConnectionConfig.Port;
  mcMain.Database := ConnectionConfig.Database;
  mcMain.LoginPrompt := False;
  try
    mcMain.Connect;
  except on ex:Exception do
    begin
      MainForm.LogInfo('初始化数据库连接超时:' + ex.Message, True);
      Exit;
    end;
  end;
  // 2 查询连接
  mqMain := TMyQuery.Create(nil);
  mqMain.Connection := mcMain;
  // 3 彩种列表  暂时没有使用
  LTypeList := THashedStringList.Create;
  LTypeList.Add('MNL=45');
  LTypeList.Add('HDC=46');
  LTypeList.Add('WNM=47');
  LTypeList.Add('HILO=48');

  // 4 线程设定
  if iJCType = 0 then
    SetPause(True)
  else
    SetPause(false);
  CoInitialize(nil);
  Self.Resume;
end;

destructor TJCMatchThd.Destroy;
begin
  if Assigned(mcMain) then mcMain.Free;
  if Assigned(mqMain) then mqMain.Free;
  if Assigned(LTypeList) then LTypeList.Free;
  if Assigned(hsl_Match) then hsl_Match.Free;
  CoUninitialize;
  inherited;
end;

procedure TJCMatchThd.Execute;
var
  bPauseStatus: Boolean;
  dtTemp: TDateTime;
  iNum : Integer;// 执行次数
begin
  { Place thread code here }
  bPauseStatus := Pause;
  iNum := 0;
  while (iNum < 4 ) and (not Terminated) do   //线程.Terminate时确保可以结束线程。
  begin
    if iJCType = 0 then
    begin
      iNum := 1;
      Sleep(iJcInv);
    end
    else
    begin
      iNum := iNum + 1;
      Sleep(500);
    end;
    //
    JcMtchRunTime := Now;                      //2013-04-28 监控变量
    if not Pause then                          //如果没有收到暂停信息
    begin
      if MainForm.IsCatchJCMatch then         //如果需要抓取
      begin
        if bPauseStatus <> Pause then
        begin
          MainForm.LogInfo('抓取线程***竞彩对阵***已启动', True);
          bPauseStatus := Pause;
        end;
        MainForm.IsJCMatchCatching := True;
        if CatchMatch then                    //如果抓取成功
        begin
          MainForm.LogInfo('竞彩对阵抓取成功,等待下一次抓取', True);
          dtTemp := Now;
          while not Pause do
          begin
            Sleep(500);
            if SecondsBetween(Now, dtTemp) > MainForm.JCMatchGetInv then Break;
          end;
        end
        else begin
          MainForm.LogInfo('抓取竞彩对阵失败,等待重试', True);
          Sleep(RETRY_INV);
        end;
      end
      else begin
        if bPauseStatus <> Pause then
        begin
          MainForm.LogInfo('抓取线程***竞彩对阵***已启动,但设置为不抓取', True);
          bPauseStatus := Pause;
        end;
        Sleep(200);
      end;
    end
    else begin                                 //如果暂停抓取
      if bPauseStatus <> Pause then
      begin
        MainForm.LogInfo('抓取线程***竞彩对阵***已暂停', True);
        bPauseStatus := Pause;
      end;
      MainForm.IsJCMatchCatching := False;
      Sleep(500);
    end;
  end;
end;

function TJCMatchThd.GetBBMatch: Boolean;
var
  ipos1 ,ipos2 ,ipos3 : integer;
  idHttp : TIdHTTP ;
  //Url,
  sResponse,MatchNO,ID : string ;
  HomeTeam , awayTeam : string ;
  GivenScore ,PresetScore : Real;
  matchtime : string ;
  StrLog,SaleStatus : string ;
  SaleType  : string ;
  SaleList : THashedStringList ;
  LotteryType : THashedStringList ;
  WeekStr,WeekStrNo : string ;
  MatchCount ,SaleCount,LotteFlag: Integer ;  
  //SingleMultipleStr,LotteryStr : string ;
  iUrlLen :Integer;
  sResponsePreset,sResponseGiven :string;
begin
  {
   ID: string;               //获取到的比赛ID
    MatchIndex: string;       //场次编码,格式为:110217-301
    MatchTime: TDateTime;     //比赛时间
    Sales: array of TSales;   //开售状态
    HomeTeam: string;         //主队名
    AwayTeam: string;         //客队名
    GivenScore: Real;         //让分让球
    PresetScore: Real;        //预设总分
    }
  Result := False ;
  SaleList := THashedStringList.Create ;
  LotteryType :=  THashedStringList.Create ;
  idHttp := TIdHTTP.Create(nil);
  idHttp.ConnectTimeout:=15000;
  idHttp.ReadTimeout:=15000;
  try
    try
      // Url := 'http://info.sporttery.com/basketball/match_list.php';
      try   //2015-02-05 liping.chen
        MainForm.LogInfo('正在获取竞篮对阵数据', True);
        sResponse := idHttp.Get(MainForm.BBMatchAddress) ;
      except on E : Exception do
        begin
          MainForm.LogInfo('idHttp.Get获取竞篮对阵数据失败 '+ E.Message, True);
          Exit;
        end;
      end;
      // 1 是否保存文件
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponse,'FileLQDZDate') then
          MainForm.LogInfo('保存竞彩篮球对阵页面成功', True);
      end;

      //========================================
      try
        MainForm.LogInfo('正在获取篮球对阵预设总分情况', True);
        sResponsePreset := idhttp.Get(MainForm.BBPresetScoreAddress);
      except on E : Exception do
        begin
          MainForm.LogInfo('idHttp.Get获取篮球对阵预设总分情况失败 '+ E.Message, True);
          Exit;
        end;
      end;
      //
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponsePreset,'FileLQYSZFDate') then
          MainForm.LogInfo('保存竞彩篮球对阵预设总分页面成功', True);
      end;
      //-------------------------------------------
      try
        MainForm.LogInfo('正在获取篮球对阵让分情况', True);
        sResponseGiven := idhttp.Get(MainForm.BBGivenScoreAddress);
      except on E : Exception do
        begin
          MainForm.LogInfo('idHttp.Get获取篮球对阵让分情况失败 '+ E.Message, True);
          Exit;
        end;
      end;
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponseGiven,'FileLQRFDate') then
        begin
          MainForm.LogInfo('保存竞彩篮球对阵让分页面成功', True);
        end;
      end;
      //=========================================
      // 2 开始解析数据
      // 2013-12-19 RULINZHANG add   缩小处理范围
      iPos1 := Pos('search_form', sResponse);
      if iPos1 = 0 then
        iPos1 := Pos('SEARCH_FORM', sResponse);
      sResponse := Copy(sResponse,iPos1,Length(sResponse) - iPos1 - 50);
      iPos2 := Pos('</form>', sResponse);
      if iPos2 = 0 then
        iPos2 := Pos('</FORM>', sResponse);
      sResponse := Copy(sResponse,1,iPos2 + 50);   //去掉末端,而已
      //
      StrLog := '<th class="txc forange">';
      ipos1 := PosEx(StrLog,sResponse) ;
      if (iPos1 = 0)then
      begin
        MainForm.LogInfo('获取竞篮对阵时出错,找不到标识字符串'+StrLog, True);
        Exit;
      end;
      MatchCount := 0 ;
      while ipos1 > 0 do
      begin
        SetLength(BBMatchList,Length(BBMatchList)+1);
        GivenScore :=0 ;  //让分清零
        PresetScore :=0; // 预设总分清零

        // 2.1 场次编号
        iPos1 := Posex('<td width="80">', sResponse,iPos1);
        sResponse := Copy(sResponse,ipos1+Length('<td width="80">') ,Length(sResponse)-Length('<td width="80">')-iPos1+1) ;
        ipos2  := PosEx('<',sResponse);
        WeekStr :=  Copy(sResponse,0,ipos2-1) ;
        MatchNO := rightstr(WeekStr,3);
        WeekStrNo  := LeftStr(WeekStr,2);
        // 2.2 官方编号
        ipos2  := PosEx('http://info.sporttery.cn/basketball/info/bk_match_mnl.php?m=',sResponse);
        iUrlLen := Length('http://info.sporttery.cn/basketball/info/bk_match_mnl.php?m=');
        sResponse := Copy(sResponse,ipos2+ iUrlLen,Length(sResponse)-ipos2- iUrlLen + 1);
        ipos3  := PosEx('''',sResponse);
        ID :=  Copy(sResponse,0,ipos3-1);
        // 2.3 客队
        ipos2  := PosEx('>',sResponse);
        sResponse := Copy(sResponse,ipos2+ Length('>'),Length(sResponse)-ipos2-Length('>')+1);
        ipos3  := PosEx('<strong>',sResponse);
        awayTeam  :=  Trim(Copy(sResponse,0,ipos3-1));
        // 2.4 主队
        ipos2  := PosEx('</strong>',sResponse);
        sResponse := Copy(sResponse,ipos2+ Length('</strong>'),Length(sResponse)-ipos2-Length('</strong>')+1);
        ipos3  := PosEx('</a>',sResponse);
        HomeTeam :=  Copy(sResponse,0,ipos3-1);
        // 2.5 截至时间
        ipos1  := Pos('<td',sResponse);
        ipos2  := Posex('>',sResponse,ipos1);
        sResponse := Copy(sResponse,ipos2+ Length('>'),Length(sResponse)-ipos2-Length('>')+1);
        ipos3  := PosEx('</td>',sResponse);
        matchtime   :=  Copy(sResponse,3,ipos3-3); //更改前格式>14-11-28 02:14<  更改后格式>2014-12-13 02:59<
        // 2.6 场次官方编码
        MatchNO := GetMatchNo(WeekStrNo,matchtime)+'-'+MatchNO;
        
        // 2.7 销售情况  // 销售类型   单关过关
        ipos2  := PosEx('>',sResponse,ipos3+6);
        sResponse := Copy(sResponse,ipos2+ Length('>'),Length(sResponse)-ipos2-Length('>')+1);
        ipos3  := PosEx('</td>',sResponse);
        SaleStatus  :=  Copy(sResponse,0,ipos3-1);
        if SaleStatus ='已开售' then     //开售才去抓取 让分 和预设总分 目前竞篮开售和未开售都一起存入数据库。
        begin
          // 2.8 让分
          GivenScore := GetBBGivenScore(ID,HomeTeam,sResponseGiven) ;
          // 2.9 预设总分
          PresetScore := GetBBPresetScore(ID,HomeTeam,sResponsePreset);

          for LotteFlag :=45  to 48 do     //循环 移位取信息,不截短,
          begin
            SetLength(BBMatchList[MatchCount].Sales,Length(BBMatchList[MatchCount].Sales)+1) ;

            BBMatchList[MatchCount].Sales[LotteFlag-45].LotteryType := IntToStr(LotteFlag);
            BBMatchList[MatchCount].Sales[LotteFlag-45].IsDGSale :=True; // False; //2015-01-13 liping.chen 全部修改为可投注
            BBMatchList[MatchCount].Sales[LotteFlag-45].IsGGSale:=True;  // False ;





            {SaleType :=''; //销售类型 每次清空

            iPos1 := posex('"_blank"><div class="',sResponse,iPos1+10);  //iPos1+10 为了让字符串向前截取
            iPos2 := posex('"></div>',sResponse,iPos1) ;
            SaleType :=Copy(sResponse,iPos1+length('"_blank"><div class="'),iPos2-iPos1-length('"_blank"><div class="'));
            if LotteFlag=47 then
            begin
              BBMatchList[MatchCount].Sales[LotteFlag-45].LotteryType:='48'; //对应彩种大小分  //Sales[LotteFlag-45]为了下标从0开始
            end
            else if LotteFlag=48 then
            begin
              BBMatchList[MatchCount].Sales[LotteFlag-45].LotteryType:='47'; //对应彩种胜分差
            end
            else
              BBMatchList[MatchCount].Sales[LotteFlag-45].LotteryType:=IntToStr(LotteFlag); //彩种

            case Pos(SaleType,'*kong*dan*closed*') of
              2:begin
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsDGSale:=False;
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsGGSale:=True;
               end  ;
              7:begin
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsDGSale:=True;
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsGGSale:=True;
               end;
              11:begin   //closed 为未开售此玩法
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsDGSale:=False;
                 BBMatchList[MatchCount].Sales[LotteFlag-45].IsGGSale:=False;
              end;
            end; }
          end;
        end
        else if SaleStatus ='&nbsp;' then  //2015-02-05 liping.chen 竞篮赛程页面变更修改
        begin
          SaleCount := 0 ;
          for LotteFlag:=45 to 48 do
          begin
            SetLength(BBMatchList[MatchCount].Sales,Length(BBMatchList[MatchCount].Sales)+1) ;
            BBMatchList[MatchCount].Sales[SaleCount].LotteryType := IntToStr(LotteFlag);
            BBMatchList[MatchCount].Sales[SaleCount].IsDGSale :=True; // False; //2015-01-13 liping.chen 全部修改为可投注
            BBMatchList[MatchCount].Sales[SaleCount].IsGGSale:=True;  // False ;
            SaleCount := SaleCount + 1;
          end;
        end;

        // 2.11 场次信息存储
        BBMatchList[MatchCount].ID := ID;
        BBMatchList[MatchCount].MatchIndex := MatchNO;
        // BBMatchList[MatchCount].MatchTime :=  StrToDateTime(matchtime);
        BBMatchList[MatchCount].MatchTime := TranMatchDateEx(matchtime);
        BBMatchList[MatchCount].HomeTeam := HomeTeam ;
        BBMatchList[MatchCount].AwayTeam := awayTeam ;
        BBMatchList[MatchCount].GivenScore := GivenScore ;
        BBMatchList[MatchCount].PresetScore := PresetScore ;
        
        // 场次数加 1
        MatchCount :=   MatchCount + 1 ;
        iPos1 := Posex('<td width="80">', sResponse,iPos3);    //这句很重要,判断是否还有场次未抓取完。
      end;

      Result := True ;
    except on e: Exception do
      begin
        MainForm.LogInfo('获取竞彩篮球对阵出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    SaleList.Free;
    LotteryType.free;
    idHttp.Free;
  end;
end;

{
function TJCMatchThd.GetBBMatch: Boolean;
var
  ResponseXML: TXMLDocument;
  RXMLRoot: IXMLNode;
  RXMLList: IXMLNodeList;
  DateStr: string;
  i, j, k, NodeCount, MatchListIndex: Integer;
  FS:TFormatSettings;
begin
  try
    Result := True;
    FS.ShortDateFormat := 'yyyy-mm-dd';
    FS.LongTimeFormat := 'hh:mm:ss';
    FS.DateSeparator := '-';
    FS.TimeSeparator := ':';
    MainForm.LogInfo('正在获取竞彩篮球对阵数据', True);
    try
      ResponseXML := TXMLDocument.Create(MainForm);
      ResponseXML.DOMVendor := GetDomVendor(oxmldom.SOpenXML);
      ResponseXML.LoadFromFile(MainForm.BBMatchAddress + IntToStr(Random(1000)));
     // ResponseXML.LoadFromFile(MainForm.BBMatchAddress);
      RXMLRoot := ResponseXML.DocumentElement;

      if MainForm.IsSaveFile then
      begin
         if not DirectoryExists('fieleLQDZDate') then
         CreateDir('fieleLQDZDate') ;
         ResponseXML.SaveToFile('fieleLQDZDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');
      end;
      RXMLList := RXMLRoot.ChildNodes;
      NodeCount := RXMLList.Count;
      for i := 0 to NodeCount - 1 do
      begin
        if RXMLList[i].NodeName <> 'Match' then Continue;
        SetLength(BBMatchList, Length(BBMatchList) + 1);
        MatchListIndex := Length(BBMatchList) - 1;
        BBMatchList[MatchListIndex].ID := RXMLList[i].Attributes['ID'];
        for j := 0 to RXMLList[i].ChildNodes.Count -1 do
        begin
          if (RXMLList[i].ChildNodes.Nodes[j].NodeName = 'HomeTeam') then
          begin
            for k := 0 to RXMLList[i].ChildNodes.Nodes[j].ChildNodes.Count - 1 do
            begin
              if RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].Attributes['lang'] = 'zh-cn' then
              begin
                BBMatchList[MatchListIndex].HomeTeam := RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].NodeValue;
                Break;
              end;
            end;
          end
          else if (RXMLList[i].ChildNodes.Nodes[j].NodeName = 'AwayTeam') then
          begin
            for k := 0 to RXMLList[i].ChildNodes.Nodes[j].ChildNodes.Count - 1 do
            begin
              if RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].Attributes['lang'] = 'zh-cn' then
              begin
                BBMatchList[MatchListIndex].AwayTeam := RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].NodeValue;
                Break;
              end;
            end;
          end
          else Continue;
        end;
        DateStr := Copy(RXMLList[i].ChildValues['BusinessDate'], 3, 8);
        DateStr := StringReplace(DateStr, '-', '', [rfIgnoreCase, rfReplaceAll]);
        BBMatchList[MatchListIndex].MatchIndex := DateStr + '-' + Copy(RXMLList[i].Attributes['num'], 2, 3);
        BBMatchList[MatchListIndex].MatchTime := StrToDateTime(RXMLList[i].ChildValues['MatchDate'] + ' ' + RXMLList[i].ChildValues['MatchTime'], FS);
      end;
    except on E : Exception do
      begin
        MainForm.LogInfo('获取竞彩篮球对阵出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    ResponseXML.Free;
  end;
end;

}

function TJCMatchThd.GetFBMatch: Boolean;
var
  ipos1 ,ipos2 ,ipos3 : integer;
  idHttp : TIdHTTP ;
  MatchNO,ID : string ;
  HomeTeam , awayTeam : string ;
  GivenScore : Real;
  GivenScoreStr : string ;
  matchtime : string ;
  StrLog ,SaleStatus, SaleType : string ;

  WeekStr,weekStrNo : string ;
  MatchCount : Integer ;
  sResponse : AnsiString ;
  iUrlLen ,LotteFlag : Integer;
begin
  idHttp := TIdHTTP.Create(nil) ;
  idHttp.ConnectTimeout:=15000;
  idHttp.ReadTimeout:=15000;
  try
    Result := True;
    try
      StrLog := '<td class="td1"' ;
      //  Url := 'http://info.sporttery.cn/football/match_list.php';
      try     //2015-02-05 liping.chen
        MainForm.LogInfo('正在获取竞彩足球对阵数据', True);
        sResponse  :=  idHttp.Get(MainForm.FBMatchAddress);
      except on E : Exception do
        begin
          MainForm.LogInfo('idHttp.Get获取竞彩足球对阵数据失败 '+ E.Message, True);
          Exit;
        end;
      end;
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponse,'FileZQDZDate') then
          MainForm.LogInfo('保存竞彩足球对阵页面成功', True);
      end;

     { //2014-12-15 liping.chen
      //获取受注赛程 总场数,可用for循环获取每场信息; 但目前用【while ipos1 >0 do】 方式
      iPos1 := Pos('查询结果:有',sResponse) ;
      iPos1 := PosRightEx('>',sResponse,ipos1);
      iPos2 := PosRightEx('</b>',sResponse,ipos1);
      iMatchCount := StrToIntDef((Copy(sResponse,iPos1+Length(CountStr),ipos2-iPos1-Length(CountStr))),-1);
      if iMatchCount =-1 then
      begin
         MainForm.LogInfo('获取页面有误,页面内容为:' + sResponse , True);
         Exit;
      end; }

      // 开始获取信息
      ipos1:=1;
      ipos1 := PosEx(StrLog,sResponse,ipos1);
      if (iPos1 = 0)then
      begin
        MainForm.LogInfo('获取竞足对阵时出错,找不到标识字符串'+StrLog, True);
        Exit;
      end;
      MatchCount := 0 ;
      while ipos1 >0 do
      begin
        SetLength(FBMatchList,Length(FBMatchList)+1) ;
        // 场次编号
        ipos1  := PosEx('>',sResponse,ipos1);
        ipos2  := PosEx('</td>',sResponse,ipos1 );
        weekStrNo :=  Copy(sResponse,ipos1+1,ipos2-ipos1-1) ;
        MatchNO := rightstr(weekStrNo,3);
        WeekStr := LeftStr(weekStrNo,2) ;
        //  官方编号
        ipos1  := PosEx('<a href="http://info.sporttery.cn/football/info/fb_match_info.php?m=',sResponse,ipos2);
        iUrlLen := Length('<a href="http://info.sporttery.cn/football/info/fb_match_info.php?m=');
        ipos2  := PosEx('" style=',sResponse,ipos1);
        ID :=  Copy(sResponse,ipos1+iUrlLen,ipos2-ipos1-iUrlLen);
        //  主队
        ipos1  := PosEx('>',sResponse,ipos2);
        ipos2  := PosEx(' VS ',sResponse,ipos1);
        HomeTeam  :=  Trim(Copy(sResponse,ipos1+1,ipos2-ipos1-1));
        // 客队
        ipos1 :=ipos2+Length(' VS ');
        ipos2  := PosEx('</a>',sResponse,ipos1);
        awayTeam  :=  Copy(sResponse,ipos1,ipos2-ipos1);
        // 取时间 合成场次编号
        ipos1  := PosEx('<td',sResponse,ipos2);
        ipos1  := PosEx('>',sResponse,ipos1);
        ipos2  := PosEx('</td>',sResponse,ipos1);
        matchtime  :=  Trim(Copy(sResponse,ipos1+3,ipos2-ipos1-3));
        // matchtime := StringReplace(matchtime,'-','/',[rfReplaceAll]) ;
        MatchNO := GetMatchNo(WeekStr,matchtime)+'-'+MatchNO;
        //销售情况
        ipos1  := PosEx('</td>',sResponse,ipos2+6);
        ipos1  := PosEx('>',sResponse,ipos1+6);
        ipos2  := PosEx('</td>',sResponse,ipos1);
        SaleStatus  :=  Copy(sResponse,ipos1+1,ipos2-ipos1-1);
        //
        if SaleStatus ='已开售' then  //2014-12-15 liping.chen
        begin
          SetLength(FBMatchList[MatchCount].Sales,Length(FBMatchList[MatchCount].Sales)+5) ;
          for LotteFlag:=69 to 73 do
          begin
            if LotteFlag=69 then
            begin
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType :='77'; //对应彩种 胜平负
            end
            else
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType :=IntToStr(LotteFlag); //彩种

            FBMatchList[MatchCount].Sales[LotteFlag-69].IsDGSale := True; // False; //2015-01-13 liping.chen 全部修改为可投注
            FBMatchList[MatchCount].Sales[LotteFlag-69].IsGGSale :=True; // False; //2015-01-13 liping.chen 全部修改为可投注
          end;


         { for LotteFlag :=69  to 73 do
          begin
            SaleType :=''; //销售类型 每次清空
            iPos1 := posex('"_blank"><div class="',sResponse,iPos1+10);  //iPos1+10 为了让字符串向前截取
            iPos2 := posex('"></div>',sResponse,iPos1) ;
            SaleType :=Copy(sResponse,iPos1+length('"_blank"><div class="'),iPos2-iPos1-length('"_blank"><div class="'));
            if LotteFlag=69 then
            begin
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType:='77'; //对应彩种 胜平负
            end                                                            //Sales[Lottery-69]为了下标从0开始
            else
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType:=IntToStr(LotteFlag); //彩种

            case Pos(SaleType,'*kong*dan*closed*') of
              2:begin
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsDGSale:=False;
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsGGSale:=True;
               end  ;
              7:begin
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsDGSale:=True;
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsGGSale:=True;
               end;
              11:begin   //closed 为未开售此玩法
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsDGSale:=False;
                 FBMatchList[MatchCount].Sales[LotteFlag-69].IsGGSale:=False;
              end;
            end;
          end; }
        end
        else //if SaleStatus ='' then
        begin
          SetLength(FBMatchList[MatchCount].Sales,Length(FBMatchList[MatchCount].Sales)+5) ;
          for LotteFlag:=69 to 73 do
          begin
            if LotteFlag=69 then
            begin
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType :='77'; //对应彩种 胜平负
            end
            else
              FBMatchList[MatchCount].Sales[LotteFlag-69].LotteryType :=IntToStr(LotteFlag); //彩种

            FBMatchList[MatchCount].Sales[LotteFlag-69].IsDGSale :=True; // False; //2015-01-13 liping.chen 全部修改为可投注
            FBMatchList[MatchCount].Sales[LotteFlag-69].IsGGSale :=True; // False; //2015-01-13 liping.chen 全部修改为可投注
          end;
        end;

        FBMatchList[MatchCount].ID := ID;
        FBMatchList[MatchCount].MatchIndex := MatchNO;
        FBMatchList[MatchCount].HomeTeam := HomeTeam ;
        FBMatchList[MatchCount].AwayTeam := awayTeam ;
        FBMatchList[MatchCount].GivenScore :=0;
        // FBMatchList[MatchCount].MatchTime := StrToDateTime(matchtime) ;
        FBMatchList[MatchCount].MatchTime := TranMatchDateEx(matchtime) ;
        //
        MatchCount := MatchCount +1 ;
        sResponse :=  Copy(sResponse,ipos2,length(sResponse)-ipos2) ;  //添加截短
        ipos1 := PosEx(StrLog,sResponse,1);
      end;
      if GetFBGivenScore then   //让分  一次性抓完
      begin
        MainForm.LogInfo('抓取竞足对阵让分成功', True);
      end;

      //*******************以下为测试代码
     { sResponse:='';
      for ipos1 :=0  to Length(FBMatchList)-1 do
      begin
        sResponse:=sResponse
            + ',' + QuotedStr(FBMatchList[ipos1].ID)
            + ',' + QuotedStr(FBMatchList[ipos1].MatchIndex)
            + ',' + QuotedStr(DateTimeToStr(FBMatchList[ipos1].MatchTime))
            + ',' + QuotedStr(FBMatchList[ipos1].HomeTeam)
            + ',' + QuotedStr(FBMatchList[ipos1].AwayTeam)
            + #13#10 ;
      end;
      MainForm.SaveFile(sResponse,'mytest'); }
      //************************
    except on E:Exception do
      begin
         MainForm.LogInfo('获取竞彩足球对阵出错,原因:' + E.Message, True);
         Result := False;
         Exit;
      end;
    end;
  finally
    idHttp.Free ;
  end;
end;



{
function TJCMatchThd.GetFBMatch: Boolean;
var
  ResponseXML: TXMLDocument;
  RXMLRoot: IXMLNode;
  RXMLList: IXMLNodeList;
  DateStr: string;
  i, j, k, NodeCount, MatchListIndex: Integer;
  FS: TFormatSettings;
begin
  try
    Result := True;
    FS.ShortDateFormat := 'yyyy-mm-dd';
    FS.LongTimeFormat := 'hh:mm:ss';
    FS.DateSeparator := '-';
    FS.TimeSeparator := ':';
    MainForm.LogInfo('正在获取竞彩足球对阵数据', True);
    try
      ResponseXML := TXMLDocument.Create(MainForm);
      ResponseXML.DOMVendor := GetDomVendor(oxmldom.SOpenXML);

     // ResponseXML.LoadFromFile(MainForm.FBMatchAddress);
      ResponseXML.LoadFromFile(MainForm.FBMatchAddress + IntToStr(Random(1000)));
    //  ResponseXML.LoadFromFile(MainForm.FBMatchAddress);
      RXMLRoot := ResponseXML.DocumentElement;

      if MainForm.IsSaveFile then
      begin
         if not DirectoryExists('fieleZQDZDate') then
         CreateDir('fieleZQDZDate') ;
         ResponseXML.SaveToFile('fieleZQDZDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');
      end;


      RXMLList := RXMLRoot.ChildNodes;
      NodeCount := RXMLList.Count;
      for i := 0 to NodeCount - 1 do
      begin
        if RXMLList[i].NodeName <> 'Match' then Continue;
        SetLength(FBMatchList, Length(FBMatchList) + 1);
        MatchListIndex := Length(FBMatchList) - 1;
        FBMatchList[MatchListIndex].ID := RXMLList[i].Attributes['ID'];
        for j := 0 to RXMLList[i].ChildNodes.Count -1 do
        begin
          if (RXMLList[i].ChildNodes.Nodes[j].NodeName = 'HomeTeam') then
          begin
            for k := 0 to RXMLList[i].ChildNodes.Nodes[j].ChildNodes.Count - 1 do
            begin
              if RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].Attributes['lang'] = 'zh-cn' then
              begin
                FBMatchList[MatchListIndex].HomeTeam := RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].NodeValue;
                Break;
              end;
            end;
          end
          else if (RXMLList[i].ChildNodes.Nodes[j].NodeName = 'AwayTeam') then
          begin
            for k := 0 to RXMLList[i].ChildNodes.Nodes[j].ChildNodes.Count - 1 do
            begin
              if RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].Attributes['lang'] = 'zh-cn' then
              begin
                FBMatchList[MatchListIndex].AwayTeam := RXMLList[i].ChildNodes.Nodes[j].ChildNodes[k].NodeValue;
                Break;
              end;
            end;
          end
          else Continue;
        end;
        DateStr := Copy(RXMLList[i].ChildValues['BusinessDate'], 3, 8);
        DateStr := StringReplace(DateStr, '-', '', [rfIgnoreCase, rfReplaceAll]);
        FBMatchList[MatchListIndex].MatchIndex := DateStr + '-' + Copy(RXMLList[i].Attributes['num'], 2, 3);
        FBMatchList[MatchListIndex].MatchTime := StrToDateTime(RXMLList[i].ChildValues['MatchDate'] + ' ' + RXMLList[i].ChildValues['MatchTime'], FS);
      end;

    except on E : Exception do
      begin
        MainForm.LogInfo('获取竞彩足球对阵出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    ResponseXML.Free;
  end;
end;

}

{
篮球销售情况
function TJCMatchThd.GetBBSales: Boolean;
var
  ResponseXML: TXMLDocument;
  RXMLRoot: IXMLNode;
  RXMLList: IXMLNodeList;
  DateStr: string;
  i, j, k, NodeCount, MatchCount, MatchListIndex: Integer;
begin
  try
    Result := True;
    MainForm.LogInfo('正在获取竞彩篮球开售数据', True);
    try
      ResponseXML := TXMLDocument.Create(MainForm);
      ResponseXML.DOMVendor := GetDomVendor(oxmldom.SOpenXML);
    //  ResponseXML.LoadFromFile(MainForm.BBSalesAddress + IntToStr(Random(1000)));
     // ResponseXML.LoadFromFile(MainForm.BBSalesAddress);
      RXMLRoot := ResponseXML.DocumentElement;
      RXMLList := RXMLRoot.ChildNodes;

      if MainForm.IsSaveFile then
      begin
        if not DirectoryExists('fieleLQXSDate') then
        CreateDir('fieleLQXSDate') ;
        ResponseXML.SaveToFile('fieleLQXSDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');
      end;

      NodeCount := RXMLList.Count;
      MatchCount := Length(BBMatchList);
      for i := 0 to NodeCount - 1 do
      begin
        if RXMLList[i].NodeName <> 'Match' then Continue;
        for j := 0 to MatchCount - 1 do
        begin
          if RXMLList[i].Attributes['ID'] <> BBMatchList[j].ID then Continue;
          SetLength(BBMatchList[j].Sales, RXMLList[i].ChildNodes.Count);
          for k := 0 to RXMLList[i].ChildNodes.Count - 1 do
          begin
            BBMatchList[j].Sales[k].LotteryType := RXMLList[i].ChildNodes[k].Attributes['code'];
            if RXMLList[i].ChildNodes[k].Attributes['code'] = 'HDC'
              then BBMatchList[j].GivenScore := RXMLList[i].ChildNodes[k].ChildValues['GoalLine']
            else if RXMLList[i].ChildNodes[k].Attributes['code'] = 'HILO'
              then BBMatchList[j].PresetScore := RXMLList[i].ChildNodes[k].ChildValues['GoalLine'];
            BBMatchList[j].Sales[k].IsDGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Single'];
            BBMatchList[j].Sales[k].IsGGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Allup'];
          end;
          Break;
        end;
      end;
    except on E : Exception do
      begin
        MainForm.LogInfo('获取竞彩篮球开售情况出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    ResponseXML.Free;
  end;
end;
}


{
//获取 足球销售情况
function TJCMatchThd.GetFBSales: Boolean;
var
  ResponseXML: TXMLDocument;
  RXMLRoot: IXMLNode;
  RXMLList: IXMLNodeList;
  DateStr: string;
  i, j, k, NodeCount, MatchCount, MatchListIndex: Integer;

begin
  try
    Result := True;
    MainForm.LogInfo('正在获取竞彩足球开售数据', True);
    try
      if not   GetFBGoalLine then Exit ;

      ResponseXML := TXMLDocument.Create(MainForm);
      ResponseXML.DOMVendor := GetDomVendor(oxmldom.SOpenXML);
      //ResponseXML.LoadFromFile(MainForm.FBSalesAddress);
     // ResponseXML.LoadFromFile(MainForm.FBSalesAddress + IntToStr(Random(1000)));
     // ResponseXML.LoadFromFile(MainForm.FBSalesAddress);
      RXMLRoot := ResponseXML.DocumentElement;
      RXMLList := RXMLRoot.ChildNodes;

      if MainForm.IsSaveFile then
      begin
        if not DirectoryExists('fieleZQXSDate') then
        CreateDir('fieleZQXSDate') ;
        ResponseXML.SaveToFile('fieleZQXSDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');
      end;

      NodeCount := RXMLList.Count;
      MatchCount := Length(FBMatchList);
      for i := 0 to NodeCount - 1 do
      begin
        if RXMLList[i].NodeName <> 'Match' then Continue;
        for j := 0 to MatchCount - 1 do
        begin
          if RXMLList[i].Attributes['ID'] <> FBMatchList[j].ID then Continue;
          SetLength(FBMatchList[j].Sales, RXMLList[i].ChildNodes.Count);


          for k := 0 to RXMLList[i].ChildNodes.Count - 1 do
          begin
            if RXMLList[i].ChildNodes[k].Attributes['code'] <> 'HHAD' then
            begin
              FBMatchList[j].Sales[k].LotteryType := RXMLList[i].ChildNodes[k].Attributes['code'];
              FBMatchList[j].Sales[k].IsDGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Single'];
              FBMatchList[j].Sales[k].IsGGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Allup'];
            end;
          end;


//          for k := 0 to RXMLList[i].ChildNodes.Count - 1 do
//          begin
//              FBMatchList[j].Sales[k].LotteryType := RXMLList[i].ChildNodes[k].Attributes['code'];
//              if RXMLList[i].ChildNodes[k].Attributes['code'] = 'HHAD'
//                then FBMatchList[j].GivenScore := RXMLList[i].ChildNodes[k].ChildValues['GoalLine'];
//              FBMatchList[j].Sales[k].IsDGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Single'];
//              FBMatchList[j].Sales[k].IsGGSale := RXMLList[i].ChildNodes[k].ChildNodes[0].ChildValues['Allup'];
//          end;


          Break;
        end;
      end;
    except on E : Exception do
      begin
        MainForm.LogInfo('获取竞彩足球开售情况出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    ResponseXML.Free;
  end;
end;
}



// 竞彩让分抓取
{
function TJCMatchThd.GetFBGoalLine:Boolean;
var
  ResponseXML: TXMLDocument;
  RXMLRoot: IXMLNode;
  RXMLList: IXMLNodeList;
  DateStr: string;
  i,j,NodeCount, MatchCount,MatchListIndex: Integer;
begin
  try
    Result := True;
    MainForm.LogInfo('正在获取竞彩足球让分数据', True);
    try
      ResponseXML := TXMLDocument.Create(MainForm);

      ResponseXML.DOMVendor := GetDomVendor(oxmldom.SOpenXML);
    //  ResponseXML.LoadFromFile(MainForm.FBGoalLineAddress);
      ResponseXML.LoadFromFile(MainForm.FBGoalLineAddress + IntToStr(Random(1000)));
   //   ResponseXML.LoadFromFile(MainForm.FBGoalLineAddress);

      RXMLRoot := ResponseXML.DocumentElement;

      if MainForm.IsSaveFile then
      begin
        if not DirectoryExists('fieleZQRFDate') then
        CreateDir('fieleZQRFDate') ;
        ResponseXML.SaveToFile('fieleZQRFDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');
      end;
      
      //ResponseXML.SaveToFile('D:\FBXMLData\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');


//      if not DirectoryExists('fieleRFDate') then
//        CreateDir('fieleRFDate');
//        ResponseXML.SaveToFile('fieleRFDate\' + FormatDateTime('yy-mm-dd-hh-mm-ss',Now)+ '.xml');


      RXMLList := RXMLRoot.ChildNodes;
      NodeCount := RXMLList.Count;
      MatchCount := Length(FBMatchList);

//      for i := 0 to NodeCount - 1 do
//      begin
//        if RXMLList[i].NodeName <> 'Match' then Continue;
//
//        if RXMLList[i].Attributes['ID'] <> ID then Continue;
//        LotteryType := RXMLList[i].ChildNodes[0].Attributes['code'];
//        GivenScore  := RXMLList[i].ChildNodes[0].ChildValues['GoalLine'];
//        IsDGSale    := RXMLList[i].ChildNodes[0].ChildNodes[1].ChildValues['Single'];
//        IsGGSale    := RXMLList[i].ChildNodes[0].ChildNodes[1].ChildValues['Allup'];
//        Break;
//        end;


      for i := 0 to NodeCount - 1 do
      begin
        if RXMLList[i].NodeName <> 'Match' then Continue;
        for j := 0 to MatchCount - 1 do
        begin
          if RXMLList[i].Attributes['ID'] <> FBMatchList[j].ID then Continue;

           SetLength(FBMatchList[j].Sales,1);

           FBMatchList[j].Sales[0].LotteryType := RXMLList[i].ChildNodes[0].Attributes['code'];
           FBMatchList[j].GivenScore := RXMLList[i].ChildNodes[0].ChildValues['GoalLine'];
           FBMatchList[j].Sales[0].IsDGSale := RXMLList[i].ChildNodes[0].ChildNodes[1].ChildValues['Single'];
           FBMatchList[j].Sales[0].IsGGSale := RXMLList[i].ChildNodes[0].ChildNodes[1].ChildValues['Allup'];
          Break;
        end;
      end;

    except on E : Exception do
      begin
        MainForm.LogInfo('获取竞彩足球让分情况出错,原因:' + E.Message, True);
        Result := False;
        Exit;
      end;
    end;
  finally
    ResponseXML.Free;
  end;
end;

 }


function TJCMatchThd.SaveData: Boolean;
var
  i, j,SucCount , iBBMatchCount, iFBMatchCount, iSalesCount, iReturnCode: Integer;
  sSQLString, sDGSales, sGGSales: string;
  insFlag : Boolean;  // 针对混合过关场次的问题
  sLotMacthId : string;
  sMatchRet,sTmp : string;
  iNoChangeNum:Integer;
begin
  Result := False;
  i:=1;
  iNoChangeNum:=0;
  while True do      //2015-02-05 liping.chen  设置失败时 允许多次设置,直到成功。
  begin
    try
      mqMain.Close;
      //sSQLString := 'TRUNCATE TABLE TRANSIT_LOTTERY_MATCH; SET NAMES GB2312;';
      sSQLString := ' SET NAMES GB2312;';
      mqMain.SQL.Text := sSQLString;
      mqMain.Execute;
      Break;
    except on E : Exception do
      begin
        MainForm.LogInfo('执行SET NAMES GB2312异常第'+IntToStr(i)+'次! ', True);
        inc(i);
        if i=4 then
          Exit;   //词句必须,若未设置完成,就会存进乱码,
        Sleep(50);
      end;
    end;
  end;

  iBBMatchCount := Length(BBMatchList);
  iFBMatchCount := Length(FBMatchList);
  if hsl_Match.Count > 1500 then
    hsl_Match.Clear;

  //============================篮彩============================
  try
    MainForm.LogInfo('准备写入竞篮对阵 共' +inttostr(iBBMatchCount)+'', True);
    SucCount := 0 ;
    for i := 0 to iBBMatchCount - 1 do
    begin
      iSalesCount := Length(BBMatchList[i].Sales);
      // 2013-04-09 rulinzhang 第一次需要保存
      insFlag := true;
      for j := 0 to iSalesCount - 1 do
      begin
        //if (not BBMatchList[i].Sales[j].IsDGSale) and (not BBMatchList[i].Sales[j].IsGGSale) then Continue;  //2014-12-15 liping.chen
        if BBMatchList[i].Sales[j].IsDGSale then sDGSales := '1'
          else sDGSales := '0';
        if BBMatchList[i].Sales[j].IsGGSale then sGGSales := '1'
          else sGGSales := '0';
        // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
        sLotMacthId := 'LQ' + '-' + BBMatchList[i].Sales[j].LotteryType + '-' + BBMatchList[i].ID;
        sMatchRet := BBMatchList[i].Sales[j].LotteryType
                      + '^' + BBMatchList[i].ID
                      + '^' + BBMatchList[i].MatchIndex
                      + '^' + DateTimeToStr(BBMatchList[i].MatchTime)
                      + '^' + sDGSales
                      + '^' + sGGSales
                      + '^' + BBMatchList[i].HomeTeam
                      + '^' + BBMatchList[i].AwayTeam
                      + '^' + FloatToStr(BBMatchList[i].GivenScore)
                      + '^' + FloatToStr(BBMatchList[i].PresetScore);
        // 判断hashed是否存在
        sTmp := trim(hsl_Match.Values[trim(sLotMacthId)]);
        if sTmp = '' then
          hsl_Match.Add(trim(sLotMacthId) + '=' + sMatchRet)
        else
        begin
          if sTmp = Trim(sMatchRet) then
          begin
            //MainForm.LogInfo('【竞篮赛程】无变更:' + sMatchRet, True);
            inc(iNoChangeNum);
            Continue;   // 退出
          end
          else
            hsl_Match.Values[trim(sLotMacthId)] := Trim(sMatchRet);
        end;
        // ---------------------------------------------------------------------
        sSQLString := 'CALL P_TRANSIT_LOTTERY_MATCH('
            + BBMatchList[i].Sales[j].LotteryType
            + ',' + QuotedStr(BBMatchList[i].ID)
            + ',' + QuotedStr(BBMatchList[i].MatchIndex)
            + ',' + QuotedStr(DateTimeToStr(BBMatchList[i].MatchTime))
            + ',' + sDGSales
            + ',' + sGGSales
            + ',' + QuotedStr(BBMatchList[i].HomeTeam)
            + ',' + QuotedStr(BBMatchList[i].AwayTeam);

        if BBMatchList[i].Sales[j].LotteryType = '46' then        //让分胜负
          sSQLString := sSQLString + ',' + FloatToStr(BBMatchList[i].GivenScore)+',null'
        else if BBMatchList[i].Sales[j].LotteryType = '48' then   //大小分
          sSQLString := sSQLString + ',null,' + FloatToStr(BBMatchList[i].PresetScore)
        else
          sSQLString := sSQLString + ',null,null';
        sSQLString := sSQLString +',@a); select @a;';

        try
          mqMain.Close;
          mqMain.SQL.Text := sSQLString;
          mqMain.Execute;
          iReturnCode := mqMain.Fields.Fields[0].AsInteger;
          mqMain.Close;
        except on E : Exception do
          begin
            MainForm.LogInfo('竞篮对阵'+BBMatchList[i].MatchIndex+'场次写入失败! '+ E.Message, True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
            mqMain.Close;
          end;
        end;

        if iReturnCode = 1 then              //数据验证失败
        begin
          MainForm.LogInfo('写入竞篮对阵失败,原因:数据验证失败', True);
          hsl_Match.Values[trim(sLotMacthId)] :='';
          //Exit;
        end
        else if iReturnCode = 100 then
        begin
          MainForm.LogInfo('写入竞篮对阵失败,原因:未知错误', True);
          hsl_Match.Values[trim(sLotMacthId)] :='';
          //Exit;
        end;

      end;
      // 独立处理竞篮混合过关
      if insFlag then       // 此时已经可以撤销该标志了
      begin
        // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
        sLotMacthId := 'LQ' + '-49-' + BBMatchList[i].ID;
        sMatchRet :=  IntToStr(49)
                      + '^' + BBMatchList[i].ID
                      + '^' + BBMatchList[i].MatchIndex
                      + '^' + DateTimeToStr(BBMatchList[i].MatchTime)
                      + '^' + '1'
                      + '^' + '1'
                      + '^' + BBMatchList[i].HomeTeam
                      + '^' + BBMatchList[i].AwayTeam;
        // 判断hashed是否存在
        sTmp := trim(hsl_Match.Values[trim(sLotMacthId)]);
        if sTmp = '' then
          hsl_Match.Add(trim(sLotMacthId) + '=' + sMatchRet)
        else
        begin
          if sTmp = Trim(sMatchRet) then
          begin
            //MainForm.LogInfo('【竞篮赛程】无变更:' + sMatchRet, True);
            Continue;   // 退出
          end
          else
            hsl_Match.Values[trim(sLotMacthId)] := Trim(sMatchRet);
        end;
        // ---------------------------------------------------------------------
        sSQLString := 'CALL P_TRANSIT_LOTTERY_MATCH(49'
          + ',' + QuotedStr(BBMatchList[i].ID)
          + ',' + QuotedStr(BBMatchList[i].MatchIndex)
          + ',' + QuotedStr(DateTimeToStr(BBMatchList[i].MatchTime))
          + ',' + '1'                                               //2014-12-15 liping.chen 固定为1
          + ',' + '1'
          + ',' + QuotedStr(BBMatchList[i].HomeTeam)
          + ',' + QuotedStr(BBMatchList[i].AwayTeam);
        sSQLString := sSQLString + ',null';
        sSQLString := sSQLString + ',null';
        sSQLString := sSQLString +',@a); select @a;';
        try
          mqMain.Close;
          mqMain.SQL.Text := sSQLString;
          mqMain.Execute;
          iReturnCode := mqMain.Fields.Fields[0].AsInteger;
          mqMain.Close;
          if iReturnCode = 1 then              //数据验证失败
          begin
            MainForm.LogInfo('写入竞篮混合对阵失败 49,原因:数据验证失败', True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
           // Exit;
          end
          else if iReturnCode = 100 then
          begin
            MainForm.LogInfo('写入竞篮混合对阵失败 49,原因:未知错误', True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
           // Exit;
          end;
          insFlag := false;
        except on E : Exception do
          begin
            MainForm.LogInfo('写入竞篮混合'+sLotMacthId+'异常!'+E.Message, True);
            // 若捕获,说明该场次没有存储成功,清空哈希对应的值
            hsl_Match.Values[trim(sLotMacthId)] :='';
          end;
        end;
      end;
      SucCount := SucCount + 1 ;
    end;

    iNoChangeNum:=iNoChangeNum div 4; //一场次存储彩种45、46、47、48 时 iNoChangeNum都累加了。
    MainForm.LogInfo('已写入竞篮对阵'+IntToStr(SucCount)+'场;无变更'+ IntToStr(iNoChangeNum)+''+#13#10, True);
  except on E : Exception do
    MainForm.LogInfo('已写入竞彩篮球对阵失败!'+E.Message, True);
  end;

  //============================足彩============================
  try
    SucCount := 0 ;
    iNoChangeNum:=0;
    MainForm.LogInfo('准备写入竞足对阵 共' +inttostr(iFBMatchCount)+'', True);
    for i := 0 to iFBMatchCount - 1 do
    begin
      iSalesCount := Length(FBMatchList[i].Sales);
      insFlag := True;
      for j := 0 to iSalesCount - 1 do            //2014-12-15 liping.chen
      begin
        //if (not FBMatchList[i].Sales[j].IsDGSale) and (not FBMatchList[i].Sales[j].IsGGSale) then Continue;
        if FBMatchList[i].Sales[j].IsDGSale then sDGSales := '1'
          else sDGSales := '0';
        if FBMatchList[i].Sales[j].IsGGSale then sGGSales := '1'
          else sGGSales := '0';
        // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
        sLotMacthId := 'ZQ' + '-' + FBMatchList[i].Sales[j].LotteryType + '-' + FBMatchList[i].ID;
        sMatchRet := FBMatchList[i].Sales[j].LotteryType
                    + '^' + trim(FBMatchList[i].ID)
                    + '^' + trim(FBMatchList[i].MatchIndex)
                    + '^' + DateTimeToStr(FBMatchList[i].MatchTime)
                    + '^' + sDGSales
                    + '^' + sGGSales
                    + '^' + trim(FBMatchList[i].HomeTeam)
                    + '^' + trim(FBMatchList[i].AwayTeam)
                    + '^' + FloatToStr(FBMatchList[i].GivenScore);
        // 判断hashed是否存在
        sTmp := trim(hsl_Match.Values[trim(sLotMacthId)]);
        if sTmp = '' then
          hsl_Match.Add(trim(sLotMacthId) + '=' + sMatchRet)
        else
        begin
          if sTmp = Trim(sMatchRet) then
          begin
            //MainForm.LogInfo('【竞足赛程】无变更:' + sMatchRet, True);
            inc(iNoChangeNum);
            Continue;   // 退出
          end
          else
            hsl_Match.Values[trim(sLotMacthId)] := Trim(sMatchRet);
        end;
        // ---------------------------------------------------------------------
        sSQLString := 'CALL P_TRANSIT_LOTTERY_MATCH('
            + FBMatchList[i].Sales[j].LotteryType
            + ',' + QuotedStr(FBMatchList[i].ID)
            + ',' + QuotedStr(FBMatchList[i].MatchIndex)
            + ',' + QuotedStr(DateTimeToStr(FBMatchList[i].MatchTime))
            + ',' + sDGSales
            + ',' + sGGSales
            + ',' + QuotedStr(FBMatchList[i].HomeTeam)
            + ',' + QuotedStr(FBMatchList[i].AwayTeam);

        if FBMatchList[i].Sales[j].LotteryType = '70' then    //让分胜平负
          sSQLString := sSQLString + ',' + FloatToStr(FBMatchList[i].GivenScore)
        else
          sSQLString := sSQLString + ',null';
        sSQLString := sSQLString +',null,@a); select @a;';

        try
          mqMain.Close;
          mqMain.SQL.Text := sSQLString;
          mqMain.Execute;
          iReturnCode := mqMain.Fields.Fields[0].AsInteger;
          mqMain.Close;
        except on E : Exception do
          begin
            MainForm.LogInfo('竞足对阵'+FBMatchList[i].MatchIndex+'场次写入失败!'+ E.Message, True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
            mqMain.Close;
          end;
        end;

        if iReturnCode = 1 then              //数据验证失败
        begin
          MainForm.LogInfo('写入竞足对阵失败,原因:数据验证失败', True);
          hsl_Match.Values[trim(sLotMacthId)] :='';
          //Exit;
        end
        else if iReturnCode = 100 then
        begin
          MainForm.LogInfo('写入竞足对阵失败,原因:未知错误', True);
          hsl_Match.Values[trim(sLotMacthId)] :='';
          //Exit;
        end;
      end;

      // 独立处理足球混合过关
      if insFlag then
      begin
        // 判断本次获取的数据,是否与上次一致,如果一致不进行保存
        sLotMacthId := 'ZQ' + '-76-' + FBMatchList[i].ID;
        sMatchRet := IntToStr(76)
                    + '^' + trim(FBMatchList[i].ID)
                    + '^' + trim(FBMatchList[i].MatchIndex)
                    + '^' + DateTimeToStr(FBMatchList[i].MatchTime)
                    + '^' + '1'
                    + '^' + '1'
                    + '^' + trim(FBMatchList[i].HomeTeam)
                    + '^' + trim(FBMatchList[i].AwayTeam);
        // 判断hashed是否存在
        sTmp := trim(hsl_Match.Values[trim(sLotMacthId)]);
        if sTmp = '' then
          hsl_Match.Add(trim(sLotMacthId) + '=' + sMatchRet)
        else
        begin
          if sTmp = Trim(sMatchRet) then
          begin
            //MainForm.LogInfo('【竞足赛程】无变更:' + sMatchRet, True);
            Continue;   // 退出
          end
          else
            hsl_Match.Values[trim(sLotMacthId)] := Trim(sMatchRet);
        end;
        // ---------------------------------------------------------------------
        sSQLString := 'CALL P_TRANSIT_LOTTERY_MATCH('
          + IntToStr(76)
          + ',' + QuotedStr(FBMatchList[i].ID)
          + ',' + QuotedStr(FBMatchList[i].MatchIndex)
          + ',' + QuotedStr(DateTimeToStr(FBMatchList[i].MatchTime))
          + ',' + '1'
          + ',' + '1'
          + ',' + QuotedStr(FBMatchList[i].HomeTeam)
          + ',' + QuotedStr(FBMatchList[i].AwayTeam);
        //让分胜平负
        sSQLString := sSQLString + ',' + FloatToStr(FBMatchList[i].GivenScore);
        sSQLString := sSQLString +',null,@a); select @a;';
        try
          mqMain.Close;
          mqMain.SQL.Text := sSQLString;
          mqMain.Execute;
          iReturnCode := mqMain.Fields.Fields[0].AsInteger;
          mqMain.Close;
          if iReturnCode = 1 then              //数据验证失败
          begin
            MainForm.LogInfo('写入竞足混合对阵失败 76,原因:数据验证失败', True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
            //Exit;
          end
          else if iReturnCode = 100 then
          begin
            MainForm.LogInfo('写入竞足混合对阵失败 76,原因:未知错误', True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
            //Exit;
          end;
          insFlag := False;
        except on E : Exception do
          begin
            MainForm.LogInfo('写入竞足混合'+sLotMacthId+'异常!'+E.Message, True);
            hsl_Match.Values[trim(sLotMacthId)] :='';
          end;
        end;
      end;
      SucCount :=  SucCount + 1 ;
    end;

    iNoChangeNum:=iNoChangeNum div 5; //一场次存储彩种70,71,72,73,77 时 iNoChangeNum都累加了。
    MainForm.LogInfo('已写入竞足对阵'+IntToStr(SucCount)+'场;无变更'+ IntToStr(iNoChangeNum)+''+#13#10, True);
  except on E : Exception do
    MainForm.LogInfo('写入竞彩对阵失败,原因:' + E.Message, True);
  end;

//////////////////////////////////////////////////////////////////////////
  try
    sSQLString := 'CALL P_UPDATE_LOTTERY_MATCH';
    mqMain.Close;
    mqMain.SQL.Text := sSQLString;
    mqMain.Execute;
    mqMain.Close;
    //
    MainForm.LogInfo('写入更新竞彩对阵成功', True);
    Result := True;
  except on E : Exception do
    begin
      MainForm.LogInfo('写入更新竞彩对阵失败,原因:' + E.Message, True);
      Result := False;
     // Exit;
    end;
  end;
end;

function TJCMatchThd.GetLotteryType(aTypeName: string): string;
begin
  Result := LTypeList.Values[aTypeName];
end;

procedure TJCMatchThd.SetPause(const aIsPause: Boolean);
begin
  Pause := aIsPause;
end;

function TJCMatchThd.GetStopMatch: Boolean;
var
  idServer: TIdHTTP;
  i, j,iPos1, iPos2, iMatchCount: Integer;
  sResponse ,URLStr ,CountStr, IsNotStr: string;
  StarMatchList : TStringList;
begin
  Result := False ;
  StarMatchList := TStringList.Create;
  idServer := TIdHTTP.Create(nil);
  try
    CountStr := 'match_counts(' ;
    URLStr := 'http://info.sporttery.cn/football/info/fb_match_info.php?m=';
    try
      //sResponse := idServer.Get('http://info.sporttery.cn/football/match_list.php');
      sResponse := idServer.Get(MainForm.FBSMResultAddress);
      iPos1 := Pos(CountStr,sResponse) ;
      iPos2 := PosEx(''')',sResponse,ipos1+1);
      iMatchCount := StrToIntDef((Copy(sResponse,iPos1+Length(CountStr)+1,ipos2-iPos1-Length(CountStr)-1)),-1);

      if iMatchCount =-1 then
      begin
         MainForm.LogInfo('获取页面有误,页面内容为:' + sResponse , True);
         Exit;
      end;

      if iMatchCount > 0 then
      begin
        for  i :=0 to iMatchCount*2 -1 do
        begin
          iPos1 := Pos(URLStr, sResponse);
          sResponse := Copy(sResponse,iPos1+Length(URLStr),Length(sResponse)-iPos1-Length(URLStr)-1) ;
          iPos2 := Pos('" ',sResponse) ;
          IsNotStr :=   Copy(sResponse,0,iPos2-1) ;
          if Pos('=',IsNotStr)= 0 then
          begin
             StarMatchList.Add(Copy(sResponse,0,iPos2-1));
          end;
        end;
      end;

      for j := 0 to Length(FBMatchList)-1 do
      begin
        if  (StarMatchList.IndexOf(FBMatchList[j].ID) < 0) then
        begin
           FBStopMatchList.Add(FBMatchList[j].ID);
        end;
      end;
      //
      MainForm.LogInfo('抓取停赛数据成功', True);
      Result := True ;
    except on E : Exception do
      begin
        MainForm.LogInfo('抓取停赛数据失败 原因:' + E.Message, True);
        Exit;
      end;
    end;
  finally
    if idServer <> nil then idServer.Free;
    StarMatchList.Free;
  end;
end;

function TJCMatchThd.SaveDateStopMatch: Boolean;
var
  k, iFBMatchCount  : integer ;
  StopMatchNo,sSQLString : string ;
begin
  //////////////////////////////写入竞彩足球停赛数据///////////////////////////////
  Result := False ;
  try
    iFBMatchCount :=  Length(FBMatchList);
    for k := 0 to iFBMatchCount -1 do
    begin
      if (FBStopMatchList.IndexOf(FBMatchList[k].ID) >= 0) then
      begin
         StopMatchNo :=  StopMatchNo + ','  + FBMatchList[k].ID ;
      end;
    end;
    //
    StopMatchNo := Copy(StopMatchNo,2,Length(StopMatchNo)-1);
    StopMatchNo := QuotedStr(StringReplace(StopMatchNo,',','*',[rfReplaceAll]));
    //
    if StopMatchNo <> '' then
    begin
      sSQLString := ' CALL P_STOP_MATCH_FLAG( '+ StopMatchNo + ' ) ;' ;
      mqMain.Close;
      mqMain.SQL.Text := sSQLString;
      mqMain.Execute;
    end;
    MainForm.LogInfo('已写入竞彩足球停赛数据', True);
    result := True ;
  except on  e: Exception do
    begin
      MainForm.LogInfo('抓取停赛数据失败 原因:' + E.Message, True);
      Exit;
    end;
  end;
end;

// 获取篮球让分情况
function TJCMatchThd.GetBBGivenScore(MatchID,HomeTeam,Response: string): Real;
var
  idhttp : TIdHTTP ;
  //Response,
  RFStr,sGivenSco : string ;
  ipos2, ipos3 : Integer ;
begin
  Result := 0;
  sGivenSco:='"fixedodds":"';  //让分所在标识
  //2015-03-23 liping.chen 竞篮让分页面改版, 参数HomeTeam暂时保留,
  //idhttp := TIdHTTP.Create(nil);
  try
    try
      //2015-01-21 liping.chen 取消分多次频繁抓取网页。
     { MainForm.LogInfo('抓取篮球对阵让分情况', True);

      Response := idhttp.Get(MainForm.BBGivenScoreAddress);

      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(Response,'FileLQRFDate') then
        begin
          MainForm.LogInfo('保存竞彩篮球对阵让分页面成功', True);
        end;
      end;  }

      ipos2 := PosEx(MatchID,Response);
      if ipos2>0 then
      begin
        Response := Copy(Response,ipos2 + Length(MatchID),Length(Response)-ipos2-Length(MatchID)-1);
        ipos3:=PosEx(sGivenSco,Response);
        if ipos3>0 then
        begin
          ipos2:=PosEx('",',Response,ipos3+length(sGivenSco));
          RFStr:=Copy(Response,ipos3+length(sGivenSco),ipos2-ipos3-length(sGivenSco));
          if RFStr<>'' then
            Result:=StrToFloat(RFStr);
        end
        else
          MainForm.LogInfo('该ID场次已开售但查找让分标示位失败,请检查' , True);
      end
      else
        MainForm.LogInfo('该ID场次已开售但让分Json中查找ID标示位失败,请检查' , True);

      //-----------------------暂时保留
     { ipos2   :=  PosEx(HomeTeam,Response);

      Response :=   Copy(Response,ipos2 + Length(HomeTeam),Length(Response)-ipos2-Length(HomeTeam)-1);
      ipos3  :=  PosEx('</a>',Response);

      RFStr := Copy(Response,0,ipos3-1) ;

      ipos2 := PosEx('(',RFStr);
      if ipos2 > 0 then
      begin
        ipos3 := PosEx(')',RFStr);
        RFStr := StringReplace(Copy(RFStr,ipos2+1,ipos3-ipos2-1),'+','',[rfReplaceAll]);
        Result := StrToFloat(RFStr) ;
      end else
      begin
        //MainForm.LogInfo('抓取篮球对阵让分失败 ', True);
        Result := 0 ;
      end;   }
    except on E: Exception do
      begin
         MainForm.LogInfo('抓取篮球对阵让分失败 原因:' + E.Message, True);
         Result := 0;
         Exit;
      end;
    end;
  finally
    //idhttp.Free;
  end;

end;


// 获取篮球预设总分
function TJCMatchThd.GetBBPresetScore(MatchID ,AwayTeam,Response : string): Real;
var
  idhttp : TIdHTTP ;
  //Response,
  YSZFStr,sGivenSco : string ;
  ipos2, ipos3 : Integer ;
begin
  //idhttp := TIdHTTP.Create(nil);
  Result := 0;
  sGivenSco:='"fixedodds":"';  //让分所在标识
  //2015-03-23 liping.chen 竞篮让分页面改版, 参数HomeTeam暂时保留,
  try
    try
      //2015-01-21 liping.chen 取消分多次频繁抓取网页。
     { MainForm.LogInfo('抓取篮球对阵预设总分情况', True);
      Response := idhttp.Get(MainForm.BBPresetScoreAddress);
      //
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(Response,'FileLQYSZFDate') then
        begin
          MainForm.LogInfo('保存竞彩篮球对阵预设总分页面成功', True);
        end;

      end;  }

      ipos2 := PosEx(MatchID,Response);
      if ipos2>0 then
      begin
        Response := Copy(Response,ipos2 + Length(MatchID),Length(Response)-ipos2-Length(MatchID)-1);
        ipos3:=PosEx(sGivenSco,Response);
        if ipos3>0 then
        begin
          ipos2:=PosEx('",',Response,ipos3+length(sGivenSco));
          YSZFStr:=Copy(Response,ipos3+length(sGivenSco),ipos2-ipos3-length(sGivenSco));
          if YSZFStr<>'' then
            Result:=StrToFloat(YSZFStr);
        end
        else
          MainForm.LogInfo('该ID场次已开售但查找预设总分标示位失败,请检查' , True);
      end
      else
        MainForm.LogInfo('该ID场次已开售但预设总分Json中查找ID标示位失败,请检查' , True);

      //-------------------------
      {ipos3 :=  PosEx(awayTeam,Response);
      Response := Copy(Response,ipos3 + Length(awayTeam),Length(Response)-ipos3-Length(awayTeam)-1);
      ipos2  :=  PosEx('</a>',Response);
      if ipos2 <> 1  then
      begin
         Result := StrToFloat(copy(Response,0,ipos2-1));
      end else
      begin
        Result := 0;
      end; }
    except on E: Exception do
      begin
         MainForm.LogInfo('抓取篮球对阵预设总分失败 原因:' + E.Message, True);
         Exit;
      end;
    end;
  finally
    //idhttp.Free;
  end;
end;

function TJCMatchThd.GetFBGivenScore: Boolean;
var
  idhttp : TIdHTTP ;
  sResponse,sID,RFStr : string ;
  ipos1, ipos2,i : Integer ;
  StrLog,sGivenSco : string ;
  iFlagNum1,iFlagNum2:Integer;
begin
  Result := False ;
  idhttp := TIdHTTP.Create(nil);
  idhttp.ConnectTimeout:=15000;    //2015-02-05 liping.chen
  idhttp.ReadTimeout:=15000;
  StrLog:=':{"id":"';   //每场开始标识
  sGivenSco:='"fixedodds":"';  //让分所在标识
  try
    try
      //从http://info.sporttery.cn/football/hhad_list.php 网页分析一下 数据源网址:
      //完整url:=http://i.sporttery.cn/odds_calculator/get_odds?i_format=json&i_callback=getDat&poolcode[]=hhad&poolcode[]=had&_=1418712667
      //url:=http://i.sporttery.cn/odds_calculator/get_odds?i_format=json&i_callback=getDat&poolcode[]=hhad 本例非让球的数据不取
      try
        MainForm.LogInfo('正在获取竞足对阵让分情况', True);
        sResponse := idhttp.Get(MainForm.FBGoalLineAddress);
      except on E : Exception do
        begin
          MainForm.LogInfo('idhttp.Get获取竞足对阵让分情况失败 '+ E.Message, True);
          Exit;
        end;
      end;
      if MainForm.IsSaveFile then
      begin
        if MainForm.SaveFile(sResponse,'FileZQRFDate') then
        begin
          MainForm.LogInfo('保存竞足对阵让分页面成功', True);
        end;
      end;
      //-------------------------  //20150226  添加易发现错误的判断机制 ID标示数要和让分标示数要相同
      iPos1 := 0;
      iFlagNum1:=0;
      iPos1:= Pos(StrLog, sResponse);
      while iPos1<> 0 do
      begin
        Inc(iFlagNum1);
        iPos1:= PosEx(StrLog, sResponse, iPos1+1);
      end;
      iPos1 := 0;
      iFlagNum2:=0;
      iPos1:= Pos(sGivenSco, sResponse);
      while iPos1<> 0 do
      begin
        Inc(iFlagNum2);
        iPos1:= PosEx(sGivenSco, sResponse, iPos1+1);
      end;
      if iFlagNum1<>iFlagNum2 then
      begin
        MainForm.LogInfo('获取竞足对阵让分时出错,ID与让分的标识数目不相同,请检查', True);
        Exit;
      end;
      //------------------------

      //ipos1 := Pos('"id":"',sResponse);   //新变动 "id":"改为  :{"id":"
      iPos1 := 0;
      ipos1 := Pos(StrLog,sResponse);
      if (iPos1 = 0)then
      begin
        MainForm.LogInfo('获取竞足对阵让分时出错,找不到标识字符串'+StrLog, True);
        Exit;
      end;


      while ipos1 >0 do
      begin
        //官方编号
        ipos2:=PosEx('"',sResponse,ipos1+length(StrLog));
        sID:= Copy(sResponse,ipos1+length(StrLog),ipos2-ipos1-length(StrLog));
        //让分
        ipos1:=PosEx(sGivenSco,sResponse,ipos2);
        ipos2:=PosEx('",',sResponse,ipos1+length(sGivenSco));
        RFStr:=Copy(sResponse,ipos1+length(sGivenSco),ipos2-ipos1-length(sGivenSco));
        for i := 0 to Length(FBMatchList)-1 do
        begin
          if (FBMatchList[i].ID = sID) and (RFStr<>'') then
          begin
            FBMatchList[i].GivenScore := StrToInt(RFStr);
            Break;
          end;
        end;
        sResponse := Copy(sResponse,iPos2,Length(sResponse) - iPos2 +1);  //添加截短
        ipos1 := PosEx(StrLog,sResponse,1);
      end;
      Result:=True;
    except on E: Exception do
      begin
         MainForm.LogInfo('抓取竞足对阵让分失败 原因:' + E.Message, True);
         Result :=False;
         Exit;
      end;
    end;
  finally
    idhttp.Free;
  end;
end;

end.
竞彩对阵

 

posted @ 2015-05-12 20:41  海蓝7  阅读(241)  评论(0编辑  收藏  举报