Extension.cs 15.4 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;
using Asa.FaceControl;
using Model;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Drawing;

namespace BLL
{
    public class Extension : IDisposable
    {
        public event IExtension.PrintDelegate Printing;
        public event IExtension.PrintDelegate SaveRetrospect;

        private readonly IExtension currentExtension;
        private readonly Dictionary<string, IExtension> dicExtension;
        private readonly Alcoelectro alcoelectro;
        private readonly Inventec inventec;
        private readonly PanaCIM panaCIM;
        private readonly NanRui nanRui;
        private readonly KaiFa kaiFa;
        private readonly General General;
        private readonly Dictionary<string, Func<ControlBase>> dicControls;
        private readonly Dictionary<Type, Action<PropertyInfo, ControlBase, object>> dicControlAttribute;
        private readonly List<ExtensionControl> ctlGroup = new();

        private int ctlX, ctlY;
        private int pnlWidth;
        private FacePanel panel;
        private System.Drawing.Point startPoint;
        private Config config;

        public Extension(Config config)
        {
            this.config = config;
            LogNet.log.Info("加载扩展:" + config.ExtensionName);

            alcoelectro = new(config);
            inventec = new(config);
            panaCIM = new(config);
            nanRui = new(config);
            kaiFa = new(config);
            General = new(config);

            dicExtension = new()
            {
                { "Bwit", alcoelectro },
                { "Inventec", inventec },
                { "PanaCIM", panaCIM },
                { "NanRui", nanRui },
                { "KaiFa", kaiFa },
                { "General", General }
            };
            for (int i = 0; i < dicExtension.Count; i++)
            {
                dicExtension.ElementAt(i).Value.Printing += new IExtension.PrintDelegate(
                    delegate (Dictionary<string, string> content) { Printing?.Invoke(content); });
                dicExtension.ElementAt(i).Value.SaveRetrospect += new IExtension.PrintDelegate(
                    delegate (Dictionary<string, string> content) { SaveRetrospect?.Invoke(content); });
            }

            dicControls = new()
            {
                { "Label", () => { return new FaceLabel(); } },
                { "TextBox", () => { return new FaceTextBox(); } },
                { "Button", () => { return new FaceButton(); } },
                { "ComboBox", () => { return new FaceComboBox(); } },
                { "CheckBox", () => { return new FaceCheckBox(); } },
                { "ListBox", () => { return new FaceListBox(); } },
                { "PictureBox", () => { return new FacePictureBox(); } },
                { "NumericUpDown", () => { return new FaceNumericUpDown(); } },
                { "RadioBox", () => { return new FaceRadioBox(); } }
            };

            dicControlAttribute = new()
            {
                { typeof(string), AttributeString },
                { typeof(int), AttributeInt32 },
                { typeof(float), AttributeSingle },
                { typeof(bool), AttributeBoolean },
                { typeof(System.Drawing.Color), AttributeColor },
                { typeof(System.Drawing.ContentAlignment), AttributeContentAlignment },
                { typeof(System.Drawing.Font), AttributeFont },
                { typeof(System.Windows.Forms.HorizontalAlignment), AttributeHorizontalAlignment }
            };

            currentExtension = dicExtension[config.ExtensionName];
        }

        public void Dispose()
        {
            currentExtension.Dispose();
        }

