using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Session;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using System.Security.Claims;

using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using XHD.Core.IServices;
using XHD.Core.IRepository;
using XHD.Core.Common;
using XHD.Core.Models;
using XHD.Core.View.Configs;
using Microsoft.Extensions.Configuration;

namespace XHD.Core.View.Controllers
{
    public class AccountController : Controller
    {
        private readonly string CaptchaCodeSessionName = "CaptchaCode";

        private readonly Ihr_employeeService _service;
        private readonly Ihr_employeeRepository _repository;
        private readonly ISys_logService _LogService;
        private readonly ISys_infoService _infoservice;

        public AccountController(Ihr_employeeService service, Ihr_employeeRepository repository, ISys_logService LogService, ISys_infoService infoservice)
        {
            _service = service;
            _repository = repository;
            //_LogService = LogService;
            _LogService = LogService;
            _infoservice= infoservice;

        }

        public IActionResult Index()
        {
            //检查是否已配置
            IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true);
            IConfigurationRoot root = builder.Build();

            var isConfig = root["isConfig"];

            if (!isConfig.ToString().Equals("1"))
            {
                return Redirect("/SysConfig/index");
            }


            var infodata = _infoservice.Grid(a => a.sys_key == "sys_name");

            ViewData["company"] = infodata.data[0].sys_value;

            return View();
        }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns>文件流</returns>
        public IActionResult ValiCode()
        {
            byte[] buf = this.CreateImage();
            return File(buf, "image/png");
        }

        public async Task<string> Login(hr_employee model)
        {
            try
            {

                var valicode_session = HttpContext.Session.GetString(CaptchaCodeSessionName);
                if (valicode_session.ToLower() != Request.Form["valicode"].ToString().ToLower())
                {
                    return XHDResult.Error("验证码错误！").ToString();
                }
            }
            catch
            {
                return XHDResult.Error("验证码已过期！").ToString();
            }

            var result = await _service.Login(model);

            if (result.Value<int>("code") == 0)
            {
                //验证通过，存储coockies

                var list = result.Value<JArray>("data");
                var employee = list[0];

                var claims = new List<Claim>
                {
                    new Claim (ClaimTypes.Sid,employee.Value<string>("id")),        //id
                    new Claim (ClaimTypes.Name,employee.Value<string>("name")),     //用户名
                    new Claim ("uid",employee.Value<string>("uid"))                 //登陆账号
               
                };

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                //日志
                await _LogService.LoginLog(employee.Value<string>("id"), employee.Value<string>("name"), HttpContext.Connection.RemoteIpAddress.ToString());

                return XHDResult.Success().ToString();
            }
            else
            {
                return result.ToString();
            }


        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public string SignOut()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return XHDResult.Success().ToString();
        }

        #region 生成验证码
        //生成随机验证码数字字符串——4位数
        private string RandomNum(int int_NumberLength)
        {
            char[] chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz".ToCharArray();
            //Random random = new Random(Guid.NewGuid().GetHashCode());
            //string intString = random.Next(1000, 9999).ToString();
            //return intString;

            Random random = new Random();
            string validateCode = string.Empty;
            for (int i = 0; i < int_NumberLength; i++)
                validateCode += chars[random.Next(0, chars.Length)].ToString();
            return validateCode;
        }

        //生成随机点
        private int[] RandomPoint()
        {
            int[] intArray = new int[6];
            for (int i = 0; i < 6; i += 2)
            {
                Random random = new Random(Guid.NewGuid().GetHashCode());
                switch (i)
                {
                    case 0:
                        intArray[i] = random.Next(0, 10);
                        break;
                    case 2:
                        intArray[i] = random.Next(45, 55);
                        break;
                    case 4:
                        intArray[i] = random.Next(90, 100);
                        break;
                }
            }
            for (int i = 1; i < 6; i += 2)
            {
                Random random = new Random(Guid.NewGuid().GetHashCode());
                intArray[i] = random.Next(0, 42);
            }
            return intArray;
        }

        private byte[] CreateImage()
        {
            //设置图片大小
            Image image = new Bitmap(120, 42);
            //设置画笔在哪一张图片上画图
            Graphics graph = Graphics.FromImage(image);
            //背景色
            graph.Clear(Color.White);
            //笔刷
            Pen pen = new Pen(Brushes.Black, 1);
            for (int i = 0; i < 4; i++)
            {
                int[] points = RandomPoint();
                //画一条曲线
                graph.DrawCurve(pen, new Point[] {
                    new Point(points[0], points[1]),
                    new Point(points[2], points[3]),
                    new Point(points[4], points[5])
                });
            }
            Random random = new Random();

            //画一条直线
            //graph.DrawLines(pen, new Point[] { new Point(10, 10), new Point(90, 40) });
            //画数字
            //graph.DrawString(RandomNum(), new Font(new FontFamily("Microsoft YaHei"), 28, FontStyle.Bold),
            //    Brushes.Black, new PointF(0, -5));

            string code = RandomNum(4);

            byte[] byteArray = System.Text.Encoding.Default.GetBytes(code);

            //将验证码存入session
            HttpContext.Session.SetString(CaptchaCodeSessionName, code);

            for (int i = 0; i < code.Length; i++)
            {
                int colorIndex = random.Next(7);//随机颜色索引值  
                int fontIndex = random.Next(4);//随机字体索引值  
                Font font = new Font(new FontFamily("Microsoft YaHei"), 28, FontStyle.Bold);//字体  
                Brush brush = new SolidBrush(GetRandomColor());//颜色  
                int y = 4;
                if ((i + 1) % 2 == 0)//控制验证码不在同一高度  
                {
                    y = 2;
                }
                graph.DrawString(code.Substring(i, 1), font, brush, (i * 26), y - 8);//绘制一个验证字符  
            }

            //内存流
            MemoryStream ms = new MemoryStream();
            //把图片存进内存流
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            //获取内存流的byte数组
            byte[] buf = ms.GetBuffer();

            ms.Dispose();

            return buf;
        }

        private Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            int int_Red = RandomNum_First.Next(210);
            int int_Green = RandomNum_Sencond.Next(180);
            int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }

        #endregion
    }
}