using OpenCvSharp;
using OpenCvSharp.Extensions;
using AssistClient.Utils;
using Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace AssistClient
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
        }
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            this.txtUserCode.SelectAll();
            string configPath = Application.StartupPath + "\\Login.ini";

            //DEV
            if (Util.ReadIniValue(configPath, "LOGIN", "RememberUserCode") == "1")
            {
                this.txtUserCode.Text = Util.ReadIniValue(configPath, "LOGIN", "UserCode");
                this.chkRememberUserCode.Checked = true;
                this.txtUserPw.SelectAll();
                if (Util.ReadIniValue(configPath, "LOGIN", "RememberPw") == "1")
                {
                    this.txtUserPw.Text = Util.ReadIniValue(configPath, "LOGIN", "PassWord");
                    this.chkRememberPw.Checked = true;
                    this.btnLogin.Focus();
                }
            }
        }
        private void FrmLogin_Shown(object sender, EventArgs e)
        {
            //this.txtUserCode.Text = "admin";
            //this.txtUserPw.Text = "";
            //btnLogin_Click(null, null);
        }
        private void waiting(Object form)
        { 
            FrmLoading2 frmLoading = form as FrmLoading2;
            btnLogin_Click(null,null);
            frmLoading.Close();
        }
        private void FrmLogin_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
            System.GC.Collect();
            System.Environment.Exit(0);
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string szUserCode=this.txtUserCode.Text.Trim();
                string szUserPw=this.txtUserPw.Text.Trim();
                if (szUserCode == "")
                    throw new Exception("请填写用户帐号！");
                if (szUserPw.Length != 32)
                    szUserPw = Utils.Util.GetMD5(szUserPw);

                UserService service = new UserService();
                var model = service.GetModel(szUserCode, szUserPw);
                if (model == null)
                    throw new Exception("帐号或密码错误！");
                if (szUserCode!="admin" && !model.State)
                    throw new Exception("帐号已停用！");
                if (string.IsNullOrWhiteSpace(model.Password))
                    model.Password = "";
                //
                string configPath = Application.StartupPath + "\\Login.ini";
                if (this.chkRememberUserCode.Checked)
                {
                    
                    Util.WriteIniValue(configPath, "LOGIN", "UserCode", szUserCode);
                    Util.WriteIniValue(configPath, "LOGIN", "RememberUserCode", "1");
                    Util.WriteIniValue(configPath, "LOGIN", "PassWord", this.chkRememberPw.Checked ? szUserPw : "");
                    Util.WriteIniValue(configPath, "LOGIN", "RememberPw", this.chkRememberPw.Checked ? "1" : "0"); 
                }
                else
                {
                    Util.WriteIniValue(configPath, "LOGIN", "RememberUserCode", "");
                    Util.WriteIniValue(configPath, "LOGIN", "RememberPw", "0");
                    Util.WriteIniValue(configPath, "LOGIN", "PassWord", this.chkRememberPw.Checked ? szUserPw : "");
                    Util.WriteIniValue(configPath, "LOGIN", "RememberPw", this.chkRememberPw.Checked ? "1" : "0");
                }
                //
                this.Hide();
                Config.loginUser=model;
                FrmMain frmMain = new FrmMain();
                frmMain.Show(); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void chkRememberUserCode_CheckedChanged(object sender, EventArgs e)
        {
            if(!chkRememberUserCode.Checked)
                chkRememberPw.Checked = false;
        }
        private void chkRememberPw_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRememberPw.Checked)
                chkRememberUserCode.Checked = true;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确定初始化数据库？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;

            try
            {
                Service.InitDB.initDB(this.txtUserPw.Text=="reset");
                MessageBox.Show("数据库初始化成功，请使用admin进行登录！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"失败",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            byte[] buff = File.ReadAllBytes(Application.StartupPath + @"\bigbmp\bigbmp.bmp");
            this.Text = (DateTime.Now - now).TotalMilliseconds.ToString() + "  ";
            now = DateTime.Now;
            MemoryStream stream = new MemoryStream(buff);

            List<Bitmap> listBmp = new List<Bitmap>();
            using (Mat mat = BitmapConverter.ToMat(new System.Drawing.Bitmap(stream)))
            {
                //
                int smallW = mat.Width / 23;
                int smallH = mat.Height / 23;
               
                {
                    for (int i = 0; i < 23; i++)
                    {
                        for (int j = 0; j < 23; j++)
                        {
                            Rect rect1 = new Rect(i * smallW, j * smallH, smallW, smallH);
                            using (Mat mat8U = mat[rect1])
                            {
                                listBmp.Add(BitmapConverter.ToBitmap(mat8U));
                            }
                        }
                    }
                }
            }

            this.Text += (DateTime.Now - now).TotalMilliseconds.ToString();
            int index = 0;
            listBmp.ForEach(b => b.Save(Application.StartupPath + @"\bigbmp\" + (index++) + ".bmp", ImageFormat.Bmp));
        }

        public static Mat bmpToMat(Bitmap srcbit)
        {
            int iwidth = srcbit.Width;
            int iheight = srcbit.Height;
            int iByte = iwidth * iheight * 3;
            byte[] result = new byte[iByte];
            int step;
            Rectangle rect = new Rectangle(0, 0, iwidth, iheight);
            BitmapData bmpData = srcbit.LockBits(rect, ImageLockMode.ReadWrite, srcbit.PixelFormat);
            IntPtr iPtr = bmpData.Scan0;
            Marshal.Copy(iPtr, result, 0, iByte);
            step = bmpData.Stride;
            srcbit.UnlockBits(bmpData);
            return new Mat(srcbit.Height, srcbit.Width, new MatType(MatType.CV_8UC3), result, step);
        } 

        public static Mat bmpBuffToBat(byte[] buff,int  height,int width)
        {
            var src = new Mat(height, width, MatType.CV_8UC3);
            int length = height * width * 3; // or src.Height * src.Step;
            Marshal.Copy(buff, 0, src.Data, length);

            return src;
        }
        public static byte[] matToBmpBuff(string fullpath, int height, int width)
        {
            Mat mat = Cv2.ImRead(fullpath);//Mat默认通道顺序是Bgr，和Bitmap一致
            var bytes = new byte[mat.Total() * 3];//这里必须乘以通道数，不然数组越界，也可以用w*h*c，差不多
            Marshal.Copy(mat.Data, bytes, 0, bytes.Length);


            return bytes;
        }

     
    }
}
