using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AIProofread.Controls
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class BaseWinForm : Form
    {
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn(
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
         );

        [DllImport("dwmapi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

        [DllImport("dwmapi.dll")]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        [DllImport("dwmapi.dll")]
        public static extern int DwmIsCompositionEnabled(ref int pfEnabled);

        private bool m_aeroEnabled;                     // variables for box shadow
        private const int CS_DROPSHADOW = 0x00020000;
        private const int WM_NCPAINT = 0x0085;
        private const int WM_ACTIVATEAPP = 0x001C;

        public struct MARGINS                           // struct for box shadow
        {
            public int leftWidth;
            public int rightWidth;
            public int topHeight;
            public int bottomHeight;
        }

        private const int WM_NCHITTEST = 0x84;          // variables for dragging the form
        private const int HTCLIENT = 0x1;
        private const int HTCAPTION = 0x2;

        protected override CreateParams CreateParams
        {
            get
            {
                m_aeroEnabled = CheckAeroEnabled();

                CreateParams cp = base.CreateParams;
                if (!m_aeroEnabled)
                    cp.ClassStyle |= CS_DROPSHADOW;

                return cp;
            }
        }

        private bool CheckAeroEnabled()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                int enabled = 0;
                DwmIsCompositionEnabled(ref enabled);
                return (enabled == 1) ? true : false;
            }
            return false;
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                //阴影
                case WM_NCPAINT:
                    if (m_aeroEnabled)
                    {
                        var v = 2;
                        DwmSetWindowAttribute(this.Handle, 2, ref v, 4);
                        MARGINS margins = new MARGINS()
                        {
                            bottomHeight = 1,
                            leftWidth = 1,
                            rightWidth = 1,
                            topHeight = 1
                        };
                        DwmExtendFrameIntoClientArea(this.Handle, ref margins);
                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
            // 拖动
            if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT)
                m.Result = (IntPtr)HTCAPTION;
        }

        public BaseWinForm()
        {
            m_aeroEnabled = false;
            this.FormBorderStyle = FormBorderStyle.None;
        }

        protected async void InitWebView(WebView2 webView,String url,string name,Action callaback = null)
        {
            //Bridge.InitWebEnvAsync(name, webView);
            try
            {
                if (webView.IsDisposed) return;
                var ops = new CoreWebView2EnvironmentOptions("--disable-web-security");
                var env = await CoreWebView2Environment.CreateAsync(null, Config.WEB_DATA_PATH, ops);

                await webView.EnsureCoreWebView2Async(env);

                var eventForwarder = new EventForwarder(this);
                webView.CoreWebView2.AddHostObjectToScript("event", eventForwarder);
                webView.CoreWebView2.AddHostObjectToScript("host", this);
                webView.CoreWebView2.AddHostObjectToScript("bridge", Bridge.bridge);
                if(callaback != null)
                {
                    callaback();
                }

                webView.Source = new Uri(url);
            }catch (Exception ex)
            {
                Logger.Log("\ninit webview error:" + ex.Message + "\n" + ex.StackTrace);
            }
        }
        public void Download(string url)
        {
            Globals.ThisAddIn.ActiveDocument.RunInMainThread(() =>
            {
                var sfd = new SaveFileDialog();
                sfd.Filter = "Excel文件|*.xlsx";
                sfd.DefaultExt = ".xlsx";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    var fileName = sfd.FileName;
                    Download(url, fileName);
                }
            });
        }
        public void Download(string url, string fileName)
        {
            // 现在url对应文件并保存到fileName
            try
            {
                using (var client = new WebClient())
                {
                    client.DownloadFile(url, fileName);
                }
            }
            catch (Exception ex)
            {
                Logger.Log("\nDownload error:" + ex.Message + "\n" + ex.StackTrace);
            }
        }
    }
}
