// Принимаем файл реестров цен напрямую в солярис с сайта:
//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.