        public void LoadPanel(FacePanel pnl,List<string> keywords)
        {
            panel = pnl;
            pnlWidth = pnl.Width;
            startPoint = new(6, panel.TextHeight + 6);
            object[] rows;
            if (!System.IO.File.Exists(FilePath.CONFIG_EXTENSION))
            {
                List<object[]> listrow = new List<object[]>();
                foreach (var key in keywords)
                {
                    Dictionary<string, object> L = new()
                    {
                        { "Type", "Label" },
                        {
                            "Attribute",
                            new Dictionary<string, object>()
                            {
                                { "Name", "clbl_" + key},
                                { "Font", "Arial,9,,"},
                                {"BorderWidth", 0},
                                {"Width", 100},
                                {"Height", 40},
                                {"Text", key},
                                {"TextAlign", "MiddleLeft"}
                            }
                        },
                    };
                    Dictionary<string, object> R = new() {
                        { "Type", "TextBox" },
                        { "Key", key },
                        { "LinkName", key },
                        { "CanClear", "True" },
                        {
                            "Attribute",
                            new Dictionary<string, object>()
                            {
                                { "Name", "ctxt_"+key},
                                { "Font", "Arial,9,,"},
                                { "Width", -1},
                                { "Height",40},
                                { "ShowDel","False"},
                                { "ShowQuery","False"},
                                { "Text",""},
                                {"Enabled",Config.AllowModifyPrintInfo }
                            }
                        }
                    };
                    listrow.Add(new object[] { L, R });
                }
                Dictionary<string, object> A = new()
                {
                    { "Type", "Button" },
                    {
                        "Attribute",
                        new Dictionary<string, object>()
                        {
                            { "Name", "BtnGetReelID"},
                            { "Font", "Arial,12,B,"},
                            //{"BorderWidth", 0},
                            {"Width", -1},
                            {"Height", 40},
                            {"Text", "Get ReelID"},

                        }
                    },
                    {
                        "Event",
                        new Dictionary<string, object>()
                        {
                            { "Click", "GetHttpReelID"}
                        }
                    }
                };
                Dictionary<string, object> B = new()
                {
                    { "Type", "Button" },
                    {
                        "Attribute",
                        new Dictionary<string, object>()
                        {
                            { "Name", "BtnPrint"},
                            { "Font", "Arial,12,B,"},
                            //{"BorderWidth", 0},
                            {"Width", -1},
                            {"Height", 40},
                            {"Text", Asa.FaceControl.Language.Dialog("PrintLabel","Print")},//"Print Label"
                            
                        }
                    },
                    {
                        "Event",
                        new Dictionary<string, object>()
                                {
                                    { "Click", "PrintLabel"}
                                }
                    }
                };
                if (!string.IsNullOrEmpty(config.HttpReelID))
                    listrow.Add(new object[] { A });
                #region 显示替换数据按钮
                string pnkey = ConfigHelper.Config.Get("SelectHttpPN_KeyWords", "");
                string pnurl=ConfigHelper.Config.Get("SelectHttpPN_Url","");
                if (BLLCommon.config.SelectHttpPN == true&&
                    !string.IsNullOrEmpty(pnkey)&&!string.IsNullOrEmpty(pnurl))
                {
                    Dictionary<string, object> C = new(){
                        { "Type", "Button" },
                        {"Attribute",new Dictionary<string, object>(){
                            { "Name", "DynamicButton" },                
                            { "Font", "Arial,12,B,"},                
                            {"Width", -1},                
                            {"Height", 40},                
                            {"Text", Asa.FaceControl.Language.Dialog("ReplaceData","替换数据")},}
                         },        
                        {           
                            "Event",           
                            new Dictionary<string, object>()
                            {
                                { "Click", "DynamicButtonClick" }            
                            }      
                        }    
                    };
                    listrow.Add(new object[] { C }); 
                }
                #endregion
                listrow.Add(new object[] { B });
                rows = listrow.ToArray();
            }
            else
            {
                string json = System.IO.File.ReadAllText(FilePath.CONFIG_EXTENSION);
                JavaScriptSerializer serializer = new();
                rows = (object[])serializer.DeserializeObject(json);

            }
            ctlY = startPoint.Y;
            for (int i = 0; i < rows.Length; i++)
                LoadRow(rows[i]);

            currentExtension.Load(ctlGroup);
        }

        public void Clear()
        {
            currentExtension.Clear();
        }

        public bool SetKey(string[] originalCode, Dictionary<string, string> key,bool hasMatch, out string errmsg)
        {
            return currentExtension.SetKey(originalCode, key, hasMatch, out errmsg);
        }
        public void Print(bool hasMatch, Dictionary<string, string> key)
        {
            currentExtension.Print(hasMatch, key);
        }
        public void DrawTextBackground(Dictionary<string, string> key)
        {
            currentExtension.DrawTextBackground(key);
        }

        public void Update()
        {
            currentExtension.Update();
        }

