using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils;
using PageAdmin.Web.Filter;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.Admin.Controllers
{
    public class OnlineUpgradeController : BaseController
    {

        public OnlineUpgradeController() : base("Tool/")
        {
        }

        [HttpGet]
        /// <summary>
        /// 默认首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            OnlineUpgradeBLL onlineUpgradeBLL = new OnlineUpgradeBLL();
            string upgradeApi = CmsConfig.Config().CmsUpgradeApi;
            HttpRequestHelper httpRequestHelper = new HttpRequestHelper();
            string result;
            try
            {
                result=onlineUpgradeBLL.GetUpgradeList();
                ViewBag.CurrentVersion = onlineUpgradeBLL.CurrentVserion;
                ViewBag.UpgradeList = result;
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }

            return View();
        }

        [AjaxOnly]
        [HttpPost]
        /// <summary>
        /// 下载升级文件
        /// </summary>
        /// <returns></returns>
        public JsonResult DownLoad(FormCollection form)
        {
            OnlineUpgradeBLL onlineUpgradeBLL = new OnlineUpgradeBLL();
            TipsInfo tipsInfo = new TipsInfo();
            string version = form["version"];
            string package = form["package"];
            if (!StringHelper.IsVersion(version) || !StringHelper.IsUrl(package))
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "version或package参数错误";
                return base.Json(tipsInfo);
            }
            tipsInfo = onlineUpgradeBLL.DownLoadUpgradePackage(package, version);
            LogHelper.SaveLog(LogTypeEnum.UpgradeLog, "下载"+ version+"升级文件("+tipsInfo.Msg+")", CurrentUser);
            return base.Json(tipsInfo);
        }


        /// <summary>
        /// 重启进程
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public JsonResult RestartApplication(FormCollection form)
        {
            SysHelper.RestartApplication();
            TipsInfo tipsInfo = new TipsInfo();
            return base.Json(tipsInfo);
        }



        [AjaxOnly]
        [HttpPost]
        /// <summary>
        /// 重启后模拟访问
        /// </summary>
        /// <returns></returns>
        public JsonResult Visitor(FormCollection form)
        {
            TipsInfo tipsInfo = new TipsInfo();
            return base.Json(tipsInfo);
        }

    }
}