// Ýêñïîðò çàÿâîê â ÑÈÀ Èíòåðíåéøíë.
// Ôîðìàò âïåðâûå èñïîëüçîâàëñÿ â Ñàðàòîâå (Ôàðìöåíòð)

var // ïðåäîïðåäåëåííûå ïåðåìåííûå

  Dataset :TDataset;
  VarExportEMail :string;
  VarName_Storage :variant;
  VarID_Storage :variant;
  varname_org :variant;
  varid_orgs :variant;
  VarDate_Doc :variant;
  varTime_Doc :tdatetime;
  VarNumber_Doc :variant;
  VarID :variant;
  VarPreq_Sum :variant;
  VarRows_count :variant;
  VarExportReport :string;
  VarINfo :string;
  VarExportOutPreqOriginalPrices :boolean; // ôëàã, íóæíî ëè ýêñïîðòèðîâàòü öåíó îðèãèíàëüíóþ èç ïðàéñ-ëèñòà. èíà÷å - öåíó, óêàçàííóþ â çàÿâêå


const
   MessageSubject = 'Ýëåêòðîííàÿ çàÿâêà SolPrice';


var
    MailMessage :Variant;
    ExportFilename :string;
    Bodystr :string;

    FileStr :string;
    strval :string;
    DirName :string;

function GetPrice :double;
begin
  if VarExportOutPreqOriginalPrices
  then result := Dataset.fieldbyname('price_pr').asfloat
  else result := Dataset.fieldbyname('price').asfloat;
end;


procedure AddStr(var DestStr: string; SourceStr :string;UseCR :boolean = true);
begin
  if DestStr >'' then begin
     if UseCR then DestSTr := DestStr + #13;
     DestStr := DestStr + #10;
  end;

  DestStr := DestStr + SourceStr;
end;

function ifthen_1(BoolVal :boolean; trueval,falseval :string) :string;
begin
  if boolval
  then result := trueval
  else result := falseval
end;

procedure CheckParams;
begin
   if asint64(varid_storage)=0
   then begin
     varid_storage := id_storage_current;
   end;
   if (asint64(varid_storage)<>0) and (varname_storage='')
   then begin
     varname_storage := dbQueryvalue('select name from orgs where id = :id ',[varid_storage]);
   end;
   if asint64(varid_storage)<>0
   then begin
     id_org_main := coalesce_int64( asint64( DBQueryvalue('select id_parent_org from orgs where id = :id',[VARID_STORAGE]))
                                    ,id_org_main);
   end;
end;

begin
   Checkparams;


   filestr := '';
   bodystr := '';



   strval := strpadright('Êëèåíò',13)+': '
             +coalesce_string(asstring(getexternalorgcode(id_org_main,varid_orgs)),
                              asstring(getexternalorgcode(0,varid_orgs))
                             )
             +', '
             + asstring(dbQueryvalue('select name from orgs where id = :id',[id_org_main]));

   AddStr(FileStr,strval);
   addstr(BodyStr,strval,true);


   //showmessage(asstring(varid_orgs)+':'+asstring(varname_org));

   strval := strpadright('Ïîëó÷àòåëü',13)+': '
            + coalesce_string(asstring(getexternalorgcode(asint64(varid_storage),varid_orgs)),
                              asstring(getexternalorgcode(id_org_main,varid_orgs)),
                              asstring(getexternalorgcode(0,varid_orgs))
                             )
            +', '
            + coalesce_string(asstring(DBQueryvalue('select address from orgs where id = :id',[VARID_STORAGE])),
                             asstring(DBQueryvalue('select address from orgs where id = :id',[id_org_main])));
   AddStr(FileStr,strval);
   addstr(BodyStr,strval,true);

   strval := strpadright('Îïëàòà',13)+': 0';
   AddStr(FileStr,strval);
   //addstr(BodyStr,strval);

   strval := strpadright('ID çàêàçà',13)+': '+asstring(varID);
   AddStr(FileStr,strval);

   strval := strpadright('Äàòà çàêàçà',13)+': '+formatdatetime('dd.mm.yyyy hh:nn:ss',vardate_doc+vartime_doc);
   AddStr(FileStr,strval);
   addstr(BodyStr,strval,true);

   dataset.last; // âäðóã ýòî fibdataset, è îí íå äîáðàí

   strval := strpadright('Ïîçèöèé',13)+': '+asstring(dataset.recordcount);
   AddStr(FileStr,strval);
   addstr(BodyStr,strval,true);


   strval := strpadright('Âåðñèÿ EXE',13)+': ';
   AddStr(FileStr,strval);
   strval := strpadright('Âåðñèÿ CFG',13)+': ';
   AddStr(FileStr,strval);
   strval := strpadright('Ñòàòóñ CFG',13)+': ';
   AddStr(FileStr,strval);

   strval := strpadright('Ïðàéñ-ëèñò',13)+': '
            +formatdatetime('dd.mm.yyyy hh:nn:ss',
             asdatetime(dbQueryValue('select first 1 a.update_org from prices_headers_upd a '
                                     +' join prices_rows b on a.id = b.id_prices_headers '
                                     +' join out_preq_rows c on b.id = c.id_prices_rows '
                                     +' where c.id_out_preq = :id',[varid]))
            );
   AddStr(FileStr,strval);


   strval := strpadright('Êîììåíòàðèé',13)+': '+asString(VarInfo);
   AddStr(FileStr,strval);
   addstr(BodyStr,strval,true);


   AddStr(Filestr,''); // îòñòóï

   dataset.first;
   while not dataset.eof do
   begin

     addstr(Filestr,
            coalesce_string( dataset.fieldbyname('price_code').asstring, dataset.fieldbyname('price_code_goods').asstring)
            +stringofchar(' ',9)+
            dataset.fieldbyname('quantity').asstring
           );


     dataset.next;
   end;

   AddStr(Filestr,''); // îòñòóï


    ExportFilename :=  gettempdir + 'Çàÿâêà_îò_'+formatdatetime('yyyy_mm_dd_hh-nn-ss',vardate_doc+vartime_doc)+'.txt';   //getuniquefilename(gettempdir+'
    StringToFile(ExportFilename,FileStr);

    if pos('@',varexportemail)>0
    then begin

      MailMessage := CreateOleObject('mailprocessor.mpmailmessage');

      if not MailMessage.srv.connected
      then MailMessage.SRV.ConnectWP('Ïîëüçîâàòåëü','1');

      if not MailMessage.srv.connected
      then begin
        CreateHintE('Íå ìîãó ïðèñîåäèíèòüñÿ.');
        exit;
      end;


      MailMessage.ID := 0;
      MailMessage.Recipients :=  varexportemail;


      MailMessage.Subject := MessageSubject;

      MailMessage.Body := BodyStr;

      MailMessage.AddAttachment(ExportFilename);

      if (VarExportReport>'')
         and fileexists(VarExportReport)
      then
        MailMessage.AddAttachment(VarExportReport);


      MailMessage.Save;

    end
    else begin // çíà÷èò òàì óêàçàí êàòàëîã, ñîõðàíÿåì â ýòîì êàòàëîãå
      DirName := includetrailingpathdelimiter(VarExportEmail);
      ForceDirectories(Dirname);
      CopyFile(ExportFilename, DirName + ExtractFileName(ExportFileName));

    end;

    deletefile(exportfilename);

end.
