// Ñêðèïò èìïîðò èç Ïðîòåê (Ñàðàòîâ)

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

Var CurrLangDriver :string = ''; //'db866ru0'; //   'DBWINUS0' ;
    CurrDBFCP :integer = 38; //87;

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

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

const ListSeparator = ' îò ';

var Table :TTable;
    num_doc :string;
    Item :variant;
    i,k :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_SUM, thF_BarCode,thF_DateSertif,thF_Em :TField;
    thF_Price_Reg, thf_ndoc, thf_datedoc :TField;
    str,str1 :string;
    Field :TField;

    InvoicesList :TStringList;

    List :TStringlist;
    List1 :tStringLIst;
    FirstI :integer;
    Strval :string;
    INtVal :integer;
    StrVal3 :string;
    StrVAl4 :string;
    StrVal1 :string;
    PriceWithNDS :currency;
    PriceWithoutNDS :currency;
    FloatVal2 :double;

    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
     //FileName := '';
     if filename=''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Óêàæèòå ôàéë';
         OpenDialog.Filename  := AppIniFile.readstring('plugins_protek','filename','');
         opendialog.initialdir := extractfilepath(opendialog.filename);
  
         OpenDialog.Filter := 'Ôàéëû-íàêëàäíûå(*.dbf,*.sst)|*.dbf;*.sst|Âñå ôàéëû(*.*)|*.*';
         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;
     end;

     if FileName = '' then exit;

     //showmessage(uppercase(extractfileext(filename)));

     InvoicesList:= Tstringlist.create;


     with TMyWait.create('Èäåò èìïîðò íàêëàäíîé') do
     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);
          

          if CurrLangDriver>'' 
          then SetTableLangDriver(Table,CurrLangDriver)
          else if CurrDBFCP<>0
          then CheckDBFCP(Table.TableName,CurrDBFCP); //866DOS

          Table.Open;
          Table.First;

          if table.isempty then begin
             createhintw('Òàáëèöà ïóñòà');
             exit;
          end;
          thf_ndoc := FindField(Table,'nomerdoc;DOCN;DOCNO;NDOC','');
          thf_datedoc := findfield(table,'datadoc;DATEN;DOCDAT;DATEDOC','');
          
          if  (thf_ndoc<>nil) and (thf_datedoc<>nil)
            then 
            begin

               table.first;
               while not table.eof do
               begin
                 Str := thf_ndoc.asstring + ListSeparator + thf_datedoc.asstring;
                 //Str := Table.fieldbyname('nomerdoc').asstring + ListSeparator + Table.fieldbyname('datadoc').asstring;
                // Str := Table.fieldbyname('DOCN').asstring + ListSeparator + Table.fieldbyname('DATEN').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 := '['+thf_ndoc.fieldname+']='+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_FIRSTPRICE := FindField(Table, 'PRODCOST;PPWONDS;PRO;PRICE1N','');
          if  thF_FIRSTPRICE = nil
          then thF_FIRSTPRICE := FindField(Table, 'PRICE1','Öåíà çàâîäà');
          
          thF_SROK :=  FindField(Table,'SROKGODN;SERTDAT;SROK_DATE;SERIA_SROK;GDATE','Ñðîê ãîäíîñòè');
          thF_SROKSERTIF := FindField(Table,'SERTDAT;S_S_DATE;SERT_END;CERTDATE',''); //Ñðîê äåéñòâèÿ ñåðòèôèêàòà
          thF_NAMESERTIF := FindField(Table,'ORGAN;ORG;SERT_ORGAN;CERTORG;SERTORG','Êåì âûäàí ñåðòèôèêàò');
          thF_AMOUNT := FindField(Table,'KOL;QTY;KOL;QNT','Êîëè÷åñòâî åäèíèö');
          thF_NDS := FindField(Table,'PROCNDS;PROC_NDS;NDS','Ñòàâêà ÍÄÑ');
          thF_NAME := FindField(Table,'NAME;NM_M;TOVAR','Íàèìåíîâàíèå òîâàðà');
          thF_Seria := FindField(Table,'SERIA;NM_S;SERIA_NAME;SER','Ñåðèÿ');
          thF_Sertif := FindField(Table,'REGNOMER;SERT;SERT_NAME;CERTIF;SERTIF','Ñåðòèôèêàò');
          thF_NameProducer := FindField(Table,'PRODUCT;NM_PROD;PROD;FIRM','Ïðîèçâîäèòåëü');
          thF_tamog := FindField(Table,'GTD;NUMGTD','Íîìåð òàìîæåííîé äåêëàðàöèè');

          //DUE_DATE ? ÷òî çà ïîëå
          thf_country := findfield(table,'country;STRANA;CNTR;STRANA','Ñòðàíà');

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

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

          thF_DateSertif := findfield(table,'PASDAT;DATE_SERT;SERT_BEGIN;DATEMADE;CERTDATE','Äàòà âûäà÷è ñåðòèôèêàòà');
          thF_Em := findfield(table,'package;EDSM','');
          thF_Price_reg := findfield(table,'REESTR;REESTRCENA;REGPRC','');

          thF_SUM := FindField(table,'SUMMAWNDS;SUMMA',''); // Ñóììà ñ ÍÄÑ
          if thF_Sum=nil
          then thF_Price := FindField(table,'PRICE2','Öåíà') //FindField(table,'PRICE2N','Öåíà áåç ÍÄÑ')
          else thF_Price := nil;

          
          data.Add(
          'srok'#9+
          'sroksertif'#9+
          'sertifname'#9+
          'kol'#9+
          'nds'#9+
          'name'#9+
          'firstcena'+#9+
          'seria'#9+
          'sertif'#9+
          
          'producername'#9+
          
          'datesertif'+#9+
          
          'tamog'#9+
          'countryname'#9+
          //'regn'#9+
          'summa'#9+
          'cena'#9+ //'cenanotnds'#9+
          'price_reg'+#9+
          'barcode'+#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);
          Addstr(str,thF_Sum);
          Addstr(str,thF_Price);

          Addstr(str,thF_price_reg);

          Addstr(str,thF_Barcode);



          data.Add(str);
            
            Table.Next;
          end;  
         finally  
            Table.free;
         end;
       end
       else
       if uppercase(extractfileext(filename)) = '.SST'
       then begin

         List := TStringList.create;
         List1 := TsTringLIst.create;
         try

          List.LoadFromFile(FileName);

          if List.count<2 then begin
             raiseexception('ÔÀéë íàêëàäíîé èìååò ìåíåå 2 ñòðîê. Ïðèåì íåâîçìîæåí. Îáðàòèòåñü â òåõïîääåðæêó');
          end;

          //list.casesensitive := false;

          FirstI :=  list.IndexOf('[Header]');
          if FirstI <0
          then begin
             raiseexception('Íåïðàâèëüíûé ôîðìàò ôàéëà - íå íàéäåí ðàçäåë [Header]');
          end;

          inc(FirstI);
          while (List.count>FirstI) and (List[FirstI] ='-') and (uppercase(list[FirstI]) <>'[BODY]')
          do Inc(FirstI);

          if (List.count>FirstI) and (uppercase(list[FirstI])<>'[BODY]')
          then begin


            StrVal := List[FirstI];

            if StrVal >''
            then begin
              IntVal := pos(';',StrVal);
              if IntVal >-1
              then begin
                Header.add(ExportNakladNom+'='+copy(strval,1,IntVal-1));
                StrVal := copy(StrVal,IntVal+1,100);
                IntVal := pos(';',strval);
                if IntVal>0
                then strVal := copy(StrVal,1,IntVal-1);

                strVal := Copy(strval,1,10);  // çàãëóøêà îò âðåìåíè

                if StrVal >''
                then Header.add(ExportNakladData+'='+formatdatetime('dd.mm.yyyy',strtodateprotected( StrVal)));


              end
            end
            else begin
               bvMessageError('Íåïðàâèëüíûé ôîðìàò ôàéëà - ïåñòîé ðàçäåë [Header]');
               exit;
            end;


          end
          else begin
             bvMessageError('Íåïðàâèëüíûé ôîðìàò ôàéëà - íå íàéäåíî ñîäåðæèìîå ðàçäåëà [Header]');
             exit;
          end;

          FirstI := list.indexof('[BODY]');
          if FirstI <0
          then begin
             bvMessageError('Íåïðàâèëüíûé ôîðìàò ôàéëà - íå íàéäåí ðàçäåë [Body]');
             exit;
          end;


          for i := 0 to FirstI-1 do list.Delete(0);


          list[0] :='name'#9'producername'#9'countryname'#9+
                    'kol'#9'FirstCena'#9'cenanotnds'#9+
                    'GTD'#9+
                    'sertif'#9+
                       'datesertif'#9+
                       'sertifname'#9+
                    'seria'#9'srok'#9+

                    'barcode'#9 +
                    //'datereestr'#9+
                    'price_reg'+#9+

                    'nds';

          //list.text := StringReplace(list.text,';',#9,[rfReplaceAll]); //ïî÷åìó-òî AV çäåñü



          for i := 1 to list.count-1 do
          begin

            strval3 := list[i];

            stringtolist(StrVAl3,List1,';');

            if list1.count>0
            then begin


              StrVAl1 := List1[1];                              // name
              StrvAl1 := StrVAl1 + #9 + list1[2];              // producername


              StrvAl1 := StrVAl1 + #9 + List1[3];             // countryname

              StrvAl1 := StrVAl1 + #9 + List1[4];             // kol

              PriceWithNDS := StrToFloatProtected( List1[5]); // öåíà ñ ÍÄÑ

              FloatVal2 := strtofloatprotected(List1[6]);
              if FloatVal2 <>0
              then
                StrvAl1 := StrVAl1 + #9 + List1[6]             // firstcena
              else
                StrvAl1 := StrVAl1 + #9 + List1[7];             // FirstCena, åñëè áûëà ïóñòàÿ

              PriceWithoutNDS := strtofloatprotected(List1[7]);

              StrvAl1 := StrVAl1 + #9 + List1[7];             // cenanotnds

              StrvAl1 := StrVAl1 + #9 + List1[11];             // ÃÒÄ

              /////////////////////////////

              StrvAl := List1[12];

               //43AO55^POCC DE.ÔM02.A71359(P-318-2716-4)^01.06.07  ÌÖÑ ã.Ìîñêâà
               //010304^POCC.DE.ÔM02.A87770^05.10.2004 ÎÀÎ "ÌÖÑ" Ìîñêâà010304^140059^28.05.2005
               //0505^77.99.11.3.Ó.2840.9.04^16.09.2004 ÔÇ ÏÏèÁ
               //103103103BB^004677.Ð.643.03.2003^17.03.2003 ÌÇÐÔ103103103BB^77.99.20.919.Á.000187.02.04^13.02.2004 ÄÃÑÝÍ

              IntVal := pos('^',StrVal); // ïðîïóñêàåì ïåðâóþ ãàëî÷êó - ñåðèÿ
              delete(strval,1,intval);

              IntVal := pos('^',StrVal);
              strval1 := strval1+ #9+ copy(strval,1,intval-1); // ñåðòèôèêàò
              delete(strval,1,intval);


              IntVal := pos(' ',StrVal); // äàòà âûäà÷è ñåðòèôèêàòà
              strval1 := strval1+ #9+ copy(strval,1,intval-1);
              delete(strval,1,intval);

              intval := Pos('',strval);
              if intval >0
              then Delete(strval,intval,1000);

              strval1 := strval1+ #9+ strval; // ñåðòèôèöèðóþùèé îðãàí


              /////////////////////////////

              StrvAl1 := StrVAl1 + #9 + List1[13];             // ÑÅÐÈß


              StrvAl1 := StrVAl1 + #9 + List1[15]; // Ñðîê ãîäíîñòè (äàòà)
              StrvAl1 := StrVAl1 + #9 + List1[16];             // barcode
              //StrvAl1 := StrVAl1 + #9 + List1[14]; // Äàòà âûïóñêà ïðåïàðàòà


              (*
              StrvAl3 := Copy(StrVal3,FirstI+Length(strval)+1,1000);
              StrvAl := GetWord(StrVAl3,FirstI,';',False);
              while (Length(strval)>0) and  (StrVal[1]='0') do
                 Delete(StrVal,1,1);

              if not UseBarcode
              then STrvAl := ''
              else
              if Length(strVAl)>12 then Delete(StrVal,13,1000);
              *)


             // StrvAl1 := StrVAl1 + #9 + List1[17];            // datereestr


              StrvAl1 := StrVAl1 + #9 + List1[18];           // öåíà ðååñòðà

              //StrvAl3 := Copy(StrVal3,FirstI+Length(strval)+1,1000);
              //StrvAl := GetWord(StrVAl3,FirstI,';',False);

              //createhint(floattostr(pricewithnds)+':'+floattostr(pricewithoutnds)+':'+inttostr(round((PriceWithNDS / PriceWithoutNDS - 1) * 100)));

              if PriceWithoutNDS = 0    // Ñòàâêà ÍÄÑ
              then
                StrVAl1 := strVAl1+#9#9
              else
              try
                strval1 := strval1 +#9 +inttostr(round((PriceWithNDS / PriceWithoutNDS - 1) * 100))+#9;
              except
              end;

              list[i] := StrVal1;
             end;
          end;

          data.text := list.text;



         finally
            List1.free;
            List.free;
         end;
       end
       
       
       
       
       else
            raiseexception('Òàáëèöà èìååò ôîðìàò, íå ñîãëàñîâàííûé ñ ïîñòàâùèêîì. Îáðàòèòåñü â òåõïîääåðæêó');

     finally
       Invoiceslist.free;
       free
     end;

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