using System;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StaffManagement.Database;
using StaffManagement.Extensions;

namespace StaffManagement.Controllers
{
    /// <summary>
    /// 控制器类基类
    /// </summary>
    //[Route("[Controller]/[Action]")]
    public abstract class ControllerBase<LoggerType>:Controller
    {
        /// <summary>
        /// 日志记录服务
        /// </summary>
        public ILogger Logger { get; set; }
        /// <summary>
        /// 服务集合
        /// </summary>
        public IServiceProvider Services { get; set; }
        /// <summary>
        /// 数据库
        /// </summary>
        public SMDbContext Db { get; set; }
        /// <summary>
        /// 缓冲帮助器
        /// </summary>
        public CacheHelper Cache { get; private set; }
        /// <summary>
        /// 获取请求的方法前缀
        /// </summary>
        protected string Prefix {
            get {
                var con = this.RouteData.Values["controller"];
                var ac = this.RouteData.Values["action"];
                return $":{con}:{ac}";
            }
        }

        /// <summary>
        /// 通过日志组件和服务集合生成控制器
        /// </summary>
        /// <param name="logger">控制器日志组件</param>
        /// <param name="service">服务集合</param>
        public ControllerBase(ILogger<LoggerType> logger,IServiceProvider service) {
            this.Logger = logger;
            this.Services = service;
            this.Db = service.GetService<SMDbContext>();
            this.Cache = service.GetService<CacheHelper>();
        }

        /// <summary>
        /// 从对象序列化字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>字符串</returns>
        protected string JsonSerialize<T>(T obj) {
            return JsonSerializer.Serialize<T>(obj,new JsonSerializerOptions {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
            });
        }
        /// <summary>
        /// 从字符串反序列化对象
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <returns>对象实例</returns>
        protected T JsonDeserialize<T>(string json) {
            return JsonSerializer.Deserialize<T>(json);
        }
    }
}
