// Скрипт импорта накладной из Фармкомплект

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком
const UseOutPrice = false; // определяет, нужно ли использовать поле "цена розницы"


var
    Header :TStringList; // предопределена приложением
    Data :TStringList; // предопределена приложением
    ExportAgent :string; // все определены приложением
    FileName :string;

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;
    EXPORTNAKLADSROK :string;

var Table :TTable;
    num_doc :string;
    Item :variant;
    i,k :integer;
    OpenDialog :TOpenDialog;
    ThF :TField;
    str,str1 :string;
    Field :TField;
    FPrice_Reg :TField;
    FBarcode :TField;

    str1val :string;

    List :TStringList;
    List1 :TSTringList;
    List2 :Tstringlist;

    FSrokSertif, FSrok, FAmount, FNDS, FNameGoods,
    FFirstPrice,  FSeria, FSertif, FDateSertif, FTamog,
    FCountry, FRegN, FPrice, FNameProducer, FNameSertif,FPriceRosn,thf_ndoc,thf_datedoc :TField;

    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    end;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;

    procedure AddStr(var Destination :string; FieldNameList :tstringLIst; const FieldName :string; FieldValueList :TStringlist);
    var j :integer;
    begin
      j := FieldNameList.indexof(FieldName);
      //createhint('i='+inttostr(i)+',Name =' +FieldName+',NC ='+inttostr(FieldNamelist.count)+', VC='+inttostr(fieldvaluelist.count));
      if (j>=0) and (FieldValueList.count>J)
      then Destination := Destination + FieldValueList[j];
      Destination := Destination + #9;
    end;

    procedure AddStr1(var Destination :string; const thField :tField);
    begin
      if thField<>nil
      then begin
        Destination := Destination + thField.asstring;
        //createhinti(thfield.fieldname+':'+ thfield.asstring);
      end;

      Destination := Destination + #9;
    end;


    function FindField(const Table :tDataset; const FieldNames :string; const FieldDescription :string) :TField;
    var List :TstringList;
        i :integer;
    begin
       result := nil;
       List := tstringlist.create;
       try
          stringtolist(FieldNames,List,';,');
          if list.count=0 then RaiseException('не указаны имена полей в функции FindField');

          for i := 0 to List.count-1 do
          begin
            Result := Table.findfield(List[i]);
            if result<>nil then break;
          end;
          if (Result=nil) and (FieldDescription>'') then RaiseException('не найдено поле "'+FieldDescription+'" ('+FieldNames+')');
       finally
          List.free;
       end;

    end;


 begin
     //FileName := '';
     if filename = ''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring('plugins_import_invoice_farmkomplekt','filename','');
         opendialog.initialdir := extractfilepath(opendialog.filename);
         OpenDialog.Filter := 'Файлы-накладные(*.dbf)|*.dbf|Все файлы(*.*)|*.*';
         while  OpenDialog.execute do begin
           if not fileexists(OpenDialog.FileName) then CreateHint('Укажите правильно файл ')
           else begin
             Filename := OpenDialog.FileName;
             AppIniFile.writestring('plugins_import_invoice_farmkomplekt','filename',OpenDialog.filename);
             break;
           end;
         end;
       finally
         OpenDialog.free;
       end;
     end;

     if FileName = '' then exit;

     with TMyWait.create('Идет импорт накладной') do
     try

       if uppercase(extractfileext(filename))='.DBF'
       then begin

         Table := TTable.Create(nil);
         try

          table.tabletype := ttFoxpro;

          Table.TableName := gettempdir + extractfilename(FileName);
          filedelete(Table.tablename);
          Table.tabletype := ttfoxpro;
          copyfile(FileName,Table.TableName,False);
          //SetTableLangDriver(Table,'db866ru0');
         // CheckDBFCP(Table.TableName,38); //866DOS

          Table.Open;
          Table.First;
          
          

          if  table.findfield('n_nacl') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('n_nacl').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('d_nacl').asstring;
          
             Header.Values[ExportSkladName] := table.fieldbyname('apteka').asstring;


          data.Clear;

          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          data.Add('srok'+#9+'sroksertif'+#9+'sertifname'+#9+
            'kol'+#9+'nds'+#9+
            'name'+#9+'firstcena'+#9+'seria'+#9+'sertif'+#9+
            'producername'+#9+
            'datesertif'+#9+
            'tamog'+#9+
            'countryname'+#9+
            'regn'+#9+ //+'cenanotnds'
            'barcode'+#9+'summa'+#9+'price_reg'+str1val);

          FPrice_reg := findfield(table,'price_rees','');

          if UseBarcode then
            FBarcode := findfield(table,'scancod;barcode1;barcode;ean13','')
          else
            FBarcode := nil;

          FNameGoods := findfield(table,'NAME','Наименование товара');
          FNameProducer := findfield(table,'FACTORY','Производитель');
          FCountry := findfield(table,'country','Страна-производитель');
          FAmount := findfield(table,'quantity','Количество');
          FSeria := findfield(table,'series','Серия');
          fsrok := findfield(table,'date_valid', 'Срок годности');
          FTamog :=findfield(table,'gtd','Номер таможенной декларации');
          FSertif := findfield(table,'sert','Сертификат');
          FDateSertif := findfield(table,'date_s;DATEGIVE','' {'Дата выдачи сертификата' в третьем варианте поля не нашел});
          FNameSertif := findfield(table,'sertwho;ORGANGIVE','Сертифицирующий орган');
          FRegn := nil; //findfield(table,'regnumber','');
          FNDS := findfield(table,'nds_pr','Ставка НДС');
          FFirstPrice := findfield(table,'price_make','Цена производителя'); // третий вариант - под вопросом: я не нашел поле, отвечающее за цену производителя, вставил цену реестра
          FPrice := findfield(table,'summa;SUMWNDS','Сумма за товар с ндс');
          FSrokSertif := findfield(table,'datevalids;DEND','Дата окончания сертификата');  
          FBarcode := findfield(table,'SCANCOD','Штрихкод');
          FPrice_Reg := findfield(table,'PRICE_REES','Цена Реестра');
          fpricerosn := nil; //findfield(table,'price_rozn','');


          while not Table.eof do begin

            str := '';

            addstr1(str,fsrok);
            addstr1(str,fsroksertif);
            addstr1(str,FNameSertif);
            addstr1(str,FAmount);
            addstr1(str,FNDS);
            addstr1(str,fnamegoods);
            addstr1(str,FFirstPrice);
            addstr1(str,Fseria);
            addstr1(str,FSertif);
            addstr1(str,FNameProducer);
            addstr1(str,FDateSertif);
            addstr1(str,FTamog);
            addstr1(str,FCountry);
            addstr1(str,FREGN);
            addstr1(str,FBarcode);
            addstr1(str,FPrice);
            addstr1(str,FPrice_Reg);

            if useoutprice
            then addstr1(str,fpricerosn);

            data.Add(str);
            Table.Next;
          end;
          end
  //*******************************************************************************
  else
  if  table.findfield('NDOC') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('NDOC').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('DATEDOC').asstring;
          


          data.Clear;

          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          data.Add('srok'+#9+'sroksertif'+#9+'sertifname'+#9+
            'kol'+#9+'nds'+#9+
            'name'+#9+'firstcena'+#9+'seria'+#9+'sertif'+#9+
            'producername'+#9+
            'datesertif'+#9+
            'tamog'+#9+
            'countryname'+#9+
            'regn'+#9+ //+'cenanotnds'
            'barcode'+#9+'summa'+#9+'price_reg'+str1val);

          FPrice_reg := findfield(table,'REGPRC','');

          if UseBarcode then
            FBarcode := findfield(table,'EAN13','')
          else
            FBarcode := nil;


          FNameGoods := findfield(table,'NTOV','Наименование товара');
          FNameProducer := findfield(table,'NPROIZ','Производитель');
          FCountry := findfield(table,'NSTRANA','Страна-производитель');
          FAmount := findfield(table,'KOLVO','Количество');
          FSeria := findfield(table,'NSER','Серия');
          fsrok := findfield(table,'SROKG', 'Срок годности');
          FTamog :=findfield(table,'gtd','Номер таможенной декларации');
          FSertif := findfield(table,'NUMSERT','Сертификат');
          FDateSertif := findfield(table,'DATASERT','' {'Дата выдачи сертификата' в третьем варианте поля не нашел});
          FNameSertif := findfield(table,'ORGANSERT','Сертифицирующий орган');
          FRegn := nil; //findfield(table,'regnumber','');
          FNDS := findfield(table,'STAVNDS','Ставка НДС');
          FFirstPrice := findfield(table,'PROCEBZNDS','Цена производителя'); // третий вариант - под вопросом: я не нашел поле, отвечающее за цену производителя, вставил цену реестра

          FPrice := findfield(table,'SUMSNDS','Сумма за товар с ндс');
          FSrokSertif := findfield(table,'DATASERTDO','Срок действия сертификата');



          fpricerosn := nil; //findfield(table,'price_rozn','');


          while not Table.eof do begin

            str := '';

            addstr1(str,fsrok);
            addstr1(str,fsroksertif);
            addstr1(str,FNameSertif);
            addstr1(str,FAmount);
            addstr1(str,FNDS);
            addstr1(str,fnamegoods);
            addstr1(str,FFirstPrice);
            addstr1(str,Fseria);
            addstr1(str,FSertif);
            addstr1(str,FNameProducer);
            addstr1(str,FDateSertif);
            addstr1(str,FTamog);
            addstr1(str,FCountry);
            addstr1(str,FREGN);
            addstr1(str,FBarcode);
            addstr1(str,FPrice);
            addstr1(str,FPrice_Reg);

            if useoutprice
            then addstr1(str,fpricerosn);

            data.Add(str);
            Table.Next;
          end;
          end
            else
  if  table.findfield('NOMERDOC') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('NOMERDOC').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('DATADOC').asstring;
          


          data.Clear;

          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          data.Add('srok'+#9+'sroksertif'+#9+'sertifname'+#9+
            'kol'+#9+'nds'+#9+
            'name'+#9+'firstcena'+#9+'seria'+#9+'sertif'+#9+
            'producername'+#9+
            'datesertif'+#9+
            'tamog'+#9+
            'countryname'+#9+
            'regn'+#9+ //+'cenanotnds'
            'barcode'+#9+'summa'+#9+'price_reg'+str1val);

          FPrice_reg := findfield(table,'REESTR','');

          if UseBarcode then
            FBarcode := findfield(table,'BARCODE','')
          else
            FBarcode := nil;


          FNameGoods := findfield(table,'NAME','Наименование товара');
          FNameProducer := findfield(table,'PRODUCT','Производитель');
          FCountry := findfield(table,'STRANA','Страна-производитель');
          FAmount := findfield(table,'KOL','Количество');
          FSeria := findfield(table,'SERIA','Серия');
          fsrok := findfield(table,'SROKG', 'Срок годности');
          FTamog :=findfield(table,'GTD','Номер таможенной декларации');
          FSertif := findfield(table,'REGNOMER','Сертификат');
          FDateSertif := findfield(table,'DATASERT','' {'Дата выдачи сертификата' в третьем варианте поля не нашел});
          FNameSertif := findfield(table,'ORGAN','Сертифицирующий орган');
          FRegn := findfield(table,'REGNOMER','');
          FNDS := findfield(table,'PROCNDS','Ставка НДС');
          FFirstPrice := findfield(table,'PRODCOST','Цена производителя'); // третий вариант - под вопросом: я не нашел поле, отвечающее за цену производителя, вставил цену реестра

          FPrice := findfield(table,'SUMMA','Сумма за товар с ндс');
          FSrokSertif := findfield(table,'SERTDAT','Срок действия сертификата');



          fpricerosn := nil; //findfield(table,'price_rozn','');


          while not Table.eof do begin

            str := '';

            addstr1(str,fsrok);
            addstr1(str,fsroksertif);
            addstr1(str,FNameSertif);
            addstr1(str,FAmount);
            addstr1(str,FNDS);
            addstr1(str,fnamegoods);
            addstr1(str,FFirstPrice);
            addstr1(str,Fseria);
            addstr1(str,FSertif);
            addstr1(str,FNameProducer);
            addstr1(str,FDateSertif);
            addstr1(str,FTamog);
            addstr1(str,FCountry);
            addstr1(str,FREGN);
            addstr1(str,FBarcode);
            addstr1(str,FPrice);
            addstr1(str,FPrice_Reg);

            if useoutprice
            then addstr1(str,fpricerosn);

            data.Add(str);
            Table.Next;
          end;
  
         end; 
          
        //end;

          //data.savetofile('c:\temp\1.txt');

          //createhinti(table.tablename);

         finally
            Table.free;
         end;
       end
       else CreateHintE('Данный формат накладных от Фармкомпдект не исследован, обратитесь в техподдержку');

     finally
       free
     end;

     createhint('Операция завершена');
 end.
