using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NLog;
using Sugar.Enties;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using WebAPIBase.API.Requests;
using WebAPIBase.Utils;
using WebAPIBase.Utils.Jwt;

namespace WebAPIBase.API.Controllers
{
    [Produces("application/json;charset=UTF-8")]
    [Route("api/User")]
    [ServiceFilter(typeof(Filter.TokenAuthorize))]
    public class UserController : BaseController
    {
        /// <summary>
        /// webservice地址
        /// </summary>
        private string webserviceUrl;
        /// <summary>
        /// 授权校验服务地址
        /// </summary>
        private string validServiceUrl;
        private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly IHttpClientFactory _httpclientfactory;
        private IMemoryCache _memoryCache;
        private readonly SignInManager<AppUser> _signInManager;
        private readonly UserManager<AppUser> _userManager;
        private readonly IConfiguration _configuration;
        /// <summary>
        /// 供应商登录接口地址
        /// </summary>
        private string supplyUrl;
        /// <summary>
        /// 令牌获取和验证类
        /// </summary>
        private readonly ITokenHelper tokenHelper = null;

        public UserController(IMemoryCache memoryCache, IHttpClientFactory httpclientfactory, UserManager<AppUser> userManager,
            SignInManager<AppUser> signInManager, ITokenHelper _tokenHelper,
            IConfiguration configuration)
        {
            _httpclientfactory = httpclientfactory;
            _memoryCache = memoryCache;


            webserviceUrl = Configuration["Logging:AppSettings:webserviceUrl"];
            validServiceUrl = Configuration["Logging:AppSettings:validServiceUrl"];
            supplyUrl = configuration["Logging:AppSettings:supplyUrl"];
            _userManager = userManager;
            _signInManager = signInManager;
            _configuration = configuration;
            tokenHelper = _tokenHelper;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("")]
        public JsonResult ValidateUser([FromBody] UserLogin request)
        {
            Console.WriteLine("【ValidateUser】request:" + JsonConvert.SerializeObject(request));

            #region 公司授权           
            var validateResult = HttpClientHelper.DoPost(validServiceUrl + "/api/user");
            Console.WriteLine($"【ValidateUser】validateResult:{validateResult}");
            logger.Info($"【validateResult】:{validateResult}");
            if (validateResult == "")
            {
                var res1 = new ApiResponse
                {
                    Code = 200,
                    IsSuccess = false,
                    ErrMsg = "授权失败"

                };
                return Json(res1);
            }
            else
            {
                var resAuthorize = JsonConvert.DeserializeObject<ApiResponse>(validateResult);
                if (!resAuthorize.IsSuccess)
                {
                    var res1 = new ApiResponse
                    {
                        Code = 200,
                        IsSuccess = false,
                        ErrMsg = "授权失败"

                    };
                    return Json(res1);
                }
                logger.Info($"【授权成功】:{validateResult}");
            }
            #endregion

            NameValueCollection values = new NameValueCollection();
            values.Add("userid", request.UserName);
            values.Add("password", request.Password);
            values.Add("dno", "");
            values.Add("dtoken", "");
            //请求webservice的登录接口，获取返回信息
            var result = WebClientHelper.ClientPost(webserviceUrl + "/Login", values);

            //Console.WriteLine(result);

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

            var user = new SystemUserManager().GetList(m => m.UserID == request.UserName).FirstOrDefault();
            var loginUser = new LoginUserDTO();

            //loginUser.IsSuccess = false;
            if (login != null && login.result)       //地产云用户登录
            {
                var unitManager = new UnitManager();
                var userCode = login.data.userCode;
                var station = unitManager.GetUserStation(userCode);

                loginUser.roles = new string[1] { "admin" };
                loginUser.introduction = login.data.userName;
                loginUser.name = login.data.userName;

                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";
                user = new SystemUser();
                user.UserCode = login.data.userCode;
                user.UserID = login.data.userId;
                user.UserName = login.data.userName;
                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

            }
            else     //登录失败，则判断是否供应商登录
            {



                var res1 = new ApiResponse
                {
                    Code = 200,
                    IsSuccess = false,
                    ErrMsg = login.msg

                };
                return Json(res1);


            }

            TnToken tnToken;

            //获取令牌，返回客户端 
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "UserID", user.UserID }
                    };
            tnToken = tokenHelper.CreateToken(keyValuePairs);

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


