using CliWrap;
using CliWrap.Buffered;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Web.Administration;

namespace UseSQLQueryData.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IISController : ControllerBase
    {

        [HttpPost()]
        public async Task<ReturnInfo> Recly()
        {
            var dt = DateTime.Now;
            var span = new TimeSpan(0, 1, 0);
            ReturnInfo r = new ReturnInfo();
            try
            {
                if (dt - Program.Dt > span)
                {

                    string Key = "IISRecycle";
                    CSRedisCacheHelper.redis3.Set(Key,1);
                    //using (ServerManager serverManager = new ServerManager())
                    //{
                    //    var pool = serverManager.ApplicationPools["DefaultAppPool"];
                    //    if (pool != null)
                    //    {
                    //        pool.Recycle();
                    //        r.isok = true;
                    //    }
                    //    else
                    //    {
                    //        r.isok = false;
                    //    }
                    //}

                    //Program.Dt = DateTime.Now;
                    //var cmd = await Cli.Wrap("1.cmd")
                    //.WithWorkingDirectory("D:\\BLW_Data\\cricsSQL")
                    //.ExecuteBufferedAsync();


                    //var result = await Cli.Wrap(@"C:\Windows\System32\inetsrv\appcmd.exe")
                    // .WithArguments("recycle apppool /apppool.name:DefaultAppPool")
                    // .ExecuteBufferedAsync();

                    //if (result.ExitCode == 0)
                    //{
                    //    Console.WriteLine("应用程序池回收成功！");
                    //    Console.WriteLine(result.StandardOutput);
                    //}
                    //else
                    //{
                    //    Console.WriteLine($"回收失败，错误代码: {result.ExitCode}");
                    //    Console.WriteLine(result.StandardError);
                    //}
                    r.isok = true;
                }
                else
                {
                    r.isok = false;
                    r.message = "1分钟之间只能回收一次";
                }
            }
            catch (Exception ex)
            {
                r.isok = false;
                r.message = ex.Message;
            }
            return r;
        }
    }
}
