using CloudBuilder.Core.Service;
using CloudBuilder.Gui;
using CloudBuilder.Request.Security;
using CloudBuilder.Security.Data;
using CloudBuilder.Security.Entity;
using CloudBuilder.Security.Linkup;
using CloudBuilder.Security.Policy;
using DocumentFormat.OpenXml.Wordprocessing;
using Krypton.Toolkit;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudBuilder.Security.Gui
{
    public partial class SecurityPermissionOperationPage : AbstractPage
    {
        private SecurityMessagePolicy securityMessagePolicy;
        private SecurityPermissionRequest securityPermissionRequest;
        private SecurityPermissionEntity securityPermissionEntity;
        private SecurityPermissionData data;

        public object deselectedGv { get; private set; }

        public SecurityPermissionOperationPage()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 第一次加载时执行，只执行一次
        /// </summary>
        public override void FunctionLoaded()
        {
            try
            {
                base.FunctionLoaded();
                //初始化容器-------------------------------------
                securityMessagePolicy = ServiceHelper.GetTypeService<SecurityMessagePolicy>()!;
                securityPermissionRequest = ServiceHelper.GetTypeService<SecurityPermissionRequest>();

                //界面初始化
                InitGui();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }


        private void InitGui()
        {
            InitBindingContext();

            InitDisplayMode();

            this.ParentAbstractForm.AcceptButton = this.searchBut;
            this.ParentAbstractForm.CancelButton = this.resetBut;
        }

        /// <summary>
        /// 有特殊要求的UI控件初始化设置,Init与Add配对后，使用guiOperateHelper管理
        /// </summary>
        private void InitBindingContext()
        {
            //需要绑定数据
            guiBindingContext = new GuiBindingContext();

            InitPermission();

            permissionNameTxt.Set(SecurityPermissionEntity.PERMISSION_NAME,permissionNameLabel.Text, EnumEditModeColor.Required);
            dependentTxt.Set(SecurityPermissionEntity.DEPENDENT);
            descriptionTxt.Set(SecurityPermissionEntity.DESCRIPTION);
            delegateIndcChk.Set(SecurityPermissionEntity.DELEGATE_INDC);

            dependentDetailNameCol.Set(EnumEditModeColor.Required);
            dependentDetailDescriptionCol.Set(EnumEditModeColor.Required);

            dataGv.InitColumn(false, true);

            guiOperateHelper = new GuiOperateHelper();
        }

        private void InitPermission()
        {
            createBut.Set(SecurityPermissionPolicy.SecurityPermission, Operate.Insert);
            amendBut.Set(SecurityPermissionPolicy.SecurityPermission, Operate.Update);
            deleteBut.Set(SecurityPermissionPolicy.SecurityPermission, Operate.Delete);
        }

        /// <summary>
        /// 每次从别的界面进入时执行，发生在FunctionLoaded之后
        /// </summary>
        /// <param name="param"></param>
        public override void FunctionActivated(object param)
        {
            try
            {
                if (param == null)
                {
                    permissionNameSearchTxt.Focus();
                    return;
                }

                InitDisplayMode();

                SecurityPermissionOperationLinkup linkup = null;

                if (param is SecurityPermissionOperationLinkup)
                {
                    linkup = (SecurityPermissionOperationLinkup)param;
                }

                this.DisplayMode = (GuiDisplayMode)linkup.DisplayMode;

                permissionNameSearchTxt.Text = linkup.PermissionName;

                if (this.DisplayMode == GuiDisplayMode.View)
                {
                    Search();
                }
                else if (this.DisplayMode == GuiDisplayMode.Create)
                {
                    Create();
                }
                else if (this.DisplayMode == GuiDisplayMode.Amend)
                {
                    Search();
                    Amend();
                }

                permissionNameSearchTxt.Focus();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        public override void FunctionSelected()
        {
            this.ParentAbstractForm.AcceptButton = this.searchBut;
            if (!IsDialog)
                this.ParentAbstractForm.CancelButton = this.resetBut;
            else
                this.ParentAbstractForm.CancelButton = this.cancelBut;

            permissionNameSearchTxt.Focus();
        }

        public override bool FunctionDeactivating()
        {
            if (this.DisplayMode == GuiDisplayMode.View)
            {
                return true;
            }
            else
            {
                return CancelEditing();
            }
        }

        private bool CancelEditing()
        {
            DialogResult result = ShowMessageBox.ShowOption(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM_CANCEL), securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM));

            //从外部跳转(非mainKryptonNavigator)，result第一次不生效？，所以再执行一次生效
            if (result == DialogResult.Cancel)
            {
                result = ShowMessageBox.ShowOption(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM_CANCEL), securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM));
            }

            if (result == DialogResult.No)
            {
                return false;
            }

            Cancel();

            return true;
        }

        private void InitDisplayMode()
        {
            this.DisplayMode = GuiDisplayMode.View;

            SetDisplayMode();
        }

        private void SetDisplayMode()
        {
            if (this.DisplayMode == GuiDisplayMode.View)
            {
                savePanel.Visible = false;
                operationPanel.Visible = true;

                guiOperateHelper.EnableControls(true, topPanel);
                guiOperateHelper.EnableControls(false, contentPanel);
                //查詢有記錄時,修改等控件有效
                if (securityPermissionEntity != null)
                    guiOperateHelper.EnableControls(true, bottomPanel);
                else
                    guiOperateHelper.EnableControls(false, bottomPanel);
            }
            else if (this.DisplayMode == GuiDisplayMode.Amend || this.DisplayMode == GuiDisplayMode.Create)
            {
                savePanel.Visible = true;
                operationPanel.Visible = false;

                guiOperateHelper.EnableControls(false, topPanel);
                guiOperateHelper.EnableControls(true, bottomPanel, contentPanel);

                if (this.DisplayMode == GuiDisplayMode.Amend) guiOperateHelper.EnableControls(false, permissionNameTxt);
            }
        }

        private void PackUIToEntity()
        {
            guiBindingContext.DataPack();

            SecurityPermissionDependentEntity[] dependentEntities = dataGv.GetAllRows<SecurityPermissionDependentEntity>();

            if (dependentEntities == null || dependentEntities.Length == 0)
                data.SecurityPermissionDependents = null;
            else
                data.SecurityPermissionDependents = dependentEntities.Select(x => new SecurityPermissionDependentEntity()
                {
                    CreatedBy = x.CreatedBy,
                    UpdatedBy = x.UpdatedBy,
                    PermissionName = permissionNameTxt.Text,
                    Dependent = dependentTxt.Text,
                    DependentDetailName = x.DependentDetailName,
                    DependentDetailDescription = x.DependentDetailDescription
                }).ToArray(); ;
        }

        private bool SaveValidate()
        {
            if (!guiOperateHelper.CheckValidate(this.contentPanel)) return false;

            if (dataGv.Rows.Count > 0 && string.IsNullOrEmpty(dependentTxt.Text))
            {
                ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_VALID_INPUT, GuiOperateHelper.GetLabelText(dependentLabel.Text)));
                dependentTxt.Focus();
                return false;
            }

            return true;
        }

        private void Search()
        {
            try
            {
                if (string.IsNullOrEmpty(permissionNameSearchTxt.Text)) return;

                Reset();

                data = securityPermissionRequest.FindByKey(permissionNameSearchTxt.Text);

                if (data == null || data.SecurityPermission == null)
                {
                    ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_WS_RECORD_NOT_FOUND));
                }
                else
                {
                    securityPermissionEntity = data.SecurityPermission;

                    PackEntityToUI();

                    SetDisplayMode();
                }
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void Create()
        {
            this.DisplayMode = GuiDisplayMode.Create;

            guiOperateHelper.ResetControls(this.mainPanel);

            SetDisplayMode();

            data = new SecurityPermissionData();
            securityPermissionEntity = new SecurityPermissionEntity()
            {
                CreatedBy = string.Empty,
                UpdatedBy = string.Empty,
                CreatedDatetime = DateTime.Now,
                UpdatedDatetime = DateTime.Now,
            };
            data.SecurityPermission = securityPermissionEntity;

            PackEntityToUI();

            permissionNameTxt.Focus();
        }

        private void Amend()
        {
            this.DisplayMode = GuiDisplayMode.Amend;

            SetDisplayMode();
        }

        private void PackEntityToUI()
        {
            guiBindingContext.DataBind(data.SecurityPermission, this);

            dataGv.SetDataSource(data.SecurityPermissionDependents);
        }

        private void Reset()
        {
            this.DisplayMode = GuiDisplayMode.View;

            securityPermissionEntity = null;

            guiOperateHelper.ResetControls(this.contentPanel);

            SetDisplayMode();

            permissionNameSearchTxt.Focus();
        }

        public void Cancel()
        {
            if (!string.IsNullOrEmpty(permissionNameSearchTxt.Text))
                Search();
            else
                Reset();

        }


        private void permissionNameSearchBut_Click(object sender, EventArgs e)
        {
            try
            {
                AbstractForm dialog = GetAbstractDialog(typeof(SecurityPermissionEnquiryPage).Name);

                if (DialogResult.OK != dialog.ShowDialog()) return;

                permissionNameSearchTxt.Text = ((SecurityPermissionEntity[])dialog.OutputData)[0].PermissionName;

                Search();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void searchBut_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(permissionNameSearchTxt.Text))
                {
                    ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_VALID_INPUT, GuiOperateHelper.GetLabelText(permissionNameSearchLabel.Text)));
                    this.permissionNameSearchTxt.Focus();
                    return;
                }
                this.DisplayMode = GuiDisplayMode.View;

                Search();

            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void resetBut_Click(object sender, EventArgs e)
        {
            try
            {
                guiOperateHelper.ResetControls(this.topPanel);
                Reset();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void createBut_Click(object sender, EventArgs e)
        {
            try
            {
                Create();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void amendBut_Click(object sender, EventArgs e)
        {
            try
            {
                Amend();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void deleteBut_Click(object sender, EventArgs e)
        {
            try
            {
                if (securityPermissionEntity == null)
                {
                    ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_WS_RECORD_NOT_FOUND));
                    return;
                }

                if (DialogResult.Yes != ShowMessageBox.ShowOption(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM_DEL_NULL), securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_DELETE))) return;

                securityPermissionRequest.Delete(securityPermissionEntity.PermissionName);

                ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_SUCCEED_DELETED_NULL));

                Reset();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void saveBut_Click(object sender, EventArgs e)
        {
            try
            {
                if (!SaveValidate()) return;

                PackUIToEntity();


                if (this.DisplayMode == GuiDisplayMode.Create)
                    securityPermissionRequest.Insert(data);
                else
                    securityPermissionRequest.Update(data);


                ShowMessageBox.ShowInfo((this.DisplayMode == GuiDisplayMode.Create) ?
                    securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_SUCCEED_CREATED_NULL) :
                    securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_SUCCEED_UPDATED_NULL));

                permissionNameSearchTxt.Text = securityPermissionEntity.PermissionName;
                Search();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void cancelBut_Click(object sender, EventArgs e)
        {
            try
            {
                CancelEditing();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void addBut_Click(object sender, EventArgs e)
        {
            dataGv.AddRow(new SecurityPermissionDependentEntity() { CreatedBy = string.Empty, UpdatedBy = string.Empty });
        }

        private void delBut_Click(object sender, EventArgs e)
        {
            if (dataGv.RowCount <= 0 || dataGv.SelectedCells.Count <= 0)
            {
                ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_WS_RECORD_NOT_FOUND));
                return;
            }

            dataGv.DeleteRows(dataGv.SelectedCells);
        }
    }
}
