// Ñêðèïò èìïîðòà íàêëàäíîé èç Êàòðåí (Ñàðàòîâ)

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


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

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

var Table :TTable;
    num_doc :string;
    Item :variant;
    i,k :integer;
    FileName :string;
    OpenDialog :TOpenDialog;
    ThF :TField;
    str,str1 :string;
    Field :TField;
    FPrice_Reg :TField;
    FBarcode :TField;

    List :TStringList;
    List1 :TSTringList;
    List2 :Tstringlist;

    function StrToDTStr( str :string) :string;
    begin
      if length(str)<>8
      then begin
        result := str;
      end
      else begin
        result := copy(str,7,2)+'.'+copy(str,5,2)+'.'+ copy(str,1,4);
      end;
    end;

    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    end;

    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;

    procedure AddStr(var Destination :string; FieldNameList :tstringLIst; const FieldName :string; FieldValueList :TStringlist);
    var j :integer;
    begin
      j := FieldNameList.indexof(FieldName);
      //createhint('i='+inttostr(i)+',Name =' +FieldName+',NC ='+inttostr(FieldNamelist.count)+', VC='+inttostr(fieldvaluelist.count));
      if j>=0
      then Destination := Destination + FieldValueList[j];
      Destination := Destination + #9;
    end;

 begin
     FileName := '';
     OpenDialog := TOpenDialog.create(nil);
     try
       OpenDialog.Title := 'Óêàæèòå ôàéë';
       OpenDialog.FileName  := AppIniFile.readstring('plugins_katren','filename','');
       opendialog.initialdir := extractfilepath(opendialog.filename);
       OpenDialog.Filter := 'Ôàéëû-íàêëàäíûå(*.dbf,*.txt)|*.dbf;*.txt|Âñå ôàéëû(*.*)|*.*';
       while  OpenDialog.execute do begin
         if not fileexists(OpenDialog.FileName) then CreateHint('Óêàæèòå ïðàâèëüíî ôàéë ')
         else begin
           Filename := OpenDialog.FileName;
           AppIniFile.writestring('plugins_katren','filename',OpenDialog.filename);
           break;
         end;
       end;
     finally
       OpenDialog.free;
     end;

     if FileName = '' then exit;

     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);
          //SetTableLangDriver(Table,'db866ru0');
         // CheckDBFCP(Table.TableName,38); //866DOS

          Table.Open;
          Table.First;

          data.Clear;

          if table.findfield('tfact') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('tfact').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('tdata').asstring;



              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+ //+'cenanotnds'
                'barcode'+#9+'summa'+#9+'price_reg');

              FPrice_reg := table.findfield('reestr');

              if UseBarcode then
                FBarcode := Table.findfield('barcode')
              else
                FBarcode := nil;


              while not Table.eof do begin

                try
                  str1 := table.fieldbyname('docend').asstring;

                  (* óñòàðåëî
                      formatdatetime('dd.mm.yyyy',
                      EncodeDate(
                        strtoint(Copy( Table.FieldByName('docend').AsString,1,4)),
                        strToInt(Copy( Table.FieldByName('docend').AsString,5,2)),
                        strToInt(Copy( Table.FieldByName('docend').AsString,7,2))
                      ))  *);


                except
                  str1  := '';
                end;

                str :=
                   Table.FieldByName('dataendtov').AsString+#9+
                   Str1 +#9+
                   Table.FieldByName('centrsert').AsString+#9+
                   Table.FieldByName('amount').AsString+#9+
                   Table.FieldByName('nds').AsString+#9+
                   Table.FieldByName('name').AsString+#9+
                   Table.FieldByName('price1').asstring+#9+
                   Table.FieldByName('seria').AsString+#9+
                   Table.FieldByName('numdoc').AsString+#9+
                   Table.FieldByName('manufac').AsString+#9+
                   Table.FieldByName('docd').AsString+#9+
                   Table.FieldByName('gtd').AsString+#9+
                   Table.FieldByName('country').AsString+#9+
                   Table.FieldByName('regn').AsString+#9;

                if (FBarcode<>nil)
                then Str := Str + FBarcode.asstring;
                Str := Str + #9;

                Str := Str + Table.FieldByName('SUMM').AsString;
                Str := Str + #9;

                if (FPrice_Reg<>nil) and (FPrice_Reg.asFloat <>0)
                then Str := Str +FPrice_Reg.asstring;
                // else îñòàâëÿåì ïóñòûì

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

          end
          else
          if table.findfield('docname') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('docname').asstring;
             Header.Values[ExportNakladData] := StrTodtStr( table.fieldbyname('datedoc').asstring);
             Header.Values[ExportNakladSROK] := strtodtstr( table.fieldbyname('datepay').asstring);

              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+ //+'cenanotnds'
                'barcode'+#9+'cenanotnds'+#9+'price_reg');

              FPrice_reg := table.findfield('reestr');

              if UseBarcode then
                FBarcode := Table.findfield('barcode')
              else
                FBarcode := nil;


              while not Table.eof do begin


                str :=
                   Table.FieldByName('dateb').AsString+#9+
                   table.fieldbyname('dateb').asstring +#9+
                   Table.FieldByName('sertwho').AsString+#9+
                   Table.FieldByName('quant').AsString+#9+
                   Table.FieldByName('nds').AsString+#9+
                   Table.FieldByName('good').AsString+#9+
                   Table.FieldByName('priceent').asstring+#9+
                   Table.FieldByName('serial').AsString+#9+
                   Table.FieldByName('sert').AsString+#9+
                   Table.FieldByName('enterp').AsString+#9+
                   Table.FieldByName('dates').AsString+#9+
                   {Table.FieldByName('gtd').AsString+}#9+
                   Table.FieldByName('country').AsString+#9+
                   {Table.FieldByName('regn').AsString+}#9;

                if (FBarcode<>nil)
                then Str := Str + FBarcode.asstring;
                Str := Str + #9;

                Str := Str + Table.FieldByName('pricewonds').AsString;
                Str := Str + #9;

                if (FPrice_Reg<>nil) and (FPrice_Reg.asFloat <>0)
                then Str := Str +FPrice_Reg.asstring;
                // else îñòàâëÿåì ïóñòûì

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

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

         finally
            Table.free;
         end;
       end
       else if uppercase(extractfileext(filename))='.TXT'
       then begin


         //DATE_ORDER;NUM_ORDER;DATE_TO_PAID;ORDER_SUM;ORDER_NDS_SUM


         List := Tstringlist.create;
         List1 := Tstringlist.create;
         LIst2 := Tstringlist.create;
         try

          List.loadfromfile(filename);
          if (list.count<3) or (pos('DATE_ORDER;NUM_ORDER;DATE_TO_PAID;ORDER_SUM;ORDER_NDS_SUM',list[0])=0)
          then
            raiseexception('Òàáëèöà èìååò ôîðìàò, íå ñîãëàñîâàííûé ñ ïîñòàâùèêîì. Îáðàòèòåñü â òåõïîääåðæêó');

          StringtoList( list[1],List2,';');

          if list2.count<5
          then
            raiseexception('Òàáëèöà èìååò ôîðìàò, íå ñîãëàñîâàííûé ñ ïîñòàâùèêîì (êîëè÷åñòâî ïîëåé â çàãîëîâêå = '+inttostr(list2.count)+'). Îáðàòèòåñü â òåõïîääåðæêó');


          Header.Values[ExportNakladNom] := List2[1];
          Header.Values[ExportNakladData] := List2[0];
          Header.Values[ExportNakladSROK] := List2[2];

          StringtoList( list[2],List1,';');

          data.Clear;
          data.Add('srok'+#9+'sroksertif'+#9+'sertifname'+#9+
            'kol'+#9+'nds'+#9+
            'name'+#9+'firstcenaplusnds'+#9+'seria'+#9+'sertif'+#9+
            'producername'+#9+
            'datesertif'+#9+
            'tamog'+#9+
            'countryname'+#9+
            'regn'+#9+ //+'cenanotnds'
            'barcode'+#9+'summa'+#9+'price_reg');


          for i := 3 to list.count-1 do
          begin
            StringtoList( list[i],List2,';');

            if list2.count=List1.count
            then begin

            //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

              Str := '';

              AddStr(Str,List1,'BEST_BEFORE',List2);
              AddStr(Str,List1,'CERTIFICATE_SROK',List2);
              AddStr(Str,List1,'CERTIFICATE_ORG',List2);
              AddStr(Str,List1,'QUANT',List2);
              AddStr(Str,List1,'PERCENT_NDS',List2);
              AddStr(Str,List1,'GOODS',List2);
              AddStr(Str,List1,'PRICE',List2);
              AddStr(Str,List1,'SERIES',List2);
              AddStr(Str,List1,'CERTIFICATE_SERIES',List2);
              AddStr(Str,List1,'PRODUCER',List2);
              AddStr(Str,List1,'CERTIFICATE_DATE',List2);
              AddStr(Str,List1,'GTD',List2);
              AddStr(Str,List1,'COUNTRY',List2);
              AddStr(Str,List1,'REGN',List2); // òàêîãî ïîëÿ íåò ó íèõ ïîêà
              AddStr(Str,List1,'BARCODE',List2); // ïîëÿ íåò ïîêà
              AddStr(Str,List1,'SUM',List2);
              AddStr(Str,List1,'PRICE_REGISTRY',List2); // ïîëÿ íåò ïîêà
              data.Add(str);
            end;
          end;

         finally

            LIst2.free;
            LIst1.free;
            List.free;
         end;
       end
       else CreateHintE('Äàííûé ôîðìàò íàêëàäíûõ îò Êàòðåí íå èññëåäîâàí, îáðàòèòåñü â òåõïîääåðæêó');

     finally
       free
     end;

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