// скрипт сканирует файл XLS или ZIP, принятый с http://grls.rosminzdrav.ru/PriceLims.aspx
// и расставляет МНН во всех товарах, где совпали "торговое наименование" реестра
// и начало наименования в нашем справочнике

// В реестре на одно и то же торговое наименование будет нескольких вариантов,
// какой из них правильный - мы не знаем, поэтому, берем первый и расставляем во все наши наименования, остальные - не трогаем

// скрипт предложит скачать свежий файл с указанного ресурса.
// Если отказаться, то предложит взять файл с диска (предполагается, что скачали сами).
// При этом он съест как XLS, так и ZIP

// Скрипт сохранит результат работы в логе
// (TXT с табуляциями, удобно читать его процедурой "Администратор/Проверка данных (таблицы)/Чтение данных из внешнего файла"
// Имя и местоположение файла лога скрипт отобразит по окончанию работы

// поля в исходном справочнике
const
  FieldMNN = 'МНН';
  FieldTorgName = 'Торговое наименование лекарстве';

  MissStrings = 2; // пропустить строк. Если не нужно пропускать, то указать 0  (автоматический пропуск пустых) или -1 -ничего не пропускать

var
  CDS :TClientdataset;
  TAble :TTable;

  ImportFileName :string = '';
  strval :string;
  strval1 :string;
  strval2,strval3 :string;

  i :integer;

  stream :tfilestream;
  strings :tstringlist;

  changedcnt :integer=0;
  allcnt :integer = 0;
  DistinctCNT :integer = 0;

  Loglist :tstringlist;

  OldVal :string = '';
begin

   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('checkmnnscript','dir','');
     Title := 'Укажите файл реестра';
     Filter := 'Реестры (xls,zip)|*.XLS;*.ZIP';


     if execute
     then begin
       appinifile.writestring('checkmnnscript','dir',extractfilepath(filename));
       ImportFileName := Filename;
     end;
   finally
     free
   end;

  if importfilename='' then exit;

   if uppercase(extractfileext(importfilename))='.ZIP'
   then begin
    with tmywait.create1('Распаковка архива ',selfscript) do
    try
     importfileName := GetTempDir + ZipExtractAll(ImportFilename,gettempdir);
    finally
      free
    end;
   end;

   if not fileexists(ImportFilename)
   then begin
     createhinte('Не найден файл '+ImportFilename);
     exit;
   end;


  cds := tclientdataset.create(selfscript);
  LogList := tstringlist.create;
  try
    table := ttable.create(selfscript);

    table.tablename := 'tovar';
    table.databasename := 'dbkassa';
    table.open;
    table.indexfieldnames := 'name';

    with tmywait.create1('Идет перенос данных',selfscript) do
    try

      advancedtext := 'Открываем таблицы';

      ReadXLS(cds,importfileName,false,true,MissStrings);

      if cds.findfield(fieldmnn)=nil
      then raiseexception('Поле "'+FieldMNN+'" не найдено в полученной таблице');

      if cds.findfield(fieldTorgName)=nil
      then raiseexception('Поле "'+FieldTorgName+'" не найдено в полученной таблице');

      progressbarmax := cds.recordcount;

      cds.indexfieldnames := fieldtorgname;
      cds.first;

      advancedtext := 'Изменение данных в справочнике товаров';

      LogList.add('Торг.Наименование в реестре'+#9+'Наше наименование'#9+'Наш код товара'#9+'МНН в реестре'+#9+'Наше МНН');

      allcnt := cds.recordcount;


      while not cds.eof do begin

          {
          BDEExecSQL('update tovar set intername = :nm where upper(name) like :nm1',[
             cds.fieldbyname(FieldMNN).asstring,
             ansiuppercase(cds.fieldbyname(FieldTorgName).asstring)+'%',
             ],table.databasename);
          }

        strval := ansiuppercase(cds.fieldbyname(FieldTorgName).asstring);


        if (length(cds.fieldbyname(fieldmnn).asstring)>2) // бывает, что мнн не указан, либо прочерки какие-нибудь стоят
           and (cds.fieldbyname(fieldmnn).asstring<>'Нет')
           and (cds.fieldbyname(fieldmnn).asstring<>'_____')
           and (oldval<>strval) // одно и то же торг.наименование не смотрим дальше
        then begin
          oldval := strval;
          inc(distinctcnt);

          if not table.active
          then begin
            table.open;
            table.indexfieldnames := 'name';
          end;


          table.first;
          table.findnearest([strval]);
          while not table.eof and (pos(strval,ansiuppercase(table.fieldbyname('name').asstring))=1) do
          begin
            if trim(table.fieldbyname('intername').asstring) <>  trim(cds.fieldbyname(fieldmnn).asstring)
            then begin

              loglist.add(strval+#9+
                          table.fieldbyname('name').asstring+#9+
                          table.fieldbyname('NN').asstring+#9+
                          cds.fieldbyname(fieldmnn).asstring+#9+
                          table.fieldbyname('intername').asstring);


              table.edit;
              table.fieldbyname('intername').asstring := trim(cds.fieldbyname(fieldmnn).asstring);
              table.post;
              inc(changedcnt);
              advancedtext := 'Изменение данных в справочнике товаров, заменено '+inttostr(changedcnt)+' строк';
            end;
            table.next;
            application.processmessages;
          end;
        end;

        cds.next;
        incprogress;
        application.processmessages;

      end;


      CreateHintI('В реестре '+inttostr(allcnt)+' строк'+#13+
                  'Уникальных торг.наименований: '+ inttostr(DistinctCNT)+#13+
                  'Заменено '+inttostr(changedcnt)+' товаров',
                  'Процедура поиска торговых наименований завершена',1000);

      strval :=extractfilepath(application.exename)+'log_checkmnn.txt';
      loglist.savetofile(strval);
      CreateHintI('Результаты работы сохранены в логе : '+strval,
                  'Процедура поиска торговых наименований завершена',1000);



    finally
      free
    end;


  finally
    Loglist.free;
    cds.free;
  end;

end.
