Inventec.cs 13.5 KB
/*
 * 马来西亚 英华达 Inventec
 * 2020-4-21
 */

using System;
using System.Collections.Generic;
using System.Linq;
using Model;
using Asa.FaceControl;
using System.Web.Script.Serialization;
using NLog.Fluent;

namespace ExtensionGroup
{
    public class Inventec : IExtension
    {
        private List<ExtensionControl> extensions;
        private readonly Dictionary<string, int> reelID;
        private ServerContent[] serverContent;
        private string reelIDKey = "";
        private bool needPrint = false;
        public event IExtension.PrintDelegate Printing;
        public event IExtension.PrintDelegate SaveRetrospect;

        public Inventec()
        {
            reelID = new();
        }

        public void Dispose()
        {
        }

        public void Load(List<ExtensionControl> extensions)
        {
            this.extensions = extensions;

            if (System.IO.File.Exists(FilePath.CONFIG_REELID))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_REELID);
                for (int i = 0; i < lines.Length; i++)
                {
                    string[] arr = lines[i].Split(',');
                    if (arr.Length != 2) continue;
                    reelID.Add(arr[0], Convert.ToInt32(arr[1]));
                }
            }
        }

        public void Clear()
        {
            for (int i = 0; i < extensions.Count; i++)
            {
                if (!extensions[i].CanClear) continue;
                if (extensions[i].Control is FaceComboBox box)
                    box.Items.Clear();
                extensions[i].Control.Text = "";
            }
        }

        public void SetKey(string[] originalCode, Dictionary<string, string> key)
        {
            for (int i = 0; i < extensions.Count; i++)
            {
                if (key.ContainsKey(extensions[i].Key))
                    extensions[i].Control.Text = key[extensions[i].Key];
            }

            //int index = extensions.FindIndex(match => match.Control.Name == "TxtSupplierPN");
            //if (index == -1) return;
            //PNPress(extensions[index].Control, EventArgs.Empty);

      
        }

        public void Update()
        {
        }



        private class ServerContent
        {
            public string supplierPn { set; get; }
            public string partNumber { set; get; }
            public string description { set; get; }
        }

        private void SaveReelID()
        {
            int idx = 0;
            string[] lines = new string[reelID.Count];
            foreach (string key in reelID.Keys)
                lines[idx++] = string.Format("{0},{1}", key, reelID[key]);
            System.IO.File.WriteAllLines(FilePath.CONFIG_REELID, lines);
        }

        private string GetHttpReelID(string id)
        {
            Dictionary<string, string> param = new();
            string[] key = new string[] { "RI", "PN", "LOC", "QTY", "SP", "BATCH", "PRODATE", "EXPDATE" };
            param.Add(key[0], id);
            for (int i = 1; i < key.Length; i++)
            {
                string name = "Txt" + key[i];
                int index = extensions.FindIndex(match => match.Control.Name == name);
                if (index > -1) param.Add(key[i], extensions[index].Control.Text);
            }

            string url = AppConfig.Read("HttpReelID");
            string json = Http.Post(url, param);
            if (json == "") return id;
            JavaScriptSerializer serializer = new();
            Dictionary<string, object> dic = (Dictionary<string, object>)serializer.DeserializeObject(json);

            if (!dic.TryGetValue("status", out object value))
                return id;

            if (!Convert.ToBoolean(value))
            {
                new FaceMessageBox("BoxReelIDInfoMaintain", dic["message"].ToString(), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();
                return id;
            }

            if (dic.TryGetValue("ri", out value))
                return value.ToString();
            else
                return id;

        }

        private void GetHttpJson(ControlBase ctl, out string json)
        {
            json = "";

            //if (DebugMode)
            //{
            //    if (System.IO.File.Exists(FilePath.CONFIG_HTTP_TEST_DATA))
            //        json = System.IO.File.ReadAllText(FilePath.CONFIG_HTTP_TEST_DATA);
            //}
            //else
            //{
            string url = AppConfig.Read(AppConfigKey.HTTP_SERVER) + ctl.Text;
                json = Http.Get(url);
            //}

            if (string.IsNullOrWhiteSpace(json))
                new FaceMessageBox("", Language.Dialog("ServerReturn"), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();

        }

        private void ReadHttpJsonContent(string json)
        {
            if (string.IsNullOrWhiteSpace(json)) return;
            serverContent = null;
            JavaScriptSerializer serializer = new();

            object[] obj = (object[])serializer.DeserializeObject(json);
            if (obj == null || obj.Length == 0)
            {
                new FaceMessageBox("", Language.Dialog("ServerJson"), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();
                return;
            }

            serverContent = new ServerContent[obj.Length];
            for (int i = 0; i < serverContent.Length; i++)
            {
                Dictionary<string, object> dic = (Dictionary<string, object>)obj[i];
                serverContent[i] = new();
                System.Reflection.PropertyInfo[] info = serverContent[i].GetType().GetProperties();
                for (int j = 0; j < info.Length; j++)
                {
                    if (dic.TryGetValue(info[j].Name, out object value))
                        info[j].SetValue(serverContent[i], value.ToString());
                }
            }
        }

        private void WriteConntrolText(ControlBase ctl)
        {
            if (serverContent == null) return;

            //获取linkKey的控件
            int index = extensions.FindIndex(match => match.Control == ctl);
            if (index == -1) return;
            string linkKey = extensions[index].LinkName;
            index = extensions.FindIndex(match => match.Control.Name == linkKey);
            if (index == -1) return;
            FaceComboBox cbo = (FaceComboBox)extensions[index].Control;

            //把partNumber写入Combo
            cbo.Items.Clear();
            string[] items = new string[serverContent.Length];
            for (int i = 0; i < serverContent.Length; i++)
                items[i] = serverContent[i].partNumber;
            if (items.Length > 0)
            {
                cbo.Items.AddRange(items);
                cbo.SelectedIndex = 0;
            }
        }



        //===== 以下为 Extension.json 的 Event =====

        //private void PNPress(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Log.Debug("Enter PNPress Method");
        //        ControlBase ctl = sender as ControlBase;
        //        GetHttpJson(ctl, out string json);
        //        ReadHttpJsonContent(json);
        //        WriteConntrolText(ctl);
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error("PNPress", ex);
        //    }
        //}

        //private void CustomerPNSelected(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Log.Debug("Enter CustomerPNSelected Method");
        //        FaceComboBox ctl = sender as FaceComboBox;
        //        if (ctl.SelectedIndex == -1) return;
        //        int index = extensions.FindIndex(match => match.Control == ctl);
        //        if (index == -1) return;
        //        string[] linkKey = extensions[index].LinkName.Split(',');
        //        if (linkKey.Length != 2) return;

        //        if (linkKey[0] == "TxtDescription")
        //        {
        //            index = extensions.FindIndex(match => match.Control.Name == linkKey[0]);
        //            if (index > -1)
        //                ((FaceTextBox)extensions[index].Control).Text = serverContent[ctl.SelectedIndex].description;
        //        }

        //        if (linkKey[1] == "TxtSupplierName")
        //        {
        //            index = extensions.FindIndex(match => match.Control.Name == linkKey[1]);
        //            if (index > -1)
        //                ((FaceTextBox)extensions[index].Control).Text = serverContent[ctl.SelectedIndex].supplierPn;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error("CustomerPNSelected", ex);
        //    }
        //}

        private void GetReelid(object sender, EventArgs e)
        {
           
            Log.Debug("Enter GetReelid Method");
            int idIndex = extensions.FindIndex(match => match.Control.Name == "TxtRI");
            string text = extensions[idIndex].Control.Text;

            //空ReelID自动生成
            if (text == "")
            {
                //读取参数
                string matchID = AppConfig.Read(AppConfigKey.REEL_ID_MATCH);
                AppConfig.Read(AppConfigKey.REEL_ID_PLACES, out int matchPlace);
                AppConfig.Read(AppConfigKey.REEL_ID_FILL_ZERO, out bool matchFill);
                string matchPrefix = AppConfig.Read(AppConfigKey.REEL_ID_PREFIX);
                string matchPostfix = AppConfig.Read(AppConfigKey.REEL_ID_POSTFIX);

                //把key替换成实际值
                string[] keys = ObjConversion.StrGetKey(matchID);
                for (int i = 0; i < keys.Length; i++)
                {
                    int index = extensions.FindIndex(match => match.Key == keys[i]);
                    if (index == -1) continue;
                    string oldValue = string.Format("[{0}]", keys[i]);
                    matchID = matchID.Replace(oldValue, extensions[index].Control.Text);
                }

                //查找是否存在
                if (!reelID.ContainsKey(matchID))
                    reelID.Add(matchID, 0);
                int val = reelID[matchID] + 1;
                reelIDKey = matchID;

                //填充0
                text = matchPrefix;
                if (matchFill)
                    text += string.Format("{0:d" + matchPlace + "}", val);
                else
                    text += val.ToString();
                text += matchPostfix;
                extensions[idIndex].Control.Text = text;
            }

            string newText = GetHttpReelID(text);
            extensions[idIndex].Control.Text = newText;
            Log.Debug("text=" + text + " newtext=" + newText + " " + (newText == text).ToString());
            if (newText == text)
            {
                needPrint = true;
                new FaceMessageBox("", Language.Dialog("RepeatPrint"), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();
            }
            else
            {
                needPrint = false;
            }
        }

        private void PrintLabel(object sender, EventArgs e)
        {
            Log.Debug("Enter PrintLabel Method");
            int index = extensions.FindIndex(match => match.Control.Name == "TxtRI");
            if (index > -1)
            {
                if (extensions[index].Control.Text == "")
                {
                    Log.Info("ReelID为空");
                    return;
                }
            }

            if (needPrint)
            {
                new FaceMessageBox("", Language.Dialog("RepeatPrint"), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();
                return;
            }


            AppConfig.Read(AppConfigKey.LABEL_EMPTY_CHECK, out bool check);

            if (check)
            {
                bool find = false;
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (extensions[i].Key != "" && extensions[i].Control.Text == "")
                    {
                        find = true;
                        break;
                    }
                }
                if (find)
                {
                    string text = Language.Dialog("LabelEmpty");
                    FaceMessageBox dlg = new("", text, System.Windows.Forms.MessageBoxButtons.YesNo);
                    System.Windows.Forms.DialogResult dr = dlg.ShowDialog();
                    if (dr == System.Windows.Forms.DialogResult.No)
                        return;
                }
            }

            Dictionary<string, string> key = new();
            for (int i = 0; i < extensions.Count; i++)
            {
                if (extensions[i].Key == "") continue;
                if (key.ContainsKey(extensions[i].Key))
                    key[extensions[i].Key] = extensions[i].Control.Text;
                else
                    key.Add(extensions[i].Key, extensions[i].Control.Text);
            }

            if (reelID.ContainsKey(reelIDKey))
            {
                reelID[reelIDKey]++;
                SaveReelID();
            }
            Printing?.Invoke(key);
            //Clear();

        }

        public bool SetKey(string[] originalCode, Dictionary<string, string> key, bool hasMatch, out string errmsg)
        {
            throw new NotImplementedException();
        }

        public void Print(bool match, Dictionary<string, string> key)
        {
            throw new NotImplementedException();
        }

        public void DrawTextBackground(Dictionary<string, string> key)
        {
            throw new NotImplementedException();
        }
    }
}