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

const

  USEOLE = false;

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 :integer;
    maxID,maxID1 :integer;
    StrVal1,StrVal2,strval,strval3 :string;
    i :integer;
    AddedCNT :integer;
    DeletedCNT :integer;
    DeletedRegCNT :integer;
    AddedCNTREG :integer;
    //REGCDS :TClientDAtaset;
    Query :TQuery;

    CDSID :tclientdataset;

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

    ImportFileName :string;
    Stream :TFileStream;

    taREg,TaRegRows :TTable;

    Strings :TStringlist;
    StrVAl : string;
    TaProdCens :ttable;
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 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.create1('Èäåò èìïîðò ôàéëà '+extractfilename(importfilename),SelfScript) do
   begin
       TaReg := ttable.create(selfscript);
       taReg.databasename := 'dbkassa';
       taReg.tablename := 'prodcm';
       taReg.open;


       TaRegRows := ttable.create(selfscript);
       taRegRows.databasename := 'dbkassa';
       taRegRows.tablename :='prodcens';
       taReg.Open;

       Query := TQuery.create(selfscript);
       Query.databasename := 'dbkassa';

       //REGCDS:= TClientDataset.create(selfscript);

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

       if not fileexists(ImportFilename)
       then begin
         createhinte('Íå íàéäåí ôàéë '+ImportFilename);
         exit;
       end;


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

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

       //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.sql.text := 'select a.datereestr,a.descr,b.*'+
                            ' from prodcm a join prodcens b on a.id  = b.id_reestr';

          AdvancedText :='×òåíèå òåêóùåãî ðååñòðà öåí';

          Query.open;


          readdataset(regcds,Query);
          Query.close;


          regcds.indexfieldnames :='datereestr;descr;name;form;name_producer;cena;mnn;barcode';
          }


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


         addedcnt := 0;
         AddedCNTREg := 0;

         tareg.open;
         taReg.last;
         maxID := taReg.fieldbyname('id').asinteger;

         taregrows.open;
         taregrows.last;
         maxid1 := taregrows.fieldbyname('id').asinteger;

         Query.sql.text := 'select b.id '+
                        ' from prodcens b'+
                        ' where b.id_reestr = :id_reestr'+
                        ' and b.name = :name '+
                        ' and b.form = :form '+
                        ' and b.name_producer = :name_producer'+
                        ' and b.cena = :price '+
                        ' and b.mnn =:mnn '+
                        ' and b.barcode = :barcode ';
        // Query.prepare;



         progressbarmax:= cds.recordcount;
         cds.first;
         while not cds.eof do
         begin
            AdvancedText := 'Äîáàâëåíî: '+inttostr(AddedCNT)+' ñòðîê, ðååñòðîâ: '+inttostr(AddedCNTReg);


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



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

              end;

              mnnval := coalesce_string(trim(copy(cds.fieldbyname(fmnn).asstring,1,100)),'-');
              nameval := coalesce_string(trim(copy(cds.fieldbyname(fname).asstring,1,200)),'?-');
              formval := coalesce_string(trim(copy(cds.fieldbyname(fform).asstring,1,200)),'-');
              producerval := coalesce_string(trim(copy(cds.fieldbyname(fproducer).asstring,1,250)),'-');
              barcodeval := coalesce_string(trim(CorrectBarCode(copy(cds.fieldbyname(fbarcode).asstring,1,20),
                                     dbinifile.readbool('COMMON','BARCODEDEL13',true),
                                     false,
                                     true,
                                     false)),'-');
                                     

              regval := trim(copy(cds.fieldbyname(freg).asstring,1,50));


              id := asinteger(bdeQueryValue('select id from prodcm '+
                                            ' where datereestr = :dateregistry '+
                                            ' and descr = :name',
                                            [ strtodateprotected(StrVal1),
                                              StrVal2],'dbkassa'));

              Query.close;

              if id<>0
              then begin
                 Query.parambyname('id_reestr').asinteger := ID;
                 Query.parambyname('name').asstring := nameval;
                 Query.parambyname('form').asstring := formval;
                 Query.parambyname('name_producer').asstring := producerval;
                 Query.parambyname('price').asfloat := StrToFloatProtected(cds.fieldbyname(fPrice).asstring);
                 Query.parambyname('mnn').asstring := mnnval;
                 Query.parambyname('barcode').asstring := barcodeval;
                 Query.open;
              end;

              if  not Query.active or  Query.isempty // id=0
              then begin
                 {
                  showmessage(Query.parambyname('id_reestr').asstring+
                              ':'+Query.parambyname('name').asstring+
                              ':'+Query.parambyname('form').asstring+
                              ':'+Query.parambyname('name_producer').asstring+
                              ':'+Query.parambyname('price').asstring+
                              ':'+Query.parambyname('mnn').asstring+
                              ':'+Query.parambyname('barcode').asstring+
                              ':'
                              ); exit;
                 }
                 if id = 0
                 then begin


                   inc(maxid);
                   id := maxid;
                   tareg.open;
                   taReg.Append;
                   taReg.fieldbyname('id').asinteger := maxID;
                   taReg.fieldbyname('isreestr').asinteger := 0;
                   taReg.fieldbyname('datereestr').asdatetime := strtodateprotected(strval1);
                   taReg.fieldbyname('dateinput').asdatetime := date;
                   tareg.fieldbyname('descr').asstring := strval2;
                   taReg.fieldbyname('date_actual').asdatetime := date;
                   tareg.post;


                   inc(addedcntreg);
                 end;


                 inc(maxid1);
                 taregrows.open;
                 taregrows.append;
                 taregrows.fieldbyname('id').asinteger := maxid1;
                 taregrows.fieldbyname('id_reestr').asinteger := id;
                 taregrows.fieldbyname('cena').asfloat := strtofloatprotected(cds.fieldbyname(fPrice).asstring);
                 taregrows.fieldbyname('name').asstring := nameval;
                 taregrows.fieldbyname('form').asstring := formval;
                 taregrows.fieldbyname('name_producer').asstring := producerval;
                 taregrows.fieldbyname('barcode').asstring := barcodeval;
                 taregrows.fieldbyname('mnn').asstring := mnnval;
                 taregrows.post;

                 //showmessage(asstring(maxid1)+':'+asstring(id)+':'+cds.fieldbyname(fprice).asstring+':'+barcodeval+':'+nameval);

                 cdsid.append;
                 cdsid.fieldbyname('id').asfloat := maxid1;
                 cdsid.post;

                 //cdsid.savetofile('c:\temp\'+asstring(maxid1)+'.cds');

                 {
                 createhint(inttostr(maxid1));

                 if maxid1>100 then begin
                   cdsid.savetofile('c:\temp\2.cds');
                   exit;
                 end;
                 }

                 inc(addedcnt);

              end
              else begin
                Query.first;
                while not Query.eof do
                begin
                   cdsid.append;
                   cdsid.fieldbyname('id').asfloat := Query.fieldbyname('id').asfloat;
                   cdsid.post;
                   Query.next
                end;
              end;
            end;

            incprogress;
            cds.next;
            application.processmessages;
         end;

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

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

         taProdCens := ttable.create(selfscript);
         taProdcens.databasename := 'dbkassa';
         taprodcens.tablename := 'prodcens.db';
         taprodcens.open;
         taprodcens.first;
         while not taprodcens.eof do begin
           AdvancedText := 'Óäàëåíèå ñòàðûõ ñòðîê ðååñòðà ('+inttostr(DeletedCNT)+' íàéäåíî)';

           if not cdsid.findkey([taprodcens.fieldbyname('id').asfloat])
           then begin
             //showmessage(taprodcens.fieldbyname('id').asfloat);
             taprodcens.delete;
             inc(deletedcnt);
           end
           else
             taprodcens.next;
           //application.processmessages; âäðóã çàêðîåòñÿ
         end;

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

         Query.close;
         Query.sql.text := 'select a.id,count(b.id) from prodcm a left join prodcens b on a.id = b.id_reestr group by a.id having count(b.id)=0';
         Query.open;
         DeletedRegCNT := Query.recordcount;

         Query.First;
         while not Query.eof do begin
           BDEExecSQL('delete from prodcm where id=:id',[Query.fieldbyname('id').asfloat],'dbkassa');
           AdvancedTExt := ' Óäàëåíèå ïóñòûõ ðååñòðîâ (óäàëåíî: '+inttostr(deletedregcnt)+')';
           Query.next;
         end;

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

end.
