// Ñêðèïò èìïîðòà íàêëàäíîé èç ÃÊ "Íàäåæäà-Ôàðì"

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


var
    Header :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    Data :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    ExportAgent :string; // âñå îïðåäåëåíû ïðèëîæåíèåì
    FileName :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;
    OpenDialog :TOpenDialog;
    ThF :TField;
    str,str1 :string;
    Field :TField;
    FPrice_Reg :TField;
    FBarcode :TField;

    str1val :string;
    str2val :string;

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

    FSrokSertif, FSrok, FNameSert, FAmount, FNDS, FNameGoods,
    FFirstPrice,  FSeria, FSertif, FDateSertif, FTamog,
    FCountry, FRegN, FPrice, FNameProducer, FPriceRosn,FSummaNDS :TField;

    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) and (FieldValueList.count>J)
      then Destination := Destination + FieldValueList[j];
      Destination := Destination + #9;
    end;

    procedure AddStr1(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;


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

          if table.findfield('tfact') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('tfact').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('tdata').asstring;
          end
          else if table.findfield('numord') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('numord').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('orderdate').asstring;
          end
          else if table.findfield('num_nak') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('num_nak').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('date_nak').asstring;
          end
          else if table.findfield('ndoc') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('ndoc').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('datedoc').asstring;
          end
          else if table.findfield('DCODE') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('DCODE').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('DATE_DOC').asstring;
          end
          else if table.findfield('NUM_DOC') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('NUM_DOC').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('DATE_DOC').asstring;
          end
          else begin
            raiseexception('Òàáëèöà èìååò ôîðìàò, íå ñîãëàñîâàííûé ñ ïîñòàâùèêîì. Îáðàòèòåñü â òåõïîääåðæêó');
          end;

          data.Clear;

          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          if table.findfield('ndoc')<>nil
          then
            str2val := 'cenanotnds'
          else
            str2val := 'summa';


          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+
           str2val+#9+
          'price_reg'+str1val);

          FPrice_reg := findfield(table,'reestr;PRICE_REES;SUM3','');

          if UseBarcode then
            FBarcode := findfield(table,'barcode;EAN13','')
          else
            FBarcode := nil;


          fsrok := findfield(table,'dataendtov;DATEBEST;SROK_GOD;GDATE;SROK_S;SROK', 'Ñðîê ãîäíîñòè');
          FNameSert := findfield(table,'centrsert;NAMESERTIF;KEM;SERTORG;NMORGS;STRING2','Ñåðòèôèöèðóþùèé îðãàí');

          FAmount := findfield(table,'amount;QUANTIS;COUNT;QNT;KOLVO;VOLUME','Êîëè÷åñòâî');
          FNDS := findfield(table,'nds;procnds;PRC_NDS;NDS_PR;PCT_NDS','Ñòàâêà ÍÄÑ');
          FNameGoods := findfield(table,'name;namegood;NAM_LEK;PRODUCT;NAME_TOVAR','Íàèìåíîâàíèå òîâàðà');

          if table.findfield('ndoc')<>nil
          then
            FFirstPrice := findfield(table,'price2n','Öåíà ïðîèçâîäèòåëÿ')
          else
            FFirstPrice := findfield(table,'price1;PRPROD;cena_zavod;PRO_NNDS;PR_PROIZ','Öåíà ïðîèçâîäèòåëÿ');

          FSeria := findfield(table,'seria;series;seriy;ser;SERIES;SERIA','Ñåðèÿ');
          FSertif := findfield(table,'numdoc;sertif;sertorg;SERT_N;DOCUMENT','Ñåðòèôèêàò');
          FNameProducer := findfield(table,'manufac;FIRMNAME;zavod;firm;PRODUCER;PROIZ','Ïðîèçâîäèòåëü');
          FDateSertif := findfield(table,'docd;DATESERTIF;sertdate;DSTARTS','' {'Äàòà âûäà÷è ñåðòèôèêàòà' â òðåòüåì âàðèàíòå ïîëÿ íå íàøåë});
          FTamog := findfield(table,'gtd;GTDCODE;deklar;numgtd;GTD;GTD','Íîìåð òàìîæåííîé äåêëàðàöèè');
          FCountry := findfield(table,'country;strana;cntr;COUNTRY;COUNTRY','Ñòðàíà-ïðîèçâîäèòåëü');
          FRegn := findfield(table,'regn;REGCODE;SAR_LAB;regnomer;NUMREG;REG_NUM','');   //Ðåãèñòðàöèîííûé êîä
          
          if table.findfield('ndoc')<>nil
          then
            FPrice := findfield(table,'price1','Ñòîèìîñòü òîâàðà (ñ ÍÄÑ â ò.÷.)')
          else
           if table.findfield('SUMOUT')<>nil
             then FPrice := findfield(table,'SUMOUT','Ñóììà çà òîâàð (ñ ÍÄÑ â ò.÷.)')
           else
            FPrice := findfield(table,'summ;SUMALL;summa;SUM_OPL;SUMMA','Ñóììà çà òîâàð (ñ ÍÄÑ â ò.÷.)');


          if table.findfield('ndoc')<>nil
          then
            FSrokSertif := nil
          else
            FSrokSertif := findfield(table,'docend;bestsertif;srok_ser;DENDS;SROK','Ñðîê äåéñòâèÿ ñåðòèôèêàòà');

          fpricerosn := findfield(table,'price_rozn','');


          while not Table.eof do begin

            str := '';

            addstr1(str,fsrok);
            addstr1(str,fsroksertif);
            addstr1(str,FNameSert);
            addstr1(str,FAmount);
            addstr1(str,FNDS);
            addstr1(str,fnamegoods);
            addstr1(str,FFirstPrice);
            addstr1(str,Fseria);
            addstr1(str,FSertif);
            addstr1(str,FNameProducer);
            addstr1(str,FDateSertif);
            addstr1(str,FTamog);
            addstr1(str,FCountry);
            addstr1(str,FREgN);
            addstr1(str,FBarcode);
            addstr1(str,FPrice);
            addstr1(str,FPrice_Reg);

            if useoutprice
            then addstr1(str,fpricerosn);


            //addstr1(str,);

            (*
            str :=
               Table.FieldByName('dataendtov').AsString+#9+
               addstr1(fsroksertif) +
               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;

         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,';');


          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          data.Clear;
          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'+str1val);


          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,'PRODUCER_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); // ïîëÿ íåò ïîêà

              if useoutprice
              then
                addstr(str,list1,'PRICE_ROZN',List2);

              data.Add(str);

            end;
          end;


         finally

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

     finally
       free
     end;

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