// Скрипт импорта накладной от Арал Плюс

const UseBarcode = true; // определяет, будет ли использоваться штрихкод, поставляемый поставщиком
const UseOutPrice = false; // определяет, нужно ли использовать поле "цена розницы"


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;
    strval :string;

    List :TStringList;
    List1 :TSTringList;
    List2 :Tstringlist;

    FSrokSertif, FSrok, FAmount, FNDS, FNameGoods,
    FFirstPrice,  FSeria, FSertif, FDateSertif, FTamog,
    FCountry, FRegN, FPrice, FNameProducer, FNameSertif,FPriceRosn :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
     if filename = ''
     then begin
       OpenDialog := TOpenDialog.create(nil);
       try
         OpenDialog.Title := 'Укажите файл';
         OpenDialog.FileName  := AppIniFile.readstring(extractfilenamewithoutext(selfscript.filename),'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(extractfilenamewithoutext(selfscript.filename),'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;

          //strval := extractfilenamewithoutext(filename);
          //while (length(strval)>0) and (not isdigit(strval[1]) or (strval[1]='0')) do delete(strval,1,1);
          Header.Values[ExportNakladNom] := strval;



          if table.findfield('ndoc') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('ndoc').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('datedoc').asstring;
             //Header.Values[ExportNakladSROK] := table.fieldbyname('datepay').asstring;
          end
          else
            RaiseException('Файл имеет не согласованный с поставщиком формат');


          data.Clear;

          if UseOutPrice
          then Str1VAl := #9+'rs_cena'
          else Str1VAl := '';


          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' summa
            'barcode'+#9+'cenanotnds'+#9+'price_reg'+str1val);

          FPrice_reg := findfield(table,'rpice;cenareestr;regprc;reestr','');

          if UseBarcode then
            FBarcode := findfield(table,'barcode;ean13;bar_code','')
          else
            FBarcode := nil;


          FNameGoods := findfield(table,'name','Наименование товара');
          FNameProducer := findfield(table,'firm','Производитель');
          FCountry := findfield(table,'cntr','Страна-производитель');
          FAmount := findfield(table,'qnt','Количество');
          FSeria := findfield(table,'ser','Серия');
          fsrok := findfield(table,'gdate', 'Срок годности');
          FTamog := findfield(table,'numgtd','Номер таможенной декларации');
          FSertif := findfield(table,'sertif','Сертификат');
          FDateSertif := findfield(table,'datemade','' {'Дата выдачи сертификата' в третьем варианте поля не нашел});
          FNameSertif := findfield(table,'sertorg','Сертифицирующий орган');
          FRegn := findfield(table,'reg','');
          FNDS := findfield(table,'nds','Ставка НДС');
          FFirstPrice := findfield(table,'price1','Цена производителя'); // третий вариант - под вопросом: я не нашел поле, отвечающее за цену производителя, вставил цену реестра

          FPrice := findfield(table,'price2N','Цена без НДС ндс');
          FSrokSertif := findfield(table,'sertdate','');



          fpricerosn := nil; //findfield(table,'price_rozn','');


          while not Table.eof do begin

            str := '';

            addstr1(str,fsrok);
            addstr1(str,fsroksertif);
            addstr1(str,FNameSertif);
            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;

          //data.savetofile('c:\temp\1.txt');

          //createhinti(table.tablename);

         finally
            Table.free;
         end;
       end
       else CreateHintE('Данный формат накладных от Надежда-Фарм не исследован, обратитесь в техподдержку');

     finally
       free
     end;

     createhint('Операция завершена');
 end.
