using DeviceRepair.DataAccess;
using DeviceRepair.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Text;
using System.Web.Http;
using Newtonsoft.Json;
using DeviceRepair.Api.CustomAttribute;
using DeviceRepair.Api.Common;
using System.Xml;
using System.IO;
using DeviceRepair.Models.Common;
using System.Xml.Serialization;
using DeviceRepair.Utils;

namespace DeviceRepair.Api.Controllers
{
    [RoutePrefix("Api/User")]
    public class UserController : CFController
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Login")]
        public APIResponseData UserLogin(UserInfoModel Item)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "账户或密码错误！" };
            if (Item == null)
                return apiResponseData;
            try
            {
                if (string.IsNullOrWhiteSpace(Item.LoginCode))
                {
                    apiResponseData.Message = "用户名不能为空";
                    return apiResponseData;
                }

                if (string.IsNullOrWhiteSpace(Item.PassWord))
                {
                    apiResponseData.Message = "密码不能为空";
                    return apiResponseData;
                }

                base.GetParams();

                apiResponseData = UserAccess.Instance.GetLoginEntity(Item.LoginCode, Item.PassWord, OperationInfo);
                if (apiResponseData.Code == 1 && apiResponseData.Data != null)
                {
                    JObject jData = JObject.Parse(JsonConvert.SerializeObject(apiResponseData.Data));
                    TokenModel tm = jData.ToObject<TokenModel>();
                    apiResponseData.Token = Encode(tm);
                    apiResponseData.Data = jData;
                }
                return apiResponseData;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// SFC 获取Token
        /// </summary>
        /// <param name="LoginCode"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        [HttpPost, Route("WebToken")]
        public async System.Threading.Tasks.Task<APIResponseData> WebToken(string LoginCode, string Password)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1 };
            if (string.IsNullOrWhiteSpace(LoginCode) || string.IsNullOrWhiteSpace(Password))
                throw new Exception("账户或密码不能为空！");

            try
            {
                byte[] password = Encoding.Unicode.GetBytes(LoginCode);
                Array.Reverse(password);
                string pass64 = Convert.ToBase64String(password);
                if (pass64.Length < 10)
                    pass64 += "YeT+=fue";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                builder.AppendLine($"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
                builder.AppendLine($"  <soap:Header>");
                builder.AppendLine($"   <SvcAuthentication xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"       <Password>{pass64}</Password>");
                builder.AppendLine($"       <Username>{LoginCode}</Username>");
                builder.AppendLine($"   </SvcAuthentication>");
                builder.AppendLine($"   </soap:Header>");
                builder.AppendLine($"   <soap:Body>");
                builder.AppendLine($"      <UserLogin xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"         <userCode>{LoginCode}</userCode>");
                builder.AppendLine($"         <pwd>{Password}</pwd>");
                builder.AppendLine("         <inParams>{\"OPERATORGUID\":\"2ffdf3b2-bb2c-4fba-ae33-cea15b087eb0\",\"OPERATOR\":\"myl\",\"CLIENTIP\":\"192.168.1.5\",\"CLIENTMAC\":\"38:D5:7A:E5:42:0D\",\"CLIENTNAME\":\"HONOR\",\"APPVERSION\":\"4.0.0.4\"}</inParams>");
                builder.AppendLine($"      </UserLogin>");
                builder.AppendLine($"   </soap:Body>");
                builder.AppendLine($"</soap:Envelope>");

                using (var client = new System.Net.Http.HttpClient())
                {
                    var content = new System.Net.Http.StringContent(builder.ToString(), Encoding.UTF8, "text/xml");
                    var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "http://localhost//MedtronicSFC/SfcService.asmx");
                    request.Content = content;

                    var response = await client.SendAsync(request);
                    if (response.IsSuccessStatusCode)
                    {
                        string stringRtn = await response.Content.ReadAsStringAsync();

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(stringRtn);
                        XmlNode Node = doc.DocumentElement["soap:Body"]["UserLoginResponse"]["UserLoginResult"]["Code"].LastChild;

                        if (Node.Value == "0")
                        {
                            Node = doc.DocumentElement["soap:Body"]["UserLoginResponse"]["btResults"].LastChild;
                            byte[] bytes = Convert.FromBase64String(Node.LastChild.Value);
                             bytes.ExactDataSet();


                        }

                        return apiResponseData;
                    }
                    else
                    {
                        throw new Exception(response.StatusCode.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 判断用户名是否存在
        /// </summary>
        /// <param name="loginCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ExistLoginCode")]
        public APIResponseData ExistLoginCode(string LoginCode)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "查询数据出错！" };
            if (string.IsNullOrWhiteSpace(LoginCode))
                return apiResponseData;
            try
            {
                return UserAccess.Instance.ExistLoginCode(LoginCode);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 验证用户名密码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ValidePassWord")]
        [HttpAuthorize]
        public APIResponseData ValidePassWord(string LoginCode, string PassWord)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "账户或密码错误！" };
            try
            {
                apiResponseData = UserAccess.Instance.ValidePassWord(LoginCode, PassWord);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateUserPassword")]
        [HttpAuthorize]
        public APIResponseData UpdateUserPassword(string LoginCode, string PassWord)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "账户或密码错误！" };
            try
            {
                base.GetParams();
                apiResponseData = UserAccess.Instance.UpdateUserPassword(LoginCode, PassWord, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 用户登出
        /// </summary>
        [HttpPost]
        [Route("LogOut")]
        [HttpAuthorize]
        public void LogOut()
        {
            try
            {
                base.GetParams();
                UserAccess.Instance.LogOut(OperationInfo);
            }
            catch
            {

            }
        }

        /// <summary>
        /// 查询最后修改密码时间
        /// </summary>
        /// <param name="LoginCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckChangePwdDate")]
        public APIResponseData CheckChangePwdDate(string LoginCode)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "执行查询操作出错！" };
            try
            {
                if (string.IsNullOrWhiteSpace(LoginCode))
                {
                    apiResponseData.Message = "用户名不能为空";
                    return apiResponseData;
                }

                apiResponseData = UserAccess.Instance.CheckChangePwdDate(LoginCode);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllUser")]
        [HttpAuthorize]
        public APIResponseData GetAllUsers()
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "数据查询失败！" };

            try
            {
                apiResponseData = UserAccess.Instance.GetAllUsers();
                return apiResponseData;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserMapping")]
        [HttpAuthorize]
        public APIResponseData GetUserMapping()
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "数据查询失败！" };

            try
            {
                apiResponseData = UserAccess.Instance.GetUserMapping();
                return apiResponseData;
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="Item"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("EditUser")]
        [HttpAuthorize]
        public APIResponseData EditUser(UserInfoModel Item)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "未能获取到数据" };
            if (Item == null)
                return apiResponseData;
            try
            {
                base.GetParams();
                apiResponseData = UserAccess.Instance.Update(Item, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 新增 / 修改 用户信息
        /// </summary>
        /// <param name="Item"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("InsertOrEdit")]
        [HttpAuthorize]
        public APIResponseData InsertOrEdit(UserInfoModel Item)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "未能获取到数据" };
            if (Item == null)
                return apiResponseData;
            try
            {
                base.GetParams();
                apiResponseData = UserAccess.Instance.InsertOrEdit(Item, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }

            return apiResponseData;
        }

        /// <summary>
        /// 通过用户信息对象生成token
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private string Encode(dynamic model)
        {
            byte[] key = Encoding.Default.GetBytes("^2020#!_@MaYonglong@_!#2021^");
            string token = JWT.JsonWebToken.Encode(model, key, JWT.JwtHashAlgorithm.HS256);
            return token;
        }
    }
}
