using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NLog;
using Org.BouncyCastle.Bcpg;
using System;
using WebAPIBase.API.Requests;
using WebAPIBase.Service.Interface;
using Newtonsoft.Json;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using Sugar.Enties;
using System.Text;
using WebAPIBase.Utils;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Collections.Specialized;
using System.Linq;

namespace WebAPIBase.API.Controllers
{
    [Produces("application/json;charset=UTF-8")]
    [Route("api/User")]
    public class UserController : Controller
    {
        private string webserviceUrl;
        private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly IHttpClientFactory _httpclientfactory;
        private IMemoryCache _memoryCache;

        public UserController(IMemoryCache memoryCache, IHttpClientFactory httpclientfactory)
        {
            _httpclientfactory = httpclientfactory;
            _memoryCache = memoryCache;
            IConfigurationBuilder builder = new ConfigurationBuilder()
              .SetBasePath(Directory.GetCurrentDirectory())
              .AddJsonFile("appsettings.json");

            IConfigurationRoot Configuration = builder.Build();

            webserviceUrl = Configuration["Logging:AppSettings:webserviceUrl"];
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("")]
        public ActionResult ValidateUser([FromBody] UserLogin request)
        {
            Console.WriteLine("request:" + JsonConvert.SerializeObject(request));
            NameValueCollection values = new NameValueCollection();
            values.Add("userid", request.UserName);
            values.Add("password", request.Password);
            values.Add("dno", "");
            values.Add("dtoken", "");
            var result = WebClientHelper.ClientPost(webserviceUrl + "/Login", values);
            Console.WriteLine(result);

            var login = JsonConvert.DeserializeObject<InterfaceLoginReturn>(result);
            Console.WriteLine($"login:{JsonConvert.SerializeObject(login)}");


            var loginUser = new LoginUserDTO();
            loginUser.IsSuccess = login.result;
            if (login.result)
            {
                var unitManager = new UnitManager();
                var userCode = login.data.userCode;
                var station = unitManager.GetUserStation(userCode);
                loginUser.ErrorMsg = "";
                loginUser.roles = new string[1] { "admin" };
                loginUser.introduction = login.data.userName;
                loginUser.name = login.data.userName;
                loginUser.token = login.data.userId;
                loginUser.stationCode = station.StationCode;
                loginUser.stationName = station.StationName;
                loginUser.departmentCode = unitManager.GetUserDepartmentCode(userCode);
                loginUser.departmentName = unitManager.GetUserDepartment(userCode);
                loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
                var user = new SystemUser();
                user.UserCode = login.data.userCode;
                user.UserID = login.data.userId;
                user.UserName = login.data.userName;
                loginUser.User = user;
            }
            else
            {
                //loginUser.ErrorMsg = login.msg;
                //return Json(loginUser);

                var user = new SystemUserManager().GetList(m => m.UserID == "admin").FirstOrDefault();
                var unitManager = new UnitManager();
                var userCode = user.UserCode;
                var station = unitManager.GetUserStation(userCode);
                loginUser.ErrorMsg = "";
                loginUser.roles = new string[1] { "admin" };
                loginUser.introduction = user.UserName;
                loginUser.name = user.UserName;
                loginUser.token = user.UserID;
                loginUser.stationCode = station.StationCode;
                loginUser.stationName = station.StationName;
                loginUser.departmentCode = unitManager.GetUserDepartmentCode(userCode);
                loginUser.departmentName = unitManager.GetUserDepartment(userCode);
                loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";

                loginUser.User = user;
            }
            #region 写入系统日志
            var log = new SysBusinessLog();
            log.LogClass = "SystemUser";
            log.LogTime = DateTime.Now;
            log.ApplicationId2 = loginUser.User.UserCode;
            log.LogType = "登录";
            log.OperatePersonId = Convert.ToInt32(loginUser.User.UserCode);
            log.LogRemark = "";
            log.OperatePerson = loginUser.name;
            new SysBusinessLogManager().Insert(log);     //插入系统日志
            #endregion



            new Utils.CacheHelper(_memoryCache).SetCache(loginUser.User.UserID, loginUser.User);
            return Json(loginUser);
        }

        [AllowAnonymous]
        [HttpGet]
        [Route("getuserinfo")]
        public ActionResult GetUserInfo(string token)
        {
            Console.WriteLine("getuserinfo");
            Console.WriteLine("token:" + token);
            var ret = new Utils.CacheHelper(_memoryCache).GetCache(token);
            //Console.WriteLine("cache:" + JsonConvert.SerializeObject(ret));
            var loginUser = new LoginUserDTO();
            if (ret == null)
            {
                loginUser.IsSuccess = false;
                loginUser.ErrorMsg = "登录超时，请重新登录";

            }
            else
            {
                var user = (SystemUser)ret;
                loginUser.User = user;
                loginUser.IsSuccess = true;
                loginUser.ErrorMsg = "";
                loginUser.token = user.UserID;
                loginUser.name = user.UserName;
                loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
                loginUser.introduction = "";
                loginUser.roles = new string[1] { "admin" };
            }
            //Logger.Info(ret);
            return Json(loginUser);
        }

        [HttpGet]
        [Route("logout")]
        public ActionResult LogOut(string userid)
        {
            new Utils.CacheHelper(_memoryCache).DelCache(userid);
            return Json(new { code = 20000, data = "success" });
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("create")]
        public JsonResult InsertUser(string username, string password, string confirmpassword)
        {
            if (password == confirmpassword)
            {
                //_userService.InsertUser(username, password);
            }
            return Json("User Created Successfully! :)");
        }

        private async Task<string> remoteHelper(string url, HttpContent content)
        {
            var result = string.Empty;
            try
            {
                using (var client = _httpclientfactory.CreateClient())
                using (var response = await client.PostAsync(url, content))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return result;
        }
    }
}
