PanaCIM.cs 13.0 KB
/*
 * PanaCIM
 */

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

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

        public PanaCIM()
        {
            reelID = new();
            export = 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++)
                {
                    if (lines[i].StartsWith("#")) continue;
                    string[] arr = lines[i].Split(',');
                    if (arr.Length != 2) continue;
                    reelID.Add(arr[0], Convert.ToInt32(arr[1]));
                }
            }

          
            string path = FilePath.CONFIG_DIR + "ImportSwitch.csv";
            if (System.IO.File.Exists(path))
            {
                string[] lines = System.IO.File.ReadAllLines(path);
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].StartsWith("#")) continue;
                    string[] arr = lines[i].Split(',');
                    if (arr.Length != 2) continue;
                    export.Add(arr[0], 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 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 == "TxtReelID");
            if (idIndex == -1) return;

            //读取参数
            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
            string text = matchPrefix;
            if (matchFill)
                text += string.Format("{0:d" + matchPlace + "}", val);
            else
                text += val.ToString();
            text += matchPostfix;
            extensions[idIndex].Control.Text = text;
        }

        private void PrintLabel(object sender, EventArgs e)
        {
            Log.Debug("Enter PrintLabel Method");
            int index = extensions.FindIndex(match => match.Control.Name == "TxtReelID");
            if (index > -1)
            {
                if (extensions[index].Control.Text == "")
                {
                    Log.Info("ReelID为空");
                    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();

        }

        private void Export(object sender, EventArgs e)
        {
            string path = AppConfig.Read("CopyTo");
            if (!System.IO.Directory.Exists(path)) return;

            List<string> values = new();
            foreach (string key in export.Keys)
            {
                if (string.IsNullOrWhiteSpace(export[key]))
                    values.Add("");
                else
                {
                    int idx = extensions.FindIndex(match => match.Key == export[key]);
                    values.Add(idx == -1 ? "" : extensions[idx].Control.Text);
                }
            }

            string filePath = System.IO.Path.GetTempFileName();
            string[] contents = new string[2];
            contents[0] = string.Join(",", export.Keys);
            contents[1]= string.Join(",", values);
            System.IO.File.WriteAllLines(filePath, contents);

            path += "MaterialImport.csv";
            System.IO.File.Delete(path);
            System.IO.File.Move(filePath, path);
            new FaceMessageBox("", Language.Dialog(LanguageDialogKey.SAVE_SUCCEED), System.Windows.Forms.MessageBoxButtons.OK).ShowDialog();
        }

        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();
        }
    }

}