        public Dictionary<string, string> ReplaceData(Dictionary<string,string> dic) 
        {
           return General.ReplaceData(dic);
        }
        private void LoadRow(object row)
        {
            object[] cols = (object[])row;
            int maxHeight = 0;
            ctlX = startPoint.X;

            for (int i = 0; i < cols.Length; i++)
            {
                Dictionary<string, object> dic = (Dictionary<string, object>)cols[i];
                if (!dic.ContainsKey("Type")) continue;
                ControlBase ctl = dicControls[dic["Type"].ToString()].Invoke();
                ctl.Location = new System.Drawing.Point(ctlX, ctlY);
                panel.Controls.Add(ctl);

                ExtensionControl ext = new() { Control = ctl };
                PropertyInfo[] info = ext.GetType().GetProperties();
                for (int j = 0; j < info.Length; j++)
                {
                    if (dic.ContainsKey(info[j].Name))
                    {
                        if (info[j].PropertyType == typeof(bool))
                            info[j].SetValue(ext, Convert.ToBoolean(dic[info[j].Name]));
                        else
                            info[j].SetValue(ext, dic[info[j].Name].ToString());
                    }
                }
                ctlGroup.Add(ext);

                if (dic.ContainsKey("Attribute"))
                    LoadAttribute(ctl, (Dictionary<string, object>)dic["Attribute"]);
                ctlX += ctl.Width + 6;
                if (maxHeight < ctl.Height)
                    maxHeight = ctl.Height;

                if (dic.ContainsKey("Event"))
                    LoadEvent(ctl, (Dictionary<string, object>)dic["Event"]);
            }

            ctlY += maxHeight + 6;
        }

        private void LoadAttribute(ControlBase ctl, Dictionary<string, object> att)
        {
            Type type = ctl.GetType();
            foreach (string key in att.Keys)
            {
                PropertyInfo info = type.GetProperty(key);
                if (info == null) continue;
                dicControlAttribute[info.PropertyType].Invoke(info, ctl, att[key]);
            }
        }

        private void LoadEvent(ControlBase ctl, Dictionary<string, object> att)
        {
            try
            {
                Type type = ctl.GetType();
                foreach (string key in att.Keys)
                {
                    EventInfo info = type.GetEvent(key);
                    if (info == null) continue;
                    Delegate handler = Delegate.CreateDelegate(info.EventHandlerType, currentExtension, att[key].ToString());
                    info.AddEventHandler(ctl, handler);
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("LoadEvent", ex);
            }
        }

        private void AttributeInt32(PropertyInfo info, ControlBase ctl, object obj)
        {
            if (int.TryParse(obj.ToString(), out int result))
            {
                if (info.Name == "Width" && result < 1)
                    info.SetValue(ctl, pnlWidth - ctl.Left - 6);
                else
                    info.SetValue(ctl, result);
            }
        }

        private void AttributeString(PropertyInfo info, ControlBase ctl, object obj)
        {
            info.SetValue(ctl, obj.ToString());
        }

        private void AttributeBoolean(PropertyInfo info, ControlBase ctl, object obj)
        {
            if (bool.TryParse(obj.ToString(), out bool result))
                info.SetValue(ctl, result);
        }

        private void AttributeSingle(PropertyInfo info, ControlBase ctl, object obj)
        {
            if (float.TryParse(obj.ToString(), out float result))
                info.SetValue(ctl, result);
        }

        private void AttributeContentAlignment(PropertyInfo info, ControlBase ctl, object obj)
        {
            System.Drawing.ContentAlignment alignment = (System.Drawing.ContentAlignment)Enum.Parse(typeof(System.Drawing.ContentAlignment), obj.ToString());
            info.SetValue(ctl, alignment);
        }

        private void AttributeColor(PropertyInfo info, ControlBase ctl, object obj)
        {
            string[] s = obj.ToString().Split(',');
            if (s.Length != 3) return;

            if (!int.TryParse(s[0], out int r)) return;
            if (!int.TryParse(s[1], out int g)) return;
            if (!int.TryParse(s[2], out int b)) return;

            System.Drawing.Color color = System.Drawing.Color.FromArgb(r, g, b);
            info.SetValue(ctl, color);
        }

        private void AttributeFont(PropertyInfo info, ControlBase ctl, object obj)
        {
            System.Drawing.Font font = ObjConversion.StrToFont(obj.ToString());
            info.SetValue(ctl, font);
        }

        private void AttributeHorizontalAlignment(PropertyInfo info, ControlBase ctl, object obj)
        {
            System.Windows.Forms.HorizontalAlignment alignment = (System.Windows.Forms.HorizontalAlignment)Enum.Parse(typeof(System.Windows.Forms.HorizontalAlignment), obj.ToString());
            info.SetValue(ctl, alignment);
        }
       
    }
}