// Импорт накладных ЗАО "Роста" Самара

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком


var
    FILENAME :string; // имя файла. Если не указано, то запрашивается диалогом
    
    Header :TStringList; // предопределена приложением
    Data :TStringList; // предопределена приложением
    ExportAgent :string; // все определены приложением

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

var Table :TTable;
    CDS :TClientDAtaset;
    num_doc :string;
    Item :variant;
    i :integer;
    OpenDialog :TOpenDialog;
    ThF_FIRSTPRICE,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_Code,thF_CountryCode,thF_ProducerCode,thf_AnalizeCode,thF_SertifCode :TField;

    thF_Price_Reg :TField;
    str,str1 :string;
    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;

    procedure AddStr(var Destination :string; const thField :tField);
    begin
      if thField<>nil
      then Destination := Destination + thField.asstring;
      Destination := Destination + #9;
    end;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;

 begin
     if filename=''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring('plugins_rosta','filename','');
         OpenDialog.initialdir := extractfilepath(opendialog.filename);
         OpenDialog.Filter := 'Файлы-накладные(*.dbf,*.csv)|*.dbf;*.csv|Все файлы(*.*)|*.*';
         while  OpenDialog.execute do begin
           if not fileexists(OpenDialog.FileName) then CreateHint('Укажите правильно файл ')
           else begin
             Filename := OpenDialog.FileName;
             AppIniFile.writestring('plugins_rosta','filename',OpenDialog.filename);
             break;
           end;
         end;
       finally
         OpenDialog.free;
       end;
     end;

     if FileName = '' then exit;

     with TMyWait.create('Идет импорт накладной') do
     try

       Header.VAlues[ExportAgentName] := 'Роста';
     
       CDS := TClientdataset.create(nil);
       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;

              readdataset(cds,table);

            finally
              table.free;
            end;
        end
        else begin
          ReadTXT( CDS, FileName, '|');
        end;


        cds.first;


        if (cds.findfield('docno')<>nil) and (cds.findfield('docdat')<>nil)
        then begin
          Header.Values[ExportNakladNom] := cds.fieldbyname('docno').asstring;
          Header.Values[ExportNakladData] := cds.fieldbyname('docdat').asstring;
          Header.VAlues[ExportSkladName] := cds.fieldbyname('nameadres').asstring;
        


        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_NAME := FindField(cds,'tovar','Наименование товара');
        thF_Seria := FindField(cds,'seria','Серия');
        thF_NameProducer := FindField(cds,'prod','Производитель');
        thf_country := findfield(cds,'strana','Страна-производитель');
        thF_AMOUNT := FindField(cds,'kol','Количество единиц');
        thF_Price := FindField(cds,'summa','Суммa');
        thF_NDS := FindField(cds,'ndspro','Ставка НДС');
        thF_Sertif := FindField(cds,'sertif','Сертификат');
        thF_NAMESERTIF := FindField(cds,'sorg','Кем выдан сертификат');
        thF_DateSertif := findfield(cds,'sertot','Дата выдачи сертификата');
        thF_SROKSERTIF := FindField(cds,'SERTDO','Срок действия сертификата');
        thF_SROK :=  FindField(cds,'GODEN','Срок годности');
        thF_Price_reg := findfield(cds,'reg','Цена реестра');
        thF_FIRSTPRICE := FindField(cds, 'ZAVOD','Цена завода');
        thF_tamog := FindField(cds,'gtd','Номер таможенной декларации');
        thF_RegN := FindField(cds,'reg_num','Регистрационный номер');

        if UseBarcode then
          thF_Barcode := FindField(cds,'ean13;BARCODE','') // если нет, то не будет ошибки
        else
          thF_Barcode := nil;
        //thF_Em := findfield(table,'package','');

        data.Add(
          'srok'#9+
          'sroksertif'#9+
          'sertifname'#9+
          'kol'#9+
          'nds'#9+
          'name'#9+
          //'firstcenaplusnds'+#9+
          'firstcena'+#9+
          'seria'#9+
          'sertif'#9+
          'producername'#9+
          'tamog'#9+
          'countryname'#9+
          'regn'#9+
          'summa'#9+
          'price_reg'+#9+
          'barcode'+#9+
          'datesertif'+#9+

          //'sroksertif'#9+

          //+ifstr(thf_em<>nil,'em'+#9,'')
          );
  
        while not cds.eof do begin
          Str := '';

             Addstr(str,thF_Srok);
             Addstr(str,thF_Sroksertif);
             Addstr(str,thf_namesertif);
             Addstr(str,thf_amount);
             Addstr(str,thf_NDS);
             Addstr(str,thf_name);
             Addstr(str,thF_FIRSTPRICE);
             Addstr(str,thf_SEria);
             Addstr(str,thf_SErtif);
             Addstr(str,thf_NameProducer);
             Addstr(str,thf_Tamog);
             Addstr(str,thF_Country);
             Addstr(str,thf_regn);
             Addstr(str,thF_Price);
             Addstr(str,thF_price_reg);
             Addstr(str,thF_Barcode);
             Addstr(str,thF_DateSErtif);

             //thf_sroksertif.asstring+#9;
            //if  thf_em<>nil
            //then str := str + thF_em.asstring+#9;



          data.Add(str);
          cds.Next;
        end;
        
        end
        //************************************************************************************************************************
         else
          if (cds.findfield('N_NACL')<>nil) and (cds.findfield('D_NACL')<>nil)
        then begin
          Header.Values[ExportNakladNom] := cds.fieldbyname('N_NACL').asstring;
          Header.Values[ExportNakladData] := cds.fieldbyname('D_NACL').asstring;
        


        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_NAME := FindField(cds,'tovar;NAME','Наименование товара');
        thF_Seria := FindField(cds,'seria;SERIES','Серия');
        thF_NameProducer := FindField(cds,'prod;FACTORY','Производитель');
        thf_country := findfield(cds,'strana;COUNTRY','Страна-производитель');
        thF_AMOUNT := FindField(cds,'kol;QUANTITY','Количество единиц');
        thF_Price := FindField(cds,'summa;SUMWNDS','Суммa');
        thF_NDS := FindField(cds,'ndspro;NDS_PR','Ставка НДС');
        thF_Sertif := FindField(cds,'sertif;SERT','Сертификат');
        thF_NAMESERTIF := FindField(cds,'sorg;ORGANGIVE','Кем выдан сертификат');
        thF_DateSertif := findfield(cds,'sertot;DATEGIVE','Дата выдачи сертификата');
        thF_SROKSERTIF := FindField(cds,'SERTDO;DEND','Срок действия сертификата');
        thF_SROK :=  FindField(cds,'GODEN;DATE_VALID','Срок годности');
        thF_Price_reg := findfield(cds,'reg;PRICE_REES','Цена реестра');
        thF_FIRSTPRICE := FindField(cds, 'ZAVOD;PRICE_MAKE','Цена завода');
        thF_tamog := FindField(cds,'gtd','Номер таможенной декларации');
        thF_RegN := FindField(cds,'reg_num','Регистрационный номер');

        if UseBarcode then
          thF_Barcode := FindField(cds,'ean13;BARCODE;SCANCOD','') // если нет, то не будет ошибки
        else
          thF_Barcode := nil;
          
        //thF_Em := findfield(table,'package','');

        data.Add(
          'srok'#9+
          'sroksertif'#9+
          'sertifname'#9+
          'kol'#9+
          'nds'#9+
          'name'#9+
          //'firstcenaplusnds'+#9+
          'firstcena'+#9+
          'seria'#9+
          'sertif'#9+
          'producername'#9+
          'tamog'#9+
          'countryname'#9+
          'regn'#9+
          'summa'#9+
          'price_reg'+#9+
          'barcode'+#9+
          'datesertif'+#9+

          //'sroksertif'#9+

          //+ifstr(thf_em<>nil,'em'+#9,'')
          );
  
        while not cds.eof do begin
          Str := '';

             Addstr(str,thF_Srok);
             Addstr(str,thF_Sroksertif);
             Addstr(str,thf_namesertif);
             Addstr(str,thf_amount);
             Addstr(str,thf_NDS);
             Addstr(str,thf_name);
             Addstr(str,thF_FIRSTPRICE);
             Addstr(str,thf_SEria);
             Addstr(str,thf_SErtif);
             Addstr(str,thf_NameProducer);
             Addstr(str,thf_Tamog);
             Addstr(str,thF_Country);
             Addstr(str,thf_regn);
             Addstr(str,thF_Price);
             Addstr(str,thF_price_reg);
             Addstr(str,thF_Barcode);
             Addstr(str,thF_DateSErtif);

             //thf_sroksertif.asstring+#9;
            //if  thf_em<>nil
            //then str := str + thF_em.asstring+#9;



          data.Add(str);
          cds.Next;
        end;
        
        end
        
        //************************************************************************************************************************
        
        else begin
          raiseexception('Таблица имеет формат, не согласованный с поставщиком. Обратитесь в техподдержку');
        end;
        
        
        
       finally
          cds.free;
       end;  

     finally
       free
     end;

     createhint('Операция завершена');
 end.
