// Скрипт импорт из Генезис (Саратов)

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком

var
    Header :TStringList; // предопределена приложением
    Data :TStringList; // предопределена приложением
    ExportAgent :string; // все определены приложением
    Filename :string;

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSROK :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

const ListSeparator = ' от ';

var Table :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_Price_Reg :TField;
    thF_Price_RS :TField;
    str,str1 :string;
    Field :TField;

    InvoicesList :TStringList;

    SrcFile :TStringList;
    List1 :tStringList;

    procedure AddStr(var Destination :string; const thField :tField);
    begin
      if thField<>nil
      then Destination := Destination + thField.asstring;
      Destination := Destination + #9;
    end;

    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;


 begin
     if filename = ''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring('plugins_top_service','filename','');
         opendialog.initialdir := extractfilepath(opendialog.filename);
         OpenDialog.Filter := 'Файлы-накладные(*.txt)|*.txt|Все файлы(*.*)|*.*';
         while  OpenDialog.execute do begin
           if not fileexists(OpenDialog.FileName) then CreateHint('Укажите правильно файл ')
           else begin
             Filename := OpenDialog.FileName;
             AppIniFile.writestring('plugins_top_service','filename',OpenDialog.filename);
             break;
           end;
         end;
       finally
         OpenDialog.free;
       end;
     end;

     if FileName = '' then exit;

     Table := TClientDAtaset.Create(nil);
     InvoicesList:= Tstringlist.create;
     SrcFile := tStringList.create;
     List1 := TSTringList.create;

     with TMyWait.create('Идет импорт накладной') do
     try

        SRCFile.loadFromFile(FileName);

        if pos('DATE_ORDER;NUM_ORDER;DATE_TO_PAID;ORDER_SUM;ORDER_NDS_SUM',SRCFile[0])=0
        then
          raiseexception('Таблица имеет формат, не согласованный с поставщиком. Обратитесь в техподдержку');


        StringToList(SRCFile[1],List1);


        Header.Values[ExportNakladData] := List1[0];
        Header.Values[ExportNakladNom] := List1[1];
        Header.Values[ExportNakladSROK] := List1[2];


        SRCFile.delete(0);
        SRCFile.Delete(0);

        ReadTXTList(TAble,SRCFile,';');

        Table.First;

        if table.isempty then begin
           createhintw('Таблица пуста');
           exit;
        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');
        }

        //GOODS;ID_PROVIDER_GOODS;QUANT;PRODUCER_PRICE;PROVIDER_MARKUP;
        //PERCENT_MARKUP;PERCENT_NDS;SUM_NDS;SUM;PRICE;PRODUCER;CERTIFICATE_SERIES;
        //CERTIFICATE_DATE;CERTIFICATE_SROK;CERTIFICATE_ORG;COUNTRY;GTD;SERIES;
        //PRODUCTION_DATE;BEST_BEFORE;PRICE_ROZN


        thF_FIRSTPRICE := FindField(Table, 'PRODUCER_PRICE','Цена завода');
        thF_SROK :=  FindField(Table,'BEST_BEFORE','Срок годности');
        thF_SROKSERTIF := FindField(Table,'CERTIFICATE_SROK','Срок действия сертификата');
        thF_NAMESERTIF := FindField(Table,'CERTIFICATE_ORG','Кем выдан сертификат');
        thF_AMOUNT := FindField(Table,'QUANT','Количество единиц');
        thF_NDS := FindField(Table,'PERCENT_NDS','Ставка НДС');
        thF_NAME := FindField(Table,'GOODS','Наименование товара');
        thF_Seria := FindField(Table,'SERIES','Серия');
        thF_Sertif := FindField(Table,'CERTIFICATE_SERIES','Сертификат');
        thF_NameProducer := FindField(Table,'PRODUCER','Производитель');
        thF_tamog := FindField(Table,'GTD','Номер таможенной декларации');

        //DUE_DATE ? что за поле



        thf_country := findfield(table,'COUNTRY','');

        thF_RegN := nil; //FindField(Table,'REG_NUMBER','Регистрационный номер');

        if UseBarcode
        then
          thF_Barcode := FindField(Table,'EAN13','') // если нет, то не будет ошибки
        else
           thF_Barcode := nil;


        thF_DateSertif := findfield(table,'CERTIFICATE_DATE','Дата выдачи сертификата');
        thF_Em := nil; //findfield(table,'package','');
        thF_Price_reg := nil; //findfield(table,'PRICE_RR','Цена реестра');

        thF_Price := FindField(table,'SUM','Сумма итого');

        thF_Price_RS := FindField(table,'PRICE_ROZN','Цена розницы');


        data.Add('srok'#9'sroksertif'#9'sertifname'#9+
          'kol'#9'nds'#9+
          'name'#9+
          'firstcena'#9 + //ifstr(table.findfield('num_nak')<>nil,'firstcena','firstcenaplusnds')+#9+
          'seria'#9'sertif'#9+
          'producername'#9+
          'tamog'#9+
          'countryname'+#9+
          'regn'#9+
          'summa'#9+ //ifstr(table.findfield('num_nak')<>nil,'cenanotnds','cena')+#9

          'barcode'+#9+
          'datesertif'+#9+
          'em'+#9+
          'price_reg'+#9+
          'rs_cena'+#9
          );

        table.first;

        while not Table.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_Barcode);
          Addstr(str,thf_datesertif);
          Addstr(str,thf_em);
          Addstr(str,thf_price_reg);
          Addstr(str,thf_price_rs);

          data.Add(str);
          Table.Next;
        end;

     finally
       LIst1.free;
       srcFile.free;
       Invoiceslist.free;
       table.free;
       free
     end;

     createhint('Операция завершена');
 end.
