// Скрипт импорта накладной из МИАМЕД

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;

    List :TStringList;
    List1 :TSTringList;
    List2 :Tstringlist;

    FSrokSertif, FSrok, FNameSert, 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('plugins_miamed','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('plugins_miamed','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('NUMDOC') <> nil
          then begin
             Header.Values[ExportNakladNom] := table.fieldbyname('NUMDOC').asstring;
             Header.Values[ExportNakladData] := table.fieldbyname('DATEDOC').asstring;
          end
          else begin
            raiseexception('Таблица имеет формат, не согласованный с поставщиком. Обратитесь в техподдержку');
          end;

          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'
            'barcode'+#9+
            'summa'+#9+
            'price_reg'+str1val);

          FPrice_reg := findfield(table,'reestr','');
          if UseBarcode then
            FBarcode := findfield(table,'barcode','')
          else
            FBarcode := nil;
          fsrok := findfield(table,'DATAENDTOV;DATEBEST;SROK_GOD;GDATE', 'Срок годности');
          FNameSert := findfield(table,'CENTRSERT;NAMESERTIF;KEM;SERTORG','Сертифицирующий орган');
          FAmount := findfield(table,'amount;QUANTIS;COUNT;QNT','Количество');
          FNDS := findfield(table,'nds;procnds;PRC_NDS;NDS','Ставка НДС');
          FNameGoods := findfield(table,'name;namegood;NAM_LEK;NAME','Наименование товара');
          FFirstPrice := findfield(table,'PRICEMAN','Цена производителя');
          FSeria := findfield(table,'seria;series;seriy;SERIES','Серия');
          FSertif := findfield(table,'sertif;SERTIF','Сертификат');
          FNameProducer := findfield(table,'manufac;FIRMNAME;zavod;MANUFAC','Производитель');
          FDateSertif := findfield(table,'docd;DATESERTIF;SERTDATE','' {'Дата выдачи сертификата' в третьем варианте поля не нашел});
          FTamog := findfield(table,'gtd;GTDCODE;deklar;GTD','Номер таможенной декларации');
          FCountry := findfield(table,'country;strana;COUNTRY','Страна-производитель');
          FBarcode := findfield(table,'EAN13','Шрихкод'); //findfield(table,'regn;REGCODE;SAR_LAB','Регистрационный код');
          FPrice := findfield(table,'summ;SUMALL;summa;SUMPAY','Сумма за товар (с НДС в т.ч.)');
          FSrokSertif := findfield(table,'docend;bestsertif;srok_ser;SERTEND','Срок действия сертификата');
          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,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.
