// Импорт накладных из СИА (Саратов)

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком

var
    Header :TStringList; // предопределена приложением
    Data :TStringList; // предопределена приложением
    ExportAgent :string; // все определены приложением
    FileName :string;

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

var Table :TTable;
    num_doc :string;
    Item :variant;
    i :integer;
    OpenDialog :TOpenDialog;
    ThF_FIRSTPRICE, thF_FIRSTPRICEWNDS, thf_SROK,thF_SrokSertif,ThF_NameSertif,thF_Amount,thF_NDS,
    thF_Name,thF_Seria,thF_Sertif,thF_NameProducer,thf_Tamog,
    thF_Country,thF_Regn,thF_Price,thF_BarCode,thF_DateSertif,thF_Em :TField;
    thF_Price_Reg :TField;
    str,str1 :string;
    ipos :integer;
    Field :TField;

    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    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;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    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;


 begin
     //FileName := '';
     if filename = ''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring('plugins_sia','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_sia','filename',OpenDialog.filename);
             break;
           end;
         end;
       finally
         OpenDialog.free;
       end;
     end;

     if FileName = '' then exit;

     with TMyWait.create('Идет импорт накладной') do
     try

       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('num_nak')<>nil
        then begin
          Header.Values[ExportNakladNom] := table.fieldbyname('num_nak').asstring;
          Header.Values[ExportNakladData] := table.fieldbyname('date_nak').asstring;
        end
        else
        if table.findfield('num_doc')<>nil
        then begin
          Header.Values[ExportNakladNom] := table.fieldbyname('num_doc').asstring;
          Header.Values[ExportNakladData] := table.fieldbyname('date_doc').asstring;
        end
        else
        if table.findfield('DCODE')<>nil
        then begin
          Header.Values[ExportNakladNom] := table.fieldbyname('DCODE').asstring;
          Header.Values[ExportNakladData] := table.fieldbyname('DATE_DOC').asstring;
        end
        else
        if table.findfield('NDOC')<>nil
        then begin
          Header.Values[ExportNakladNom] := table.fieldbyname('NDOC').asstring;
          Header.Values[ExportNakladData] := table.fieldbyname('DATEDOC').asstring;
        end
        else
         begin
          raiseexception('Таблица имеет формат, не согласованный с поставщиком. Обратитесь в техподдержку');
        end;


        data.Clear;

        {
        list.Add('srok'#9'barcode'#9'sroksertif'#9'sertifname'#9+
          'upa'#9'nn'#9'article'#9'kart'#9'kol'#9'em'#9'rosn'#9'nds'#9'ed'#9+
          'name'#9'firstcena'#9'seria'#9'sertif'#9'analize'#9'producer'#9+
          'producername'#9'nalog5'#9'idanalize'#9'analizename'#9'datasertif'#9+
          'dateanalize'#9'reestrcena'#9'tamog'#9'producercountry'#9+
          'producercountryname'#9'maxprocent'#9'passport'#9'datepassport'#9+
          'sorti'#9'gost'#9'regn'#9'summa'#9'cena'#9'itogcena'#9'itogsumma');
        }


        thF_SROK :=  FindField(Table,'srok;SER_SROK;SROK_S;GOD_SERT',''); //Срок годности
        thF_SROKSERTIF := FindField(Table,'SROK;DSERT_END;SROK_S','');  //Срок действия сертификата
        thF_NAMESERTIF := FindField(Table,'string2;ORGAN_SERT','');  //Кем выдан сертификат
        thF_AMOUNT := FindField(Table,'volume;KOLVO;QNT','Количество единиц');
        thF_NDS := FindField(Table,'pct_nds;NDS_PR;NDS','Ставка НДС');
        thF_NAME := FindField(Table,'name_tovar;PREP_NAME;PRODUCT;NAME','Наименование товара');
        thF_FIRSTPRICEWNDS := FindField(Table, 'pr_proiz','');//Цена завода с НДС
        thF_FIRSTPRICE := FindField(Table, 'PRO_NNDS;PRICEMAN',''); //Цена завода БЕЗ НДС
        thF_Seria := FindField(Table,'seria;SERIES;SER','Серия');
        thF_Sertif := FindField(Table,'document;SERT_N;SERTIF','Сертификат');
        thF_NameProducer := FindField(Table,'proiz;MANUF_N;PRODUCER;FIRM','Производитель');
        thF_tamog := FindField(Table,'gtd;GTD;NUMGTD','Номер таможенной декларации');
        thf_country := findfield(table,'country;COUNTRY_N;CNTRMADE',''); //Страна-производитель
        thF_RegN := nil; //FindField(Table,'reg_num','Регистрационный номер');
        thF_Price := FindField(Table,'summa;SUM_OPL;SUMPAY','Суммa');
        thF_Price_reg := FindField(Table,'sum3;PRICE_REES;REGPRC','Цена реестра');

		if UseBarcode then
          thF_Barcode := FindField(Table,'ean13;SCANCOD;EAN13','') // если нет, то не будет ошибки
		else
		      thF_Barcode := nil;

        thF_DateSertif := findfield(table,'reg_date;DSERT;SERTDATE','');
        //thF_Em := findfield(table,'package','');





        data.Add(
          'srok'#9+
          'sroksertif'#9+
          'sertifname'#9+
          'kol'#9+
          'nds'#9+
          'name'#9+
          //'firstcenaplusnds'+#9+
          ifstr(thF_FIRSTPRICEWNDS<>nil,'firstcenaplusnds'+#9,'')+
          ifstr(thF_FIRSTPRICE<>nil,'firstcena'+#9,'')+
          'seria'#9+
          'sertif'#9+
          'producername'#9+
          'tamog'#9+
          'countryname'#9+
          'regn'#9+
          'summa'#9+
          ifstr(thf_price_reg<>nil,'price_reg'+#9,'')+
          ifstr(thf_barcode<>nil,'barcode'+#9,'')+
          ifstr(thf_datesertif<>nil,'datesertif'+#9,'')

          //'sroksertif'#9+

          //+ifstr(thf_em<>nil,'em'+#9,'')
          );



        while not Table.eof do begin
          Str := '';

          addstr1(str,thF_Srok);
          addstr1(str,thF_Sroksertif);
          addstr1(str,thf_namesertif);
          addstr1(str,thf_amount);
          addstr1(str,thf_nds);
          addstr1(str,thf_name);
          addstr1(str,thF_FIRSTPRICE);
          addstr1(str,thf_SEria);
          addstr1(str,thf_SErtif);
          addstr1(str,thf_NameProducer);
          addstr1(str,thf_Tamog);
          addstr1(str,thF_Country);
          addstr1(str,thf_regn);
          addstr1(str,thF_Price);
          addstr1(str,thF_Price_reg);
          addstr1(str,thF_Barcode);
          addstr1(str,thF_datesertif);

          {
          str :=
             thF_Srok.asstring+#9+
             thF_Sroksertif.asstring+#9+
             thf_namesertif.asstring+#9+
             thf_amount.asstring+#9+
             thf_NDS.asstring +#9+
             thf_name.asstring+#9+
             thF_FIRSTPRICE.asstring+#9+
             thf_SEria.asstring+#9+
             thf_SErtif.asstring+#9+
             thf_NameProducer.asstring+#9+
             thf_Tamog.AsString+#9+
             thF_Country.AsString+#9+
             thf_regn.asstring+#9+
             thF_Price.asstring +#9;

           if  thf_price_reg<>nil  then str := str + thF_price_reg.asstring+#9;

           if  thF_Barcode<>nil
           then begin
             str1 :=  thF_Barcode.asstring;

              ipos := pos(',',str1);
              if ipos>0
              then str1 := copy(str1,1,ipos-1);

              str:= str +str1+#9;
           end;

           if  thf_datesertif<>nil  then str := str + thF_DateSErtif.asstring+#9;

             //thf_sroksertif.asstring+#9;




          //if  thf_em<>nil
          //then str := str + thF_em.asstring+#9;
          }

          data.Add(str);
          Table.Next;
        end;
       finally
          Table.free;
       end;

     finally
       free
     end;

     createhint('Операция завершена');
 end.
