using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using WebMVCApi.Models;
using Zack.ASPNETCore;

namespace WebMVCApi.Controllers
{
    //[controller] 当前controller 的名字  [action] 代表controller 里面方法的名字

    //api/[controller]  表示当前controller 里的所有方法都被解析成 /api/Test
    //api/[action]  表示当前controller 里的所有方法都被解析成 /api/GetPerson ,/api/SaveNote 
    [Route("api/")]
    [ApiController]
    public class TestController : ControllerBase
    {

        private IMemoryCache _memoryCache;
        private IMemoryCacheHelper _memoryCacheHelper;

        public TestController(IMemoryCache _memoryCache, IMemoryCacheHelper _memoryCacheHelper) {
            this._memoryCache= _memoryCache;
            this._memoryCacheHelper = _memoryCacheHelper;
        }

        [HttpGet("GetPerson")]
        public Person GetPerson()
        {
            return new Person("zs", "13");
        }

        [HttpPost("SaveNote")]
        public string SaveNote(SaveNoteRequest request)
        {
            string filename = $"{request.Title}.txt";
            System.IO.File.WriteAllText(filename, request.Content);
            return filename;
        }
        [HttpGet("GetId")]
        public IActionResult GetId(int id)
        {
            if (id < 10)
            {
                return Ok(new { id = 10 });
            }
            else {
                //throw new Exception("id 错误");
                return NotFound(id);
            }
        }
        [HttpGet("GetId2")]
        public ActionResult<Object> GetId2(int id)
        {
            if (id < 10)
            {
                return Ok(new { id = 10 });
            }
            else
            {
                //throw new Exception("id 错误");
                return NotFound(id);
            }
        }
        [HttpGet("Add/{i1}/{i2}")]
        public ActionResult<Object> Add(int i1, int i2)
        {
          return i1 + i2;
        }
        [HttpGet("students/school/{schoolName}/class/{classNo}")]
        public ActionResult<Object> GetMessage(string schoolName,[FromRoute(Name = "classNo")] int classNom)
        {
            return new { Id = classNom+6, schoolName=schoolName + "扛把子", };
        }
      
        [HttpPut("UpdatePerson")]
        public async Task<Object> UpdatePerson(int id, Person p1)
        {
            return  _memoryCache.GetOrCreateAsync<String>("val", async (e)=>{
               
                return  $"id {id} 的用户{p1.Name}更新成功 {DateTime.Now}";
            });
        }


        [HttpGet("test1")]
        public async Task<Object> test1(long id)
        {
            return _memoryCacheHelper.GetOrCreateAsync<int>($"Book{id}",async (e) =>
            {
                return 123;
            },10);
        }
    }
}
