// Ïðèíèìàåì ôàéë ðååñòðîâ öåí íàïðÿìóþ â ñîëÿðèñ ñ ñàéòà:
//http://grls.rosminzdrav.ru/PriceLims.aspx

const

  USEOLE = false;
  UseDialog = true;

const
    FMNN = 'ÌÍÍ';
    FName = 'Òîðãîâîå íàèìåíîâàíèå ëåêàðñòâå';
    FForm  = 'Ëåêàðñòâåííàÿ ôîðìà_ äîçèðîâêà_';
    FProducer = 'Âëàäåëåö ÐÓ_ïðîèçâîäèòåëü_óïàêî';
    FAmount = 'Êîëè__÷åñòâî â ïîòðåá_ óïàêîâ__';
    FPrice = 'Ïðåäåëüíàÿ öåíà ðóá_ áåç ÍÄÑ';
    FREG = '_ ÐÓ';
    FREGDTANDNUM='Äàòà ðåãèñòðàöèè öåíû___ ðåøåíè';
    FBARCODE='Øòðèõ_êîä _EAN13_';



function StrToVar(Value :string) :Variant;
begin
 if value = '' then result := null
 else result := Value
end;

function FloatToVar(Value :double) :variant;
begin
  if Value = 0 then result := null
  else result := value;
end;


var
    CDS :tclientDAtaset;
    ID :int64;
    ID1 :int64;
    StrVal1,StrVal2,strval,strval3 :string;
    i :integer;
    AddedCNT :integer;
    DeletedCNT :integer;
    DeletedRegCNT :integer;
    AddedCNTREG :integer;
    //IDCDS :TClientDAtaset;
    //Query :tpFibDataset;

    CDSID :tclientdataset;
    cdsdel :tclientdataset;

    nameval,formval,producerval,sertval,barcodeval,mnnval,regval :string;

    ImportFileName :string;
    Stream :TFileStream;
    Strings :TStringlist;

