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 Krypton.Toolkit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudBuilder.Security.Gui
{
    public partial class SecurityUserOperationPage : AbstractPage
    {
        private SecurityMessagePolicy securityMessagePolicy;
        private SecurityUserTypePolicy securityUserTypePolicy;
        private SecurityUserData data;
        private SecurityUserDisplayData securityUserEntity;
        private SecurityActorEntity[] securityActors = null;
        private SecurityUserRequest securityUserRequest;

        //初始化Page，注入容器内，不要在此做任何事情
        public SecurityUserOperationPage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 第一次加载时执行，只执行一次
        /// </summary>
        public override void FunctionLoaded()
        {
            HandleException(() => OnFunctionLoaded());
        }

        private void OnFunctionLoaded()
        {
            base.FunctionLoaded();
            //初始化容器-------------------------------------
            securityMessagePolicy = ServiceHelper.GetTypeService<SecurityMessagePolicy>()!;
            securityUserRequest = ServiceHelper.GetTypeService<SecurityUserRequest>();
            securityUserTypePolicy = ServiceHelper.GetTypeService<SecurityUserTypePolicy>()!;
            //界面初始化
            InitGui();
        }


        private void InitGui()
        {
            InitBindingContext();

            InitComBox();

            InitDisplayMode();

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

        private void InitComBox()
        {
            userTypeCombo.SetDataSource(securityUserTypePolicy.GetDataSource(), true);

            SecurityActorRequest securityActorRequest = ServiceHelper.GetTypeService<SecurityActorRequest>();
            securityActors = securityActorRequest.FindAllByNoPermission();

            deselectedGv.SetColumnDataSource(actorLocalNameCol, securityActors, SecurityActorEntity.ACTOR_LOCAL_NAME, SecurityActorEntity.ACTOR_NAME, true);
            selectedGv.SetColumnDataSource(actorLocalNameSelectedCol, securityActors, SecurityActorEntity.ACTOR_LOCAL_NAME, SecurityActorEntity.ACTOR_NAME, true);
        }

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

            InitPermission();

            userNameTxt.Set(SecurityUserEntity.USER_NAME, userNameLabel.Text, EnumEditModeColor.Required);
            userLocalNameTxt.Set(SecurityUserEntity.USER_LOCAL_NAME);
            userMobileTxt.Set(SecurityUserEntity.USER_MOBILE, userMobileLabel.Text, EnumEditModeColor.Required);
            userIsValidIndcChk.Set(SecurityUserEntity.USER_IS_VALID_INDC, EnumBindDirection.Both);
            userTypeCombo.Set(SecurityUserEntity.USER_TYPE, userTypeLabel.Text, EnumEditModeColor.Required);
            selectedGv.InitColumn(false, true);
            deselectedGv.InitColumn(false, true);

            guiOperateHelper = new GuiOperateHelper();
        }

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

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

                InitDisplayMode();

                SecurityUserOperationLinkup linkup = null;

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

                this.DisplayMode = (GuiDisplayMode)linkup.DisplayMode;

                userNameSearchTxt.Text = linkup.UserName;

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

                userNameSearchTxt.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;

            userNameSearchTxt.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 (securityUserEntity != 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, userNameTxt);
            }

            guiOperateHelper.EnableControls(false, deselectedGv, selectedGv);
        }

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

            SecurityActorEntity[] actors = selectedGv.GetAllRows<SecurityActorEntity>();
            if (actors != null && actors.Length > 0)
                data.SecurityUserActors = actors.Select(x => new SecurityUserActorViewEntity() { UserName = userNameTxt.Text, ActorName = x.ActorName, UserLocalName = string.Empty }).ToArray();
            else data.SecurityUserActors = null;
        }
        private bool SaveValidate()
        {
            if (!guiOperateHelper.CheckValidate(this.mainPanel)) return false;

            return true;
        }

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

                Reset();

                data = securityUserRequest.FindByKey(userNameSearchTxt.Text);

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

                    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 SecurityUserData();
            securityUserEntity = new SecurityUserDisplayData()
            {
                CreatedBy = string.Empty,
                UpdatedBy = string.Empty,
                CreatedDatetime = DateTime.Now,
                UpdatedDatetime = DateTime.Now,
                UserType = SecurityUserTypePolicy.NORMAL_USERS
            };
            data.SecurityUser = securityUserEntity;

            PackEntityToUI();

            userNameTxt.Focus();
        }

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

            SetDisplayMode();
        }

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

            SecurityActorEntity[] allActors = securityActors;
            SecurityActorEntity[] deselecteds = null;
            SecurityActorEntity[] selecteds = null;
            if (data.SecurityUserActors != null && securityActors != null)
            {
                deselecteds = allActors.Where(x => !data.SecurityUserActors.Select(y => y.ActorName).Contains(x.ActorName)).ToArray();
                selecteds = allActors.Where(x => data.SecurityUserActors.Select(y => y.ActorName).Contains(x.ActorName)).ToArray();
            }
            else
            {
                deselecteds = allActors;
            }

            deselectedGv.SetDataSource(deselecteds);
            selectedGv.SetDataSource(selecteds);
        }

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

            securityUserEntity = null;

            guiOperateHelper.ResetControls(this.contentPanel);

            SetDisplayMode();

            userNameSearchTxt.Focus();
        }

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

        }

        private void searchBut_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(userNameSearchTxt.Text))
                {
                    ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_VALID_INPUT, GuiOperateHelper.GetLabelText(userNameSearchLabel.Text)));
                    this.userNameSearchTxt.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)
        {
            guiOperateHelper.ResetControls(this.topPanel);
            HandleException(() => Reset());
        }

        private void createBut_Click(object sender, EventArgs e)
        {
            HandleException(() => Create());
        }

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

                PackUIToEntity();


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


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

                userNameSearchTxt.Text = securityUserEntity.UserName;
                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)
        {

            HandleException(() => CancelEditing());

        }

        private void amendBut_Click(object sender, EventArgs e)
        {
            HandleException(() => Amend());
        }

        private void deleteBut_Click(object sender, EventArgs e)
        {
            try
            {
                if (securityUserEntity == 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;

                securityUserRequest.Delete(securityUserEntity.UserName);

                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 selectedBut_Click(object sender, EventArgs e)
        {
            if (selectedGv.RowCount <= 0 || selectedGv.SelectedCells.Count <= 0)
            {
                ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_WS_RECORD_NOT_FOUND));
                return;
            }

            SecurityActorEntity[] securityActors = selectedGv.GetSelectedCellsData<SecurityActorEntity>();
            selectedGv.DeleteRows(selectedGv.SelectedCells);

            deselectedGv.AddRow<SecurityActorEntity>(securityActors);
        }

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

            SecurityActorEntity[] securityActors = deselectedGv.GetSelectedCellsData<SecurityActorEntity>();
            deselectedGv.DeleteRows(deselectedGv.SelectedCells);

            selectedGv.AddRow<SecurityActorEntity>(securityActors);
        }

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

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

                userNameSearchTxt.Text = ((SecurityUserEntity[])dialog.OutputData)[0].UserName;

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

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

            SecurityActorEntity data = selectedGv.GetRowData<SecurityActorEntity>(selectedGv.SelectedCells[0].RowIndex);

            DisplayPage(GuiDisplayMode.View, data.ActorName);
        }


        private void DisplayPage(GuiDisplayMode mode, string actorName)
        {
            SecurityActorOperationLinkup linkupData = new SecurityActorOperationLinkup();
            linkupData.DisplayMode = Convert.ToInt32(mode);
            linkupData.ActorName = actorName;

            this.DisplayAbstractPage(typeof(SecurityActorOperationPage).Name, linkupData);
        }

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

            SecurityActorEntity data = deselectedGv.GetRowData<SecurityActorEntity>(deselectedGv.SelectedCells[0].RowIndex);

            DisplayPage(GuiDisplayMode.View, data.ActorName);
        }
    }
}
