Item_Alcoelectro.cs 13.7 KB
/*
 * 西班牙 Alcoelectro
 * 
 */

using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Model;
using Asa.FaceControl;

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

        private List<ExtensionControl> extensions;
        private ServerContent[] serverContent;
        private Config config;
        private int reelID;

        public Alcoelectro(Config config)
        {
            reelID = 0;
            this.config = config;
        }

        public void Dispose()
        {
        }

        public void Load(List<ExtensionControl> extensions)
        {
            this.extensions = extensions;
            try
            {
                if (!System.IO.File.Exists(FilePath.CONFIG_REELID))
                {
                    System.IO.FileStream fs = System.IO.File.Create(FilePath.CONFIG_REELID);
                    fs.Close();
                }

                string text = System.IO.File.ReadAllText(FilePath.CONFIG_REELID);
                int.TryParse(text, out reelID);
                string str = "Load reelID:" + text;
                LogNet.log.Info(str);
            }
            catch (Exception ex)
            {
                LogNet.log.Error("Alcoelectro", ex);
                System.Windows.Forms.MessageBox.Show(ex.Message, "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
            Clear();
        }

        public void Clear()
        {
            LogNet.log.Info("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 = "";
            }

            int idx = extensions.FindIndex(match => match.Control.Name == "BtnPrint");
            if (idx > -1) extensions[idx].Control.Enabled = false;
            Update();
        }

        public bool SetKey(string[] originalCode, Dictionary<string, string> key, bool hasMatch,out string errmsg)
        {
            errmsg = "";
            LogNet.log.Info("SetKey()");
            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 == "ctxt_PN");
            if (index > -1) PNPress(extensions[index].Control, EventArgs.Empty);

            return true;
        }

        public void Update()
        {
            LogNet.log.Info("Update()");
            int index = extensions.FindIndex(match => match.Control.Name == "CboCustomerPN");
            if (index > -1) ((FaceComboBox)extensions[index].Control).ReadOnly = config.SelectHttpPN;
            index = extensions.FindIndex(match => match.Control.Name == "BtnSetID");
            if (index > -1) ((FaceButton)extensions[index].Control).Enabled = !config.SelectHttpPN;
        }



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

        private void SaveReelID()
        {
            try
            {
                //if (streamID != null)
                //{
                //    byte[] array = System.Text.Encoding.UTF8.GetBytes(reelID.ToString());
                //    streamID.Seek(0, System.IO.SeekOrigin.Begin);
                //    streamID.Write(array, 0, array.Length);
                //    streamID.Flush();
                //    Log.Info("Save ReelID" + reelID);
                //}


                System.IO.File.WriteAllText(FilePath.CONFIG_REELID, reelID.ToString());
                LogNet.log.Info("Save ReelID:" + reelID);

            }
            catch (Exception ex)
            {
                LogNet.log.Error("SaveReelID error", ex);
            }
        }

        private void GetHttpJson(ControlBase ctl, out string json)
        {
            json = "";
            if (config.SelectHttpPN)
            {
                string url = config.HttpServer + ctl.Text;
                json = Http.Get(url);
            }
            else
            {
                if (System.IO.File.Exists(FilePath.CONFIG_HTTP_TEST_DATA))
                    json = System.IO.File.ReadAllText(FilePath.CONFIG_HTTP_TEST_DATA);
            }
        }

        private void ReadHttpJsonContent(string json)
        {
            serverContent = null;
            JavaScriptSerializer serializer = new();

            object[] obj = (object[])serializer.DeserializeObject(json);
            if (obj == null || obj.Length == 0)
            {
                ClearHttpContent();
                new FaceMessageBox("", Language.Dialog("ServerJson"), System.Windows.Forms.MessageBoxButtons.OK, true).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))
                    {
                        if (value == null) 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;
            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;
            }

            index = extensions.FindIndex(match => match.Control.Name == "BtnSetID");
            if (index > -1) extensions[index].Control.Enabled = true;
            index = extensions.FindIndex(match => match.Control.Name == "BtnPrint");
            if (index > -1) extensions[index].Control.Enabled = false;
        }

        /// <summary>
        /// Clear text in "Customer PN", "Description", "Supplier Name" and "Barcode" when server doesn't return information
        /// </summary>
        private void ClearHttpContent()
        {
            int idx = extensions.FindIndex(match => match.Control.Name == "CboCustomerPN");
            if (idx > -1)
            {
                ((FaceComboBox)extensions[idx].Control).Items.Clear();
                extensions[idx].Control.Text = "";
            }
            idx = extensions.FindIndex(match => match.Control.Name == "TxtDescription");
            if (idx > -1) extensions[idx].Control.Text = "";
            //idx = extensions.FindIndex(match => match.Control.Name == "TxtSupplierPN");
            //if (idx > -1) extensions[idx].Control.Text = "";
            idx = extensions.FindIndex(match => match.Control.Name == "TxtSupplierName");
            if (idx > -1) extensions[idx].Control.Text = "";
            idx = extensions.FindIndex(match => match.Control.Name == "TxtBarcode");
            if (idx > -1) extensions[idx].Control.Text = "";
            idx = extensions.FindIndex(match => match.Control.Name == "BtnPrint");
            if (idx > -1) extensions[idx].Control.Enabled = false;
            Update();
        }



        //===== 以下为 Extension.json 的 Event =====
        private void PNPress(object sender, EventArgs e)
        {
            try
            {
                LogNet.log.Debug("Enter PNPress Method");
                ControlBase ctl = sender as ControlBase;
                GetHttpJson(ctl, out string json);
              

                if (string.IsNullOrWhiteSpace(json))
                {
                    ClearHttpContent();
                    new FaceMessageBox("", Language.Dialog("ServerReturn"), System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                }
                else
                {
                    ReadHttpJsonContent(json);
                    WriteConntrolText(ctl);
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("PNPress", ex);
            }
        }

        private void CustomerPNSelected(object sender, EventArgs e)
        {
            try
            {
                LogNet.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].producer;
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("CustomerPNSelected", ex);
            }
        }

        private void GetReelid(object sender, EventArgs e)
        {
            LogNet.log.Debug("Enter GetReelid Method");

            //读取参数
            string matchID = config.ReelIDMatch;
            int matchPlace = config.ReelIDPlaces;
            bool matchFill = config.ReelIDFillZero;
            string matchPrefix = config.ReelIDPrefix;
            string matchPostfix = config.ReelIDPostfix;

            //把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);
            }
          
            //查找是否存在
            int val = reelID + 1;
            //reelIDKey = matchID;

            //填充0
            string text = matchPrefix;
            if (matchFill)
                text += string.Format("{0:d" + matchPlace + "}", val);
            else
                text += val.ToString();
            text += matchPostfix;
            LogNet.log.Info(string.Format("GetReelid match={0} id={1} text={2}", matchID, val, text));

            //填入key=reelid的控件
            for (int i = 0; i < extensions.Count; i++)
            {
                if (extensions[i].Key.ToUpper() == "REELID")
                {
                    extensions[i].Control.Text = text;
                    break;
                }

            }

            int idx = extensions.FindIndex(match => match.Control.Name == "BtnPrint");
            if (idx > -1) extensions[idx].Control.Enabled = true;
        }

        private void PrintLabel(object sender, EventArgs e)
        {
            LogNet.log.Debug("Enter PrintLabel Method");
            bool check = config.LabelEmptyCheck;

            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, true);
                    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);
            }

            LogNet.log.Info("打印标签前的ID:" + reelID);
            reelID++;
            SaveReelID();
            SaveRetrospect?.Invoke(key);
            Printing?.Invoke(key);

        }


    }
}