using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DeviceRepairAndOptimization.Pages
{
    public partial class pageSytemSetting : FormBase
    {
        List<SysConfigInfo> sysconfigs;

        public pageSytemSetting()
        {
            InitializeComponent();

            this.Load += PageSytemSetting_Load;
        }

        private void PageSytemSetting_Load(object sender, EventArgs e)
        {
            InitializeConfigData();
        }

        void InitializeConfigData()
        {
            try
            {
                APIResponseData apiResponseData = CommonManager.Instance.GetAllConfigs();
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                sysconfigs = apiResponseData.ToDeserializeObject<List<SysConfigInfo>>();
                if ((sysconfigs?.Count ?? 0) > 0)
                    InitializeGroup(layoutControlGroup1, sysconfigs);
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        void InitializeGroup(LayoutControlGroup control, List<SysConfigInfo> sysConfigs)
        {
            string[] GroupKeys = sysConfigs.Select(x => x.GroupKey).Distinct().ToArray();

            control.BeginUpdate();
            int index = 0;

            foreach (string item in GroupKeys)
            {
                if (item.Trim().Equals("安全策略"))
                    continue;

                var vlayoutControlGroup = new LayoutControlGroup()
                {
                    Name = $"layoutControlGroup1{index++}",
                    Text = item,
                    ExpandButtonVisible = true
                };
                InitializeGroupItem(vlayoutControlGroup, sysConfigs.Where(x => x.GroupKey.Equals(item))?.ToList());
                control.AddRange(new BaseLayoutItem[] { vlayoutControlGroup });
            }
            control.EndUpdate();
        }

        void InitializeGroupItem(LayoutControlGroup control, List<SysConfigInfo> sysConfigs)
        {
            if ((sysConfigs?.Count ?? 0) == 0)
            {
                return;
            }
            int iCtlIndex = 0;

            control.BeginUpdate();
            foreach (SysConfigInfo item in sysConfigs)
            {
                var vNewLayOutCtl = new LayoutControl();
                var layoutItemCtl = new LayoutControlItem() { TextAlignMode = TextAlignModeItem.AutoSize };

                if (item.CtlType.ToUpper() == "CHECKBOX")
                {
                    var vCheckBoxEdit = new CheckEdit()
                    {
                        Name = $"checkEdit{item.Code}{iCtlIndex++}",
                        Checked = item.Value.ToLower().Equals("true"),
                        ToolTip = item.Description,
                        Tag = item
                    };
                    vCheckBoxEdit.Properties.Caption = item.Name;
                    vCheckBoxEdit.StyleController = vNewLayOutCtl;
                    layoutItemCtl.Control = vCheckBoxEdit;
                    layoutItemCtl.Name = $"layoutControlItem1{iCtlIndex++}";
                    layoutItemCtl.TextVisible = false;
                }
                else if (item.CtlType.ToUpper() == "TEXTBOX")
                {
                    var vTextBoxEdit = new TextEdit()
                    {
                        Name = $"textEdit{item.Code}{iCtlIndex++}",
                        ToolTip = item.Description,
                        Tag = item,
                        Text = item.Value,
                    };
                    layoutItemCtl.Control = vTextBoxEdit;
                    layoutItemCtl.Text = item.Name;
                    layoutItemCtl.Name = $"layoutControlItem1{iCtlIndex++}";
                    layoutItemCtl.TextVisible = true;
                }
                else
                {
                    continue;
                }
                control.Items.AddRange(new BaseLayoutItem[] { layoutItemCtl });
            }
            control.EndUpdate();
        }

        private BaseEdit FindConfigCtl(LayoutControlGroup control, string AutoID)
        {
            foreach (var item in control.Items)
            {
                SysConfigInfo sysconfig = null;
                if (item is BaseEdit)
                {
                    sysconfig = ((BaseEdit)item).Tag as SysConfigInfo;
                    if (sysconfig == null)
                    {
                        continue;
                    }
                    if ((sysconfig.AutoID.ToString() ?? string.Empty).Equals(AutoID))
                    {
                        return (BaseEdit)item;
                    }
                }
                if (item is LayoutControlItem)
                {
                    if (((LayoutControlItem)item).Control is BaseEdit)
                    {
                        sysconfig = ((LayoutControlItem)item).Control.Tag as SysConfigInfo;
                        if (sysconfig == null)
                        {
                            continue;
                        }
                        if ((sysconfig?.AutoID.ToString() ?? string.Empty).Equals(AutoID))
                        {
                            return (BaseEdit)((LayoutControlItem)item).Control;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (item is LayoutControlGroup)
                {
                    var vTmpFind = FindConfigCtl((LayoutControlGroup)item, AutoID);
                    if (vTmpFind != null)
                    {
                        return vTmpFind;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            List<SysConfigInfo> EditArray = new List<SysConfigInfo>();

            try
            {
                foreach (SysConfigInfo item in sysconfigs)
                {
                    var ctlFind = FindConfigCtl(layoutControlGroup1, item.AutoID.ToString());

                    if (ctlFind != null)
                    {

                        if (ctlFind.EditorTypeName.Equals("TextEdit"))
                        {
                            if (((TextEdit)ctlFind).Text.Length > 50)
                            {
                                throw new Exception($"项目:[{item.Name}]最大支持文本长度为{50}位！");
                            }

                            string value = ((TextEdit)ctlFind).Text;
                            if (string.IsNullOrEmpty(value))
                            {
                                if (!item.CanNull)
                                {
                                    throw new Exception($"项目:[{item.Name}]不可以配置为空！");
                                }
                            }

                            if (item.DataType.ToUpper().Equals("INT"))
                            {
                                int iCtlValueTemp = 0;
                                if (!int.TryParse(value.Trim(), out iCtlValueTemp))
                                {
                                    throw new Exception($"项目:[{item.Name}]配置内容不正确！");
                                }
                            }
                            else if (item.DataType.ToUpper().Equals("BOOL"))
                            {
                                bool iCtlValueTemp = false;
                                if (!bool.TryParse(value.Trim(), out iCtlValueTemp))
                                {
                                    throw new Exception($"项目:[{item.Name}]配置内容不正确！");
                                }
                            }
                            else
                            {
                                continue;
                            }

                            if (item.Value.Equals(value))
                                continue;

                            EditArray.Add(new SysConfigInfo
                            {
                                AutoID = item.AutoID,
                                Value = value
                            });
                        }
                        else if (ctlFind.EditorTypeName.Equals("CheckEdit"))
                        {
                            #region 复选框
                            bool value = ((CheckEdit)ctlFind).Checked;
                            if (item.Value.ToLower() != value.ToString().ToLower())
                            {
                                EditArray.Add(new SysConfigInfo
                                {
                                    AutoID = item.AutoID,
                                    Value = value.ToString().ToLower()
                                });
                            }
                            #endregion
                        }
                    }
                }

                if (EditArray.Count > 0)
                {
                    APIResponseData apiResponseData = CommonManager.Instance.EditConfigs(EditArray);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);
                    XtraMessageBoxHelper.Info("操作成功！");
                }
                else
                {
                    XtraMessageBoxHelper.Info("没有任何的项目更改！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}
