/*
 * 运营中心系统设置
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.OpModels;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class SystemSetOperateController : BaseController
    {
        public SystemSetOperateController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }

        #region 运营中心系统设置列表

        /// <summary>
        /// 根据条件查询运营中心系统设置列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(SystemSet data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            string Condition = "";
            Condition += "WebUrl:\"" + data.WebUrl + "\",";
            Condition += "WebName:\"" + data.WebName + "\",";

            if (!string.IsNullOrEmpty(Condition))
            {
                Condition = Condition.TrimEnd(',');
                Condition = ", where: {" + Condition + "}";
            }
            ViewBag.Condition = Condition;
            return View();
        }

        #endregion

        #region 根据条件查询运营中心系统设置列表

        /// <summary>
        /// 运营中心系统设置列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(SystemSet data, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("WebUrl", "2"); //网站地址
            Fields.Add("WebName", "2"); //网站名称

            Dictionary<string, object> obj = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).IndexData("SystemSet", Fields, "Id desc", "False", page, limit);
            
            return Json(obj);
        }

        #endregion

        #region 增加运营中心系统设置

        /// <summary>
        /// 增加或修改运营中心系统设置信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            ViewBag.right = _accessor.HttpContext.Request.Query["right"];

            return View();
        }

        #endregion

        #region 增加运营中心系统设置

        /// <summary>
        /// 增加或修改运营中心系统设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(SystemSet data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("WebUrl", data.WebUrl); //网站地址
            Fields.Add("WebName", data.WebName); //网站名称
            Fields.Add("IndexKeyword", data.IndexKeyword); //首页关键词
            Fields.Add("IndexDescription", data.IndexDescription); //首页简介
            Fields.Add("UploadExt", data.UploadExt); //允许上传类型
            Fields.Add("UploadMaxSize", data.UploadMaxSize); //允许最大上传
            Fields.Add("UploadAutoZoom", data.UploadAutoZoom); //自动缩略图
            Fields.Add("UploadAutoZoomWidth", data.UploadAutoZoomWidth); //自动缩略图宽
            Fields.Add("UploadAutoZoomHeight", data.UploadAutoZoomHeight); //自动缩略图高
            Fields.Add("UploadAutoWater", data.UploadAutoWater); //自动水印
            Fields.Add("UploadWaterPosition", data.UploadWaterPosition); //水印位置
            Fields.Add("UploadWaterPath", data.UploadWaterPath); //水印图片
            Fields.Add("RightInfo", data.RightInfo); //版权信息
            Fields.Add("Address", data.Address); //企业地址
            Fields.Add("Phone", data.Phone); //联系电话
            Fields.Add("WebStatCode", data.WebStatCode); //网站统计代码
            Fields.Add("Logo", data.Logo); //Logo图片

            int Id = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Add("SystemSet", Fields, 0);
            AddSysLog(data.Id.ToString(), "SystemSet", "add");
            opdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改运营中心系统设置

        /// <summary>
        /// 增加或修改运营中心系统设置信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(int Id = 0)
        {
            ViewBag.right = _accessor.HttpContext.Request.Query["right"];

            SystemSet editData = opdb.SystemSet.FirstOrDefault() ?? new SystemSet();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改运营中心系统设置

        /// <summary>
        /// 增加或修改运营中心系统设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(SystemSet data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("WebUrl", data.WebUrl); //网站地址
            Fields.Add("WebName", data.WebName); //网站名称
            Fields.Add("IndexKeyword", data.IndexKeyword); //首页关键词
            Fields.Add("IndexDescription", data.IndexDescription); //首页简介
            Fields.Add("UploadExt", data.UploadExt); //允许上传类型
            Fields.Add("UploadMaxSize", data.UploadMaxSize); //允许最大上传
            Fields.Add("UploadAutoZoom", data.UploadAutoZoom); //自动缩略图
            Fields.Add("UploadAutoZoomWidth", data.UploadAutoZoomWidth); //自动缩略图宽
            Fields.Add("UploadAutoZoomHeight", data.UploadAutoZoomHeight); //自动缩略图高
            Fields.Add("UploadAutoZoomQuality", data.UploadAutoZoomQuality); //自动缩略图质量
            Fields.Add("UploadAutoWater", data.UploadAutoWater); //自动水印
            Fields.Add("UploadWaterPosition", data.UploadWaterPosition); //水印位置
            Fields.Add("UploadWaterPath", data.UploadWaterPath); //水印图片
            Fields.Add("RightInfo", data.RightInfo); //版权信息
            Fields.Add("Address", data.Address); //企业地址
            Fields.Add("Phone", data.Phone); //联系电话
            Fields.Add("WebStatCode", data.WebStatCode); //网站统计代码
            Fields.Add("Logo", data.Logo); //Logo图片
            Fields.Add("StartAdPhoto", data.StartAdPhoto); //App启动图片
            Fields.Add("UploadOss", data.UploadOss);

            SystemSet check = opdb.SystemSet.FirstOrDefault();
            if (check == null)
            {
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Add("SystemSet", Fields, 0);
            }
            else
            {
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("SystemSet", Fields, data.Id);
            }
            AddSysLog(data.Id.ToString(), "SystemSet", "update");
            opdb.SaveChanges();

            return "success";
        }
        public IActionResult AppStart()
        {
            ViewBag.right = _accessor.HttpContext.Request.Query["right"];
            return View();
        }
        [HttpPost]
        public string AppStart(SystemSet data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();            
            Fields.Add("StartAdPhoto", data.StartAdPhoto); //App启动图片
            SystemSet check = opdb.SystemSet.FirstOrDefault();
            if (check == null)
            {
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Add("SystemSet", Fields, 0);
            }
            else
            {
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("SystemSet", Fields, data.Id);
            }
            AddSysLog(data.Id.ToString(), "SystemSet", "AppStart");

            Models.FileUpdateInfo fileUpdateInfo = db.FileUpdateInfo.FirstOrDefault(m => m.FileName == data.StartAdPhoto);
            if (fileUpdateInfo == null)
            {
                string Path = data.StartAdPhoto.Substring(0, data.StartAdPhoto.LastIndexOf("/") + 1);
                if (Path.Contains("static"))
                {
                    Path = Path.Substring(Path.IndexOf("static"));
                }
                string FileName = data.StartAdPhoto.Substring(data.StartAdPhoto.LastIndexOf("/") + 1);
                db.FileUpdateInfo.Add(new Models.FileUpdateInfo()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    FileName = FileName,
                    Path = Path,
                    VersionNum = 1,
                });
            }
            opdb.SaveChanges();

            return "success";
        }
        public JsonResult UploadPhoto([FromForm] IFormCollection rf)
        {
            IFormFile imgFile = rf.Files[0];
            SystemSet set = opdb.SystemSet.FirstOrDefault() ?? new SystemSet();
            string path = MySystemLib.SystemPublicFuction.GetPicPath(imgFile, "skin/app/default/static/images/", function.ReadInstance("/WebRootPath.txt"), "startadphoto" + DateTime.Now.ToString("yyMMddHHmm"));
            return Json(new AppResultJson() { Status = "1", Info = "", Data = path.Replace("wwwroot/", "") });
        }
        #endregion

        #region 删除运营中心系统设置信息

        /// <summary>
        /// 删除运营中心系统设置信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "SystemSet", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Delete("SystemSet", id);
            }
            opdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "SystemSet", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("SystemSet", Fields, id);
            }
            opdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "SystemSet", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("SystemSet", Fields, id);
            }
            opdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Sort("SystemSet", Sort, Id);

            AddSysLog(Id.ToString(), "SystemSet", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                opdb.SystemSet.Add(new SystemSet()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                opdb.SaveChanges();
            }
            AddSysLog("0", "SystemSet", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(SystemSet data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("WebUrl", "2"); //网站地址
            Fields.Add("WebName", "2"); //网站名称

            Dictionary<string, object> obj = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).IndexData("SystemSet", Fields, "Id desc", "False", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "SystemSet", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