            var res = new ApiResponse
            {
                Code = 200,
                IsSuccess = true,
                ErrMsg = "",
                Data = loginUser,
                TnToken = tnToken
            };
            return Json(res);
        }

        /// <summary>
        /// oa用户免密登录入口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("sysloginoa")]
        public ActionResult LoginOa(string usercode)
        {
            var res = new ApiResponse();
            res.Code = 200;
            res.IsSuccess = false;
            res.ErrMsg = "";
            var loginUser = new LoginUserDTO();
            if (usercode.IsNullOrEmpty())
            {
                res.ErrMsg = "请输入用户名";
                return Json(res);
            }
            var user = new SystemUserManager().GetList(m => m.UserID == usercode).FirstOrDefault();
            if (user != null)
            {
                logger.Info($"【LoginOa】user:{JsonConvert.SerializeObject(user)}");

                var unitManager = new UnitManager();
                var userCode = user.UserCode;
                var station = unitManager.GetUserStation(userCode);

                loginUser.roles = new string[1] { "admin" };
                loginUser.introduction = user.UserName;
                loginUser.name = user.UserName;

                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;
            }
            else
            {

                res.ErrMsg = "不存在的用户";
                return Json(res);

            }
            #region 写入系统日志
            var log = new SysBusinessLog();
            log.LogClass = "SystemUser";
            log.LogTime = DateTime.Now;
            logger.Info($"【LoginOa】loginUser.User:{JsonConvert.SerializeObject(loginUser.User)}");
            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


            //获取令牌，返回客户端 
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "UserID", user.UserID }
                    };
            var tnToken = tokenHelper.CreateToken(keyValuePairs);
            res.IsSuccess = true;
            res.Data = loginUser;
            res.TnToken = tnToken;
            new Utils.CacheHelper(_memoryCache).SetCache(loginUser.User.UserID, loginUser.User);
            return Json(res);
        }

        /// <summary>
        /// 供应商登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("LoginSupplier")]
        public JsonResult LoginSupplier([FromBody] UserLogin request)
        {
            Console.WriteLine("【LoginSupplier】request:" + JsonConvert.SerializeObject(request));

            #region 公司授权           
            //var validateResult = HttpClientHelper.DoPost(validServiceUrl + "/api/user");
            //Console.WriteLine($"【LoginSupplier】validateResult:{validateResult}");
            //logger.Info($"【LoginSupplier】:{validateResult}");
            //if (validateResult == "")
            //{
            //    var res1 = new ApiResponse
            //    {
            //        Code = 200,
            //        IsSuccess = false,
            //        ErrMsg = "授权失败"

            //    };
            //    return Json(res1);
            //}
            //else
            //{
            //    var resAuthorize = JsonConvert.DeserializeObject<ApiResponse>(validateResult);
            //    if (!resAuthorize.IsSuccess)
            //    {
            //        var res1 = new ApiResponse
            //        {
            //            Code = 200,
            //            IsSuccess = false,
            //            ErrMsg = "授权失败"

            //        };
            //        return Json(res1);
            //    }
            //    logger.Info($"【授权成功】:{validateResult}");
            //}
            #endregion


            #region 请求供应商系统登录
            var list = new List<Dictionary<string, string>>();
            var dic1 = new Dictionary<string, string>();
            dic1.Add("loginName", request.UserName);
            dic1.Add("pwd", request.Password);
            list.Add(dic1);
            var res2 = HttpWebRequestHelper.RequestGet(supplyUrl, list);
            logger.Info("res2:" + res2);
            var obj = JsonConvert.DeserializeObject<dynamic>(res2);
            if (obj.body.code != 200)
            {
                var res1 = new ApiResponse
                {
                    Code = 500,
                    IsSuccess = false,
                    ErrMsg = obj.body.msg

                };
                return Json(res1);
            }
            var supplierCode = (string)obj.body.msg.supplierCode;
            logger.Info($"suppliercode:{supplierCode}");

            if (supplierCode.IsNullOrEmpty())
            {
                var res1 = new ApiResponse
                {
                    Code = 200,
                    IsSuccess = false,
                    ErrMsg = "供应商不存在"

                };
                return Json(res1);
            }
            #endregion


            var loginUser = new LoginUserDTO();

            //loginUser.IsSuccess = false;


            if (true)
            {
                string suppliercode = supplierCode;
                var service = new SupplierManager();
                var supplier = service.GetById(suppliercode);
                if (supplier != null)      //登录成功
                {
                    loginUser.Supplier = supplier;
                }
                else
                {
                    var res1 = new ApiResponse
                    {
                        Code = 200,
                        IsSuccess = false,
                        ErrMsg = "登录失败，无此供应商"

                    };
                    return Json(res1);
                }
            }
            else
            {
                var res1 = new ApiResponse
                {
                    Code = 200,
                    IsSuccess = false,
                    ErrMsg = "登录失败"

                };
                return Json(res1);
            }



            TnToken tnToken;

            //获取令牌，返回客户端 
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "UserID", "supplier"+loginUser.Supplier.SupplierCode }
                    };
            tnToken = tokenHelper.CreateToken(keyValuePairs);

            new Utils.CacheHelper(_memoryCache).SetCache("supplier" + loginUser.Supplier.SupplierCode, loginUser.Supplier);


            var res = new ApiResponse
            {
                Code = 200,
                IsSuccess = true,
                ErrMsg = "",
                Data = loginUser,
                TnToken = tnToken
            };
            return Json(res);
        }


        [AllowAnonymous]
        [HttpGet]
        [Route("getuserinfo")]
        public ActionResult GetUserInfo(string token)
        {
            var res = new ApiResponse();
            res.IsSuccess = false;
            res.ErrMsg = "";
            res.Code = 200;
            //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)
            {
                res.ErrMsg = "登录超时，请重新登录";

            }
            else
            {
                var user = (SystemUser)ret;
                loginUser.User = user;
                res.IsSuccess = true;
                res.ErrMsg = "";
                //获取令牌，返回客户端 
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "UserID", user.UserID }
                    };
                var tnToken = tokenHelper.CreateToken(keyValuePairs);
                res.TnToken = tnToken;
                loginUser.name = user.UserName;
                loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
                loginUser.introduction = "";
                loginUser.roles = new string[1] { "admin" };
                res.Data = loginUser;

            }
            //Logger.Info(ret);
            return Json(res);
        }

        [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;
        }


    }

    /// <summary>
    /// 供应商应答
    /// </summary>
    public class SupplyResponse
    {
        public string code { get; set; }
        public string message { get; set; }
    }


}