begin
   ImportFileName := '';

   cdsid := tclientdataset.create(selfscript);
   with cdsid do
   begin
     with fielddefs do
     begin
       clear;
       add('ID',ftlargeint,0,false);
     end;
     createdataset;
     logchanges := false;
   end;

   if not UseDialog or (GetConfirm('Ïðèíÿòü ñâåæèé ôàéë ñ ñàéòà rosminzdrav.ru?')=mrOk)
   then begin
     Strval1 := gettempdir + 'tempfile.zip';
     if fileexists(strval1) then deletefile(strval1);
     stream := TFileStream.create(strval1,fmCreate);
     strings := tstringlist.create;
     try
       with tmywait.create1('Çàãðóçêà ôàéëà',selfscript) do
       try

         if SynHttpGetText('http://grls.rosminzdrav.ru/PriceLims.aspx',Strings)
         then begin
             //<td id="ctl00_plate_tdzip" class="hi_sys" style="cursor:pointer"><a href='GetLimPrice.aspx?FileGUID=32ee3ad4-f2e7-434f-9f75-f4ddad25e334&UserReq=8684537'><img class='i1' src='forum/gfx/ext/zip.gif'/><br/>â ôàéëå ZIP<br/><span class='rdark'>(1,4 Ìá)</span><img class='i1' src='gfx/s0.gif'/></a></td>
             strval := strings.text;
             strval3 :='<td id="ctl00_plate_tdzip" class="hi_sys"';
             i := pos(strval3,strval);
             if i<=0
             then begin
               createhinte('Íå íàéäåíà ññûëêà íà ôàéë. Îáðàòèòåñü â òåõïîääåðæêó èëè ïîïðîáóéòå çàêà÷àòü ôàéë âðó÷íóþ');
               exit;
             end;

             strval := copy(strval,i+length(strval3),length(strval));
             strval3 :='<a href=''';
             i := pos(strval3,strval);
             if i<=0
             then begin
               createhinte('Íå íàéäåíà ññûëêà íà ôàéë. Îáðàòèòåñü â òåõïîääåðæêó èëè ïîïðîáóéòå çàêà÷àòü ôàéë âðó÷íóþ');
               exit;
             end;

             strval := copy(strval,i+length(strval3),length(strval));
             i := pos('&UserReq=',strval); //pos('''>',strval);

             if i<=0
             then begin
               createhinte('Íå íàéäåíà ññûëêà íà ôàéë. Îáðàòèòåñü â òåõïîääåðæêó èëè ïîïðîáóéòå çàêà÷àòü ôàéë âðó÷íóþ');
               exit;
             end;

             strval := 'http://grls.rosminzdrav.ru/'+copy(strval,1,i-1);

             //StringToFile('c:\temp\1.txt',strval);


             if SynHttpGetBinary(StrVal,Stream)
             then ImportFileName := strval1
             else createhinte('×òåíèå ôàéëà çàêîí÷èëîñü íåóäà÷åé. îáðàòèòåñü â òåõïîääåðæêó');
         end;
       finally
         free
       end;
     finally
       strings.free;
       stream.free;
     end;
   end
   else
   With TOpenDialog.create(SElfscript) do
   try
     initialdir := appinifile.readstring('importregistry','dir','');
     Title := 'Óêàæèòå ôàéë ðååñòðà';
     Filter := 'Ðååñòðû (xls,zip)|*.XLS;*.ZIP';


     if execute
     then begin
       appinifile.writestring('importregistry','dir',extractfilepath(filename));
       ImportFileName := Filename;
     end;
   finally
     free
   end;

   if importFilename<>'' then
   with TMyWait.create('Èäåò èìïîðò ôàéëà '+extractfilename(importfilename),SelfScript,{application.mainform} nil,true) do
   begin

       if uppercase(extractfileext(ImportFilename))='.ZIP'
       then begin
         AdvancedText :='Ðàñïàêîâêà ôàéëà';
         strval1 := ImportFilename;
         ImportFileName := GetTempDir + ZipExtractAll(ImportFilename,gettempdir);
         deletefile(strval1);
         text := 'Èäåò èìïîðò ôàéëà '+extractfilename(importfilename);
       end;

       if not fileexists(ImportFilename)
       then begin
         createhinte('Íå íàéäåí ôàéë '+ImportFilename);
         exit;
       end
       else if not UseDialog
       then
       if AppIniFile.Readstring('loadregistry','lastfilename','')=extractfilename(importfilename)
       then begin
         createhint('Ôàéë '+importfilename+' óæå ïðèíèìàëñÿ');
         exit
       end
       else begin
         AppIniFile.writestring('loadregistry','lastfilename',extractfilename(importfilename))
       end;


       AdvancedText :='×òåíèå ôàéëà èç Excel';

       cds := tclientdataset.create(selfscript);
       if not ReadXLS(cds,ImportFilename,UseOle,true, 2) then exit;
       deletefile(importfilename);

      // cds.savetofile('c:\temp\1.cds');


       if cds.findfield(FMNN) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FMNN+'"')
       else if cds.findfield(FName) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FName+'"')
       else if cds.findfield(FForm) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FForm+'"')
       else if cds.findfield(FProducer) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FProducer+'"')
       else if cds.findfield(FAmount) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FAmount+'"')
       else if cds.findfield(FPrice) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FPrice+'"')
       else if cds.findfield(FREG) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FREG+'"')
       else if cds.findfield(FREGDTANDNUM) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FREGDTANDNUM+'"')
       else if cds.findfield(FBARCODE) = nil then CreateHintE('Íå íàéäåíî ïîëå: "'+FBARCODE+'"')
       else begin



         //Query :=tpFibDataset.create(selfscript);
         //Query.Transaction := MainWriteTransaction;


         addedcnt := 0;
         AddedCNTREg := 0;

         progressbarmax:= cds.recordcount;
         cds.first;
         while not cds.eof do
         begin
            AdvancedText := 'Äîáàâëåíî: '+inttostr(AddedCNT)+' ñòðîê, ðååñòðîâ: '+inttostr(AddedCNTReg);
            application.processmessages;
            if stopped then begin
              createhintw('Îïåðàöèÿ çàãðóçêè ðååñòðà öåí îñòàíîâëåíà');
              exit;
            end;


            if cds.fieldbyname(fname).asstring>''
            then begin



              StrVal1 := cds.fieldbyname(fregdtandnum).asstring;
              i := pos('(',StrVal1);
              if i<=0
              then StrVAl2 := ''
              else begin
                StrVAl2 := copy(StrVal1,i+1,length(strval1));
                StrVal1 := copy(StrVAl1,1,i-1);
                i := pos(')',StrVal2);
                if i>0
                then StrVAl2 := copy(StrVal2,1,i-1);

              end;

              nameval := copy(cds.fieldbyname(fname).asstring,1,300);
              formval := copy(cds.fieldbyname(fform).asstring,1,200);
              producerval := copy(cds.fieldbyname(fproducer).asstring,1,300);
              mnnval := copy(cds.fieldbyname(fmnn).asstring,1,100);
              barcodeval := copy(cds.fieldbyname(fbarcode).asstring,1,20);
              regval := copy(cds.fieldbyname(freg).asstring,1,50);



              id:= asint64(DBQueryValue('select b.id '+
                            ' from registry a join registry_rows b on a.id  = b.id_registry'+
                            ' where a.dateregistry is not distinct from :dateregistry '+
                            ' and a.name is not distinct from :name_registry '+
                            ' and b.name is not distinct from :name '+
                            ' and b.form is not distinct from :form '+
                            ' and b.name_producers is not distinct from :name_producer'+
                            ' and b.price is not distinct from :price '+
                            ' and b.kolup is not distinct from :kolup '+
                            ' and b.mnn is not distinct from :mnn '+
                            ' and b.barcode is not distinct from :barcode '+
                            ' and b.nomer_sert is not distinct from :nomer_sert ',
                            [ strtodateprotected(StrVal1),
                              StrToVar(trim(StrVal2)),
                              FirstUppercase(trim(nameval)),
                              StrToVar(trim(formval)),
                              StrToVar(FirstUppercase(trim(producerval))),
                              FloatToVar(StrToFloatProtected(cds.fieldbyname(fPrice).asstring)),
                              strtofloatprotected(cds.fieldbyname(famount).asstring),
                              StrToVar(FirstUppercase(trim(mnnval))),
                              StrToVar(trim(barcodeval)),
                              StrToVar(trim(regval))
                            ]));

              if id=0
              then begin

                 {
                 stringtofile('c:\temp\1.txt',
                              'dateregistry:'+datetostr(strtodateprotected(StrVal1))+#13#10+
                              'name_registry:'+StrToVar(trim(StrVal2))+#13#10+
                              'name:'+FirstUppercase(trim(nameval))+#13#10+
                              'form:'+asstring(StrToVar(trim(formval)))+#13#10+
                              'name_producer:'+asstring(StrToVar(FirstUppercase(trim(producerval))))+#13#10+
                              'price:'+asstring(FloatToVar(StrToFloatProtected(cds.fieldbyname(fPrice).asstring)))+#13#10+
                              'kolup:'+floattostr(strtofloatprotected(cds.fieldbyname(famount).asstring))+#13#10+
                              'mnn:'+asstring(StrToVar(FirstUppercase(trim(mnnval))))+#13#10+
                              'barcode:'+asstring(StrToVar(trim(barcodeval)))+#13#10+
                              'nomer_sert:'+asstring(StrToVar(trim(regval)))
                           );
                 exit;
                 }
                 id := asint64(DBQueryValue('select id from registry '+
                                            ' where dateregistry is not distinct from :dateregistry '+
                                            ' and name is not distinct from :name',
                                            [ strtodateprotected(StrVal1),
                                              StrTovar(StrVal2)]));
                 if id = 0
                 then begin
                   if not mainwritetransaction.intransaction then MainWriteTransaction.StartTransaction;
                   id := asint64(FibExecSQLTR('insert into registry (isregistry,name,dateregistry,date_actual,dateinput,istochnik)'+
                             ' values (:isregistry,:name,:dateregistry,:date_actual,:dateinput,:istochnik) returning (ID)',
                             [0,
                               StrToVar(trim(StrVal2)),
                               strtodateprotected(StrVal1),
                               strtodateprotected(StrVal1),
                               date,
                               'grls.rosminzdrav.ru/PriceLims.aspx'
                              ],
                             MainWriteTransaction ));

                   MainWriteTransaction.Commit;

                   inc(addedcntreg);
                 end;

                 if not mainwritetransaction.intransaction then MainWriteTransaction.StartTransaction;
                 ID1 := asint64(FibExecSQLTR('insert into registry_rows (id_registry,name,form,name_producers,price,kolup,mnn,barcode,nomer_sert) '+
                            ' values  (:id_registry,:name,:form,:name_producer,:price,:kolup,:mnn,:barcode,:nomer_sert) returning (ID)',
                            [ ID,
                              FirstUppercase(trim(nameval)),
                              strToVar(trim(formval)),
                              StrToVar(FirstUppercase(trim(producerval))),
                              strtofloatprotected(cds.fieldbyname(fPrice).asstring),
                              strtofloatprotected(cds.fieldbyname(famount).asstring),
                              StrToVar(FirstUppercase(trim(mnnval))),
                              StrToVar(trim(barcodeval)),
                              StrToVar(trim(regval))
                            ],
                            MainWriteTransaction));

                 mainwritetransaction.commit;

                 cdsid.append;
                 cdsid.fieldbyname('id').aslargeint := id1;
                 cdsid.post;


                 inc(addedcnt);

              end
              else begin
                   cdsid.append;
                   cdsid.fieldbyname('id').aslargeint := ID;
                   cdsid.post;
              end;
            end;


            incprogress;
            cds.next;
         end;


         //createhinti('Ôàéë: '+extractfilename(importfilename)+ #13+AdvancedText,'',100);

         STrVal := AdvancedText;
         DeletedCNT := 0;
         cdsid.indexfieldnames := 'ID';

         dbreadquery(CDs,'select id from registry_rows',[null]);

         {
         cdsdel := tclientdataset.create(selfscript);
         with cdsdel do
         begin
           fielddefs.clear;
           fielddefs.add('id',ftlargeint,0,false);
           createdataset;
           logchanges := false;
         end;
         }


         cds.first;
         while not cds.eof do begin
           AdvancedText := 'Óäàëåíèå ñòàðûõ ñòðîê ðååñòðà ('+inttostr(DeletedCNT)+' íàéäåíî)';

           if not cdsid.findkey([cds.fieldbyname('id').aslargeint])
           then begin
             {
             cdsdel.append;
             cdsdel.fieldbyname('id').aslargeint := cds.fieldbyname('id').aslargeint;
             cdsdel.post;
             }

             dbexecsql('delete from registry_rows where id=:id',[cds.fieldbyname('id').aslargeint]);
             inc(deletedcnt);
           end;

           cds.next;

           application.processmessages;
           if stopped then begin
              createhintw('Îïåðàöèÿ çàãðóçêè ðååñòðà öåí îñòàíîâëåíà');
              exit;
           end;
         end;

         //cdsid.savetofile('c:\temp\1.cds');
         //cds.savetofile('c:\temp\2.cds');
         //cdsdel.savetofile('c:\temp\3.cds');



         AdvancedTExt := ' Óäàëåíèå ïóñòûõ ðååñòðîâ';

         dbreadquery(cds,'select a.id,count(b.id) from registry a left join registry_rows b on a.id = b.id_registry group by a.id having count(b.id)=0',[null]);
         DeletedRegCNT := cds.recordcount;

         cds.First;
         while not cds.eof do begin
           DBExecSQL('delete from registry where id=:id',[cds.fieldbyname('id').aslargeint]);
           AdvancedTExt := ' Óäàëåíèå ïóñòûõ ðååñòðîâ (óäàëåíî: '+inttostr(deletedregcnt)+')';
           cds.next;
           application.processmessages;
           if stopped then begin
              createhintw('Îïåðàöèÿ çàãðóçêè ðååñòðà öåí îñòàíîâëåíà');
              exit;
            end;
         end;

         createhinti('Ôàéë: '+extractfilename(importfilename)+ #13+StrVal+#13+'Óäàëåíî ñòðîê: '+inttostr(deletedCnt)+', ðååñòðîâ: '+inttostr(deletedregcnt) ,'',30);
       end;
   end;

end.
