using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using AutoMapper.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Distributed;
using SignTokenApi.IRepositories;
using MongoDB.Bson;
using MadRunFabric.Model;

namespace SignTokenApi.Controllers
{
    [ApiVersion("6.0")]
    [AllowAnonymous]
    [Produces("application/json")]
    [Route("api/Info")]
    public class InfoController : BaseController
    {

        private readonly ILogger<InfoController> _logger;
        private readonly IDistributedCache _cache;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_Role_InfoRepository _sys_roleinfoRepository;

        public InfoController(IDistributedCache cache, ISys_User_AccountRepository Sys_User_AccountRepository, ISys_Role_InfoRepository sys_roleinfoRepository, ILogger<InfoController> logger)
        {
            _cache = cache;
            _sys_user_accountRepository = Sys_User_AccountRepository;
            _sys_roleinfoRepository = sys_roleinfoRepository;
            _logger = logger;
        }


        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { $"版本信息 {RequestedApiVersion}", "开发团队: Mad Fun Fabric"};
        }

        protected ApiVersion RequestedApiVersion => HttpContext.GetRequestedApiVersion();

        /// <summary>
        /// 初始化用户表
        /// </summary>
        /// <returns></returns>
        [HttpGet("Init")]
        public async Task<IActionResult> Init()
        {
            //await _Sys_User_AccountRepository.RemoveAll();
            //await _sys_roleinfoRepository.RemoveAll();
            var count = await _sys_user_accountRepository.Count(_ => true);
            if (count > 0) { return Error("初始化用户信息失败，因为当前数据表中存在数据！"); }

            var objectid = ObjectId.GenerateNewId().ToString();

            Sys_Role_Info role = new Sys_Role_Info()
            {
                id = objectid,
                role_code = "admin",
                role_name = "系统维护",
                create_uid = "8000"
            };

            Sys_User_Account account = new Sys_User_Account()
            {
                usercode = "8000",
                username = "admin",
                password = SecureHelper.GetMD5("123456"),
                role_id = objectid
            };

            var role_result = await _sys_roleinfoRepository.Add(role);

            var account_result = await _sys_user_accountRepository.Add(account);

            if (role_result && account_result)
            {
                return Success("初始化用户信息成功！");
            }
            else
            {
                return Error("初始化用户信息失败！");
            }
        }

    }
}