using CloudBuilder.Core.Service;
using CloudBuilder.Gui;
using CloudBuilder.Request.Security;
using CloudBuilder.Security.Entity;
using CloudBuilder.Security.Policy;
using CloudBuilder.Security.SearchCriteria;
using Krypton.Toolkit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudBuilder.Security.Gui
{
    public partial class SecurityMasterDialogPage : AbstractPage
    {
        private SecurityMessagePolicy securityMessagePolicy;
        private SecurityMasterRequest securityMasterRequest;
        private SecurityMasterEntity securityMasterEntity;
        private bool allowCancel = false;
        public SecurityMasterDialogPage()
        {
            InitializeComponent();
        }

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

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

        /// <summary>
        /// 弹出界面调用，发生在FunctionLoaded()之后
        /// </summary>
        public override void InitInputData(object param, GuiDisplayMode mode)
        {
            base.InitInputData(param, mode);
            if (mode == GuiDisplayMode.Create)
            {
                Create();
                return;
            }

            SecurityMasterEntity securityMasterEntity = param as SecurityMasterEntity;
            if (securityMasterEntity == null) return;

            Search(new SecurityMasterEntityKey()
            {
                MasterCategory = securityMasterEntity.MasterCategory,
                MasterSubcategory = securityMasterEntity.MasterSubcategory,
                MasterCodeItem = securityMasterEntity.MasterCodeItem
            });

            if (mode == GuiDisplayMode.Amend)
            {
                Amend();
            }
        }

        private void InitGui()
        {
            InitBindingContext();
            InitCombo();
            InitDisplayMode();

            this.ParentAbstractForm.AcceptButton = this.okBut;

            // 手动处理 ESC 键
            this.ParentAbstractForm.KeyPreview = true; // 允许表单接收按键事件
            this.ParentAbstractForm.KeyDown += (sender, e) =>
            {
                if (e.KeyCode == Keys.Escape)
                {
                    this.ParentAbstractForm.DialogResult = DialogResult.Cancel;
                    this.ParentAbstractForm.Close();
                }
            };
        }

        private void InitCombo()
        {
            validIndcCombo.SetDataSource(YesNoPolicy.GetInstance().GetComposeMessages(), true);
        }

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

            masterCategoryTxt.Set(SecurityMasterEntity.MASTER_CATEGORY, masterCategoryLabel.Text, EnumEditModeColor.Required);
            masterSubcategoryTxt.Set(SecurityMasterEntity.MASTER_SUBCATEGORY, masterSubcategoryLabel.Text,EnumEditModeColor.Required);
            masterCodeItemTxt.Set(SecurityMasterEntity.MASTER_CODE_ITEM, masterCodeItemLabel.Text, EnumEditModeColor.Required);
            localDescriptionTxt.Set(SecurityMasterEntity.LOCAL_DESCRIPTION);
            engDescriptionTxt.Set(SecurityMasterEntity.ENG_DESCRIPTION);
            valueTxt.Set(SecurityMasterEntity.VALUE, valueLabel.Text, EnumEditModeColor.Required);
            validIndcCombo.Set(SecurityMasterEntity.VALID_INDC, validIndcLabel.Text, EnumEditModeColor.Required);
            orderByTxt.Set(SecurityMasterEntity.ORDER_BY, orderByLabel.Text, EnumEditModeColor.Required);
            remarkTxt.Set(SecurityMasterEntity.REMARK);

            guiOperateHelper = new GuiOperateHelper();
        }

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

            SetDisplayMode();
        }

        private void SetDisplayMode()
        {
            if (this.DisplayMode == GuiDisplayMode.View)
            {
                okBut.Visible = false;
                guiOperateHelper.EnableControls(false, contentPanel);
            }
            else if (this.DisplayMode == GuiDisplayMode.Amend || this.DisplayMode == GuiDisplayMode.Create)
            {
                okBut.Visible = true;
                guiOperateHelper.EnableControls(true, contentPanel);

                if (this.DisplayMode == GuiDisplayMode.Amend) guiOperateHelper.EnableControls(false, masterCategoryTxt, masterCodeItemTxt, masterSubcategoryTxt);
            }
        }

        private void PackUIToEntity()
        {
            guiBindingContext.DataPack();
            securityMasterEntity.MasterCategory = masterCategoryTxt.Text;
            securityMasterEntity.MasterSubcategory = masterSubcategoryTxt.Text;
            securityMasterEntity.MasterCodeItem = masterCodeItemTxt.Text;
            securityMasterEntity.Value = valueTxt.Text;
            //.....
        }

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

            return true;
        }

        private void Search(SecurityMasterEntityKey masterEntityKey)
        {
            try
            {
                securityMasterEntity = securityMasterRequest.FindByKey(masterEntityKey);

                if (securityMasterEntity == null)
                {
                    ShowMessageBox.ShowInfo(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_WS_RECORD_NOT_FOUND));
                }
                else
                {
                    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();

            securityMasterEntity = new SecurityMasterEntity()
            {
                CreatedBy = string.Empty,
                UpdatedBy = string.Empty,
                CreatedDatetime = DateTime.Now,
                UpdatedDatetime = DateTime.Now,
            };

            PackEntityToUI();
        }

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

            SetDisplayMode();
        }

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

        }

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

                PackUIToEntity();


                if (this.DisplayMode == GuiDisplayMode.Create)
                    securityMasterRequest.Insert(securityMasterEntity);
                else
                    securityMasterRequest.Update(securityMasterEntity);


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

                this.ParentAbstractForm.OutputData = securityMasterEntity;

                this.ParentAbstractForm.DialogResult = DialogResult.OK;
            }
            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)
        {
            if (GuiDisplayMode.View != this.DisplayMode)
            {
                DialogResult result = ShowMessageBox.ShowOption(securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM_CANCEL), securityMessagePolicy.ComposeMessage(SecurityMessagePolicy.GUI_CONFIRM));

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

            this.ParentAbstractForm.DialogResult = DialogResult.Cancel;
        }
    }
}
