// Скрипт импорта накладной Ориола (Саратов)

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком

var
    Header :TStringList; // предопределена приложением
    Data :TStringList; // предопределена приложением
    ExportAgent :string; // все определены приложением

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

var Table :TTable;
    num_doc :string;
    Item :variant;
    i :integer;
    FileName :string;
    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_sum,thF_BarCode,thF_DateSertif,thF_Em,thF_Analize :TField;
    thF_Price_Reg :TField;
    str,str1 :string;
    Field :TField;

    InvoicesList :TStringList;

    SumsTr :string;
const ListSeparator = ' от ';


    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    end;

    procedure AddStr(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;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;

    function GetValueFromListDialog(List :Tstrings) :string;
    var Form :TForm;
        ListBox :TListBox;
        Panel :TPanel;
        Btn :TButton;
    begin

      result := '';
      if List=nil then  exit;

      Form := TForm.create(nil);

      try
        ListBox := TListBox.create(Form);
        with Listbox do
        begin
          parent :=Form;
          Items.text := List.text;
          if List.count>0 then ItemIndex := 0;
          align :=alclient;
        end;


        Form.caption := 'Выберите накладную:';
        form.position := poScreenCenter;
        form.borderstyle := bsDialog;
        form.width := 300;
        form.height := 250;

        Panel := tPanel.create(Form);
        with Panel do
        begin
          parent := Form;
          align := albottom;
          height := 35;
          BevelInner :=bvNone;
          BevelOuter := bvNone;

          (*
          with TBevel.create(Form) do
          begin
            Parent := panel;
            Align :=alTop;
            Shape := bsTopLine;
            Height := 4;
          end;
          *)

          Btn := TButton.create(Form);
          with Btn do
          begin
            Parent := Panel;
            Caption := 'Отмена';
            ModalResult := mrCancel;
            Cancel := true;
            width := 70;
            Top := 6;
            Left := Form.ClientWidth - Width - 20;
          end;


          with TButton.create(Form) do
          begin
            Parent := Panel;
            Caption := 'Ok';
            ModalResult := mrOk;
            Default := true;
            Width := Btn.width;
            Top := Btn.Top;
            Left := Btn.left- Width -10;
          end;

        end;

        if form.showmodal = mrok then
        begin
          if ListBox.Itemindex <0
          then CreateHintW('Вы не выбрали ни одной накладной')
          else Result := ListBox.Items[ListBox.Itemindex];
        end

      finally
        Form.free
      end;
    end;


 begin
     FileName := '';
     OpenDialog := TOpenDialog.create(nil);
     try
       OpenDialog.Title := 'Укажите файл';
       OpenDialog.FileName  := AppIniFile.readstring('plugins_forafarm','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_forafarm','filename',OpenDialog.filename);
           break;
         end;
       end;
     finally
       OpenDialog.free;
     end;

     if FileName = '' then exit;

     InvoicesList:= Tstringlist.create;
     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,'DBWINUS0'); //DBWINUS0  db866ru0
        CheckDBFCP(Table.TableName,87); //866DOS - 38

        Table.Open;
        Table.First;

        if table.findfield('NUM_DOC')<>nil
        then begin

          table.first;
          while not table.eof do
          begin
            Str := Table.fieldbyname('NUM_DOC').asstring + ListSeparator + Table.fieldbyname('DATE_DOC').asstring;

            If InvoicesList.indexof(Str)<0
            then InvoicesList.add(Str);

            table.next;
          end;

          if InvoicesList.count>1
          then Str := GetValueFromListDialog(InvoicesList)
          else Str := INvoicesList[0];

          if Str='' then begin
            CreateHintW('Не выбрана накладная');
            exit;
          end;

          Header.Values[ExportNakladNom] := copy(str,1,pos(listSeparator,Str)-1);

          table.filter := '[NUM_DOC]='+Quotedstr(Header.Values[ExportNakladNom]);
          Table.filtered := true;

          Header.Values[ExportNakladData] := copy(str,pos(listSeparator,Str)+length(ListSeparator),length(Str));

          CreateHint('Дата: ' + Header.Values[ExportNakladData] +', номер: '+ Header.Values[ExportNakladNom]);

        end
        else
        if table.findfield('NDOC')<>nil
        then begin

          table.first;
          while not table.eof do
          begin
            Str := Table.fieldbyname('NDOC').asstring + ListSeparator + Table.fieldbyname('DATEDOC').asstring;

            If InvoicesList.indexof(Str)<0
            then InvoicesList.add(Str);

            table.next;
          end;

          if InvoicesList.count>1
          then Str := GetValueFromListDialog(InvoicesList)
          else Str := INvoicesList[0];

          if Str='' then begin
            CreateHintW('Не выбрана накладная');
            exit;
          end;

          Header.Values[ExportNakladNom] := copy(str,1,pos(listSeparator,Str)-1);

          table.filter := '[NDOC]='+Quotedstr(Header.Values[ExportNakladNom]);
          Table.filtered := true;

          Header.Values[ExportNakladData] := copy(str,pos(listSeparator,Str)+length(ListSeparator),length(Str));

          CreateHint('Дата: ' + Header.Values[ExportNakladData] +', номер: '+ Header.Values[ExportNakladNom]);

        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_NAME := FindField(Table,'NAME_TOVAR;NAME','Наименование товара');
        thF_NameProducer := FindField(Table,'PROIZ;FIRM','Производитель');
        thf_country := findfield(table,'COUNTRY;CNTR','Страна-производитель');
        thF_tamog := FindField(Table,'gtd;numgtd','Номер таможенной декларации');
        thF_AMOUNT := FindField(Table,'VOLUME;QNT','Количество единиц');
        thF_FIRSTPRICE := FindField(Table, 'PR_PROIZ;price1','Цена завода');
        thF_NDS := FindField(Table,'PCT_NDS;NDS','Ставка НДС');
        thF_Price := FindField(Table,'PRICE1','Цена');
        thF_SUM := FindField(Table,'SUMMA;SUMS0','');
        thF_Seria := FindField(Table,'SERIA;SER','Серия');
        thF_Sertif := FindField(Table,'DOCUMENT;SERTIF','Сертификат');
        thF_RegN := FindField(Table,'REG_NUM',''); //'Регистрационный номер');
        thF_DateSertif := findfield(table,'REG_DATE;DATEMADE','Дата сертификата');
        thF_SROK :=  FindField(Table,'SROK;GDATE','Срок годности');
        thF_NAMESERTIF := FindField(Table,'STRING2;SERTORG','Кем выдан сертификат');

        thF_Price_reg := nil;//findfield(Table,'REESTR','Цена реестра');
        thF_SROKSERTIF := nil;//FindField(Table,'SROK_SER','Срок действия сертификата');

        thF_analize := nil; //FindField(Table,'analis','№ протокола анализа');

     		if UseBarcode
     		then
          thF_Barcode := FindField(Table,'ean13;barcode;barcod','') // если нет, то не будет ошибки
     		else
      		  thF_Barcode := nil;

        //thF_Em := findfield(table,'package','');
        //thF_SROKSERTIF := FindField(Table,'srok_ser;srok_sert','Срок действия сертификата');



        if thf_sum<>nil
        then Sumstr := 'summa'
        else sumstr := 'cena';


        data.Add(
          'srok'#9+
          'sroksertif'#9+
          'sertifname'#9+
          'kol'#9+
          'nds'#9+
          'name'#9+
          'firstcena'+#9+
          'seria'#9+
          'sertif'#9+
          'analize'#9+
          'producername'#9+
          'datesertif'+#9+
          'tamog'#9+
          'countryname'#9+
          'regn'#9+
          sumstr+#9+
          ifstr(thf_price_reg<>nil,'price_reg'+#9,'')+

          ifstr(thf_barcode<>nil,'barcode'+#9,'')+


          //+ifstr(thf_em<>nil,'em'+#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_analize);
          Addstr(str,thf_NameProducer);
          Addstr(str,thF_DateSErtif);
          Addstr(str,thf_Tamog);
          Addstr(str,thF_Country);
          Addstr(str,thf_regn);

          if(thf_sum<>niL)
          then addstr(str,thf_sum)
          else Addstr(str,thF_Price);

          if thf_price_reg<>nil then Addstr(str,thF_price_reg);
          if thf_barcode<>nil then Addstr(str,thF_barcode);

          data.Add(str);
          Table.Next;
        end;

        //data.savetofile('c:\temp\2.txt');

       finally
          Table.free;
       end;

     finally
  	   invoiceslist.free;
       free
     end;

     createhint('Операция завершена');
 end.
