// Ñêðèïò èìïîðò èç Ìàãíàò

const UseBarcode = true; // îïðåäåëÿåò, áóäåò ëè èñïîëüçîâàòüñÿ øòðèõêîä, ïîñòàâëÿåìûé ïîñòàâùèêîì

var
    Header :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    Data :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    ExportAgent :string; // âñå îïðåäåëåíû ïðèëîæåíèåì

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;

const ListSeparator = ' îò ';
      FileSeparator = ' ôàéë: ';

var Table :TTable;
    num_doc :string;
    Item :variant;
    i :integer;
    FileName :string;
    Dirname :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_BarCode,thF_DateSertif,thF_Em,thF_FirstProcent :TField;
    thF_Price_Reg :TField;
    str,str1 :string;
    Field :TField;

    InvoicesList :TStringList;

    FileList :tstringlist;

    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 Destination := Destination + thField.asstring;
      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;
          Sorted := true;
        end;


        Form.caption := 'Âûáåðèòå íàêëàäíóþ:';
        form.position := poScreenCenter;
        form.borderstyle := bsDialog;
        form.width := 500;
        form.height := 400;
        Form.Font.Size := Form.Font.Size +4;

        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
     DirName :=  AppIniFile.readstring('plugins_magnat','dirname','');
     if not  SElectDirectory('Âûáåðèòå êàòàëîã ñ íàêëàäíûìè:','',DirName) then exit;

     DirName := Includetrailingpathdelimiter(DirName); 

     AppIniFile.writestring('plugins_magnat','DirName',DirName);


     {

     FileName := '';
     OpenDialog := TOpenDialog.create(nil);
     try
       OpenDialog.Title := 'Óêàæèòå ôàéë';
       OpenDialog.FileName  := AppIniFile.readstring('plugins_protek','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_protek','filename',OpenDialog.filename);
           break;
         end;
       end;
     finally
       OpenDialog.free;
     end;

 }

     //if FileName = '' then exit;

     InvoicesList:= Tstringlist.create;
     FileList := tstringlist.create;

     with TMyWait.create('Èäåò èìïîðò íàêëàäíîé') do
     try

       GetFileList(DirName,FileList,'*.zip',false);

       Table := TTable.Create(nil);
       try

        table.tabletype := ttFoxpro;

        for i := 0 to FileList.count-1 do
        begin


          if not ZipExtract(DirName + FileList[i], gettempdir, 'nakladn.dbf')
          then begin
            CreateHintW('Ðàñïàêîâêà zip-ïàêåòà íå óäàëàñü, îáðàòèòåñü â ñëóæáó òåõïîääåðæêè');
            exit;
          end;

          FileName := gettempdir + 'nakladn.dbf';


          table.close;
          Table.TableName := 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 not table.isempty and (table.findfield('ndoc')<>nil)
          then begin
            table.first;
            while not table.eof do
            begin
              Str := Table.fieldbyname('ndoc').asstring + ListSeparator + Table.fieldbyname('datedoc').asstring + FileSeparator + FileList[i];

              If InvoicesList.indexof(Str)<0
              then InvoicesList.add(Str);

              table.next;
            end;
          end;
          table.close;
        end;


        if InvoicesList.count=0
        then begin
            CreateHintW('Íàêëàäíûõ íå íàéäåíî');
            exit;
        end
        else begin
          if Str='' then begin
            CreateHintW('Íå âûáðàíà íàêëàäíàÿ');
            exit;
          end;

          if InvoicesList.count>1
          then Str := GetValueFromListDialog(InvoicesList)
          else Str := INvoicesList[0];
        end;

        if str = '' then exit;

        Header.Values[ExportNakladNom] := copy(str,1,pos(listSeparator,Str)-1);


        FileName := copy(str,pos(FileSeparator,Str)+length(FileSeparator),length(Str));

        if not ZipExtract(DirName + FileName, gettempdir, 'nakladn.dbf')
        then begin
          CreateHintW('Ðàñïàêîâêà zip-ïàêåòà íå óäàëàñü, îáðàòèòåñü â ñëóæáó òåõïîääåðæêè');
          exit;
        end;

        FileName := gettempdir + 'nakladn.dbf';


        table.close;
        table.tablename := Filename;

        //filedelete(Table.tablename);
        Table.tabletype := ttfoxpro;
        copyfile(dirname +  FileName,Table.TableName,False);
        SetTableLangDriver(Table,'db866ru0');

        //bvmessage(table.tablename);

        table.open;
        table.filter := '[ndoc]='+Quotedstr(Header.Values[ExportNakladNom]);
        Table.filtered := true;

        Header.Values[ExportNakladData] := copy(str,pos(listSeparator,Str)+length(ListSeparator),Pos(FileSeparator,Str)-pos(listSeparator,Str)-length(ListSeparator));

        CreateHintI('Äàòà: ' + Header.Values[ExportNakladData] +', íîìåð: '+ Header.Values[ExportNakladNom]);


        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_FIRSTPRICE := FindField(Table, 'PRICE2N','Öåíà çàâîäà');
        thF_FIRSTPROCENT := nil; //FindField(Table, 'PRC_NAC','% íàöåíêè');
        thF_SROK :=  FindField(Table,'GDATE','Ñðîê ãîäíîñòè');
        thF_SROKSERTIF := NIL; //FindField(Table,'SROK_SER','Ñðîê äåéñòâèÿ ñåðòèôèêàòà');
        thF_NAMESERTIF := FindField(Table,'sertorg','Êåì âûäàí ñåðòèôèêàò');
        thF_AMOUNT := FindField(Table,'QNT','Êîëè÷åñòâî åäèíèö');
        thF_NDS := FindField(Table,'NDS','Ñòàâêà ÍÄÑ');
        thF_NAME := FindField(Table,'NAME','Íàèìåíîâàíèå òîâàðà');
        thF_Seria := nil; //FindField(Table,'SERIY','Ñåðèÿ');
        thF_Sertif := FindField(Table,'SERTIF','Ñåðòèôèêàò');
        thF_NameProducer := FindField(Table,'FIRM','Ïðîèçâîäèòåëü');
        thF_tamog := FindField(Table,'NUMGTD','Íîìåð òàìîæåííîé äåêëàðàöèè');

        //DUE_DATE ? ÷òî çà ïîëå



        thf_country := findfield(table,'CNTR','Ñòðàíà');

        thF_RegN := nil; //FindField(Table,'INP','Ðåãèñòðàöèîííûé íîìåð');

        if UseBarcode
        then
          thF_Barcode := FindField(Table,'EAN13','') // åñëè íåò, òî íå áóäåò îøèáêè
        else
          thf_Barcode := nil;

        thF_DateSertif := nil; //findfield(table,'PASDAT','Äàòà âûäà÷è ñåðòèôèêàòà');
        thF_Em := nil; //findfield(table,'package','');
        thF_Price_reg := findfield(table,'REESTR','');

        thF_Price := FindField(table,'PRICE2','Öåíà');


        data.Add('srok'#9'sroksertif'#9'sertifname'#9+
          'kol'#9'nds'#9+
          'name'#9+
          'firstprocent'#9 +
          'seria'#9'sertif'#9+
          'producername'#9+
          'tamog'#9+
          ifstr(thf_Country<>nil,'countryname'+#9,'')+
          'regn'#9+
          'cena'#9+ //ifstr(table.findfield('num_nak')<>nil,'cenanotnds','cena')+#9

          'barcode'+#9+
          'datesertif'+#9+
          'em'+#9+
          '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_FIRSTPROCENT);
          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);

          data.Add(str);
          Table.Next;
        end;
       finally
          Table.free;
       end;

     finally
       FileList.free;
       Invoiceslist.free;
       free
     end;

     createhint('Îïåðàöèÿ çàâåðøåíà');
 end.
