Item_General.cs 12.0 KB
/*
 * kaifa
 * 
 */

using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Model;
using Asa.FaceControl;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.IO;

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

        private Config config;
        private List<ExtensionControl> extensions;
        List<string> macroKey;
        private void ReadMacro()
        {
            macroKey = new();
            if (System.IO.File.Exists(FilePath.CONFIG_MACRO_KEY))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_MACRO_KEY);
                macroKey.AddRange(lines);
            }
        }

        public General(Config config)
        {
            this.config = config;
            ReadMacro();
        }

        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 = "";
            }
        }

        public void Dispose()
        {
        }

        public void Load(List<ExtensionControl> extensions)
        {
            this.extensions = extensions;
        }
        static bool mesResult = false;
        Dictionary<string, string> lastkey = null;
        //读码后第一步
        public bool SetKey(string[] originalCode, Dictionary<string, string> key, bool hasMatch, out string errmsg)
        {
            errmsg = "";
            lastkey = key;
            mesResult = false;
            var now = DateTime.Now;
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                //第一次刷新界面
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (key.ContainsKey(extensions[i].Key))
                        extensions[i].Control.Text = key[extensions[i].Key];
                }
            }
            Application.DoEvents();
            if (!string.IsNullOrEmpty(config.ReelIDKeyWord))
            {
                var Reelidstr = GetReelid();
                if (key.ContainsKey(config.ReelIDKeyWord))
                    key[config.ReelIDKeyWord] = Reelidstr;
                else
                    key.Add(config.ReelIDKeyWord, Reelidstr);
            }
            //客户定制key
            string exKey = ConfigHelper.Config.Get("Ex_UserDataKey", "UserData4");
            if (macroKey.Contains(exKey))
            {
                if (key.ContainsKey(exKey))
                    key[exKey] = DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "MM/dd/yyyy"));
                else
                {
                    key.Add(exKey, DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "MM/dd/yyyy")));
                }
            }
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                if (key.ContainsKey(Config.DataSource_DataKey) && ExtraFileData.AllData.ContainsKey(key[Config.DataSource_DataKey]))
                {
                    var extraData = ExtraFileData.AllData[key[Config.DataSource_DataKey]];
                    foreach (var d in extraData)
                    {
                        key[d.Key] = d.Value;
                    }
                }

                //第二次刷新界面
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (key.ContainsKey(extensions[i].Key))
                        extensions[i].Control.Text = key[extensions[i].Key];
                }
            }
            if (!updatereelid(key, out errmsg))
                return false;

            Application.DoEvents();
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                if (config.AutoPrint && hasMatch)
                {
                    //if (CanPrint())
                    PrintLabel(null, EventArgs.Empty);
                }
            }
            else
            {
                //PrintLabel(null, EventArgs.Empty);
            }

            SaveRetrospect?.Invoke(key);
            return true;
        }
        bool updatereelid(Dictionary<string, string> key, out string errmsg)
        {
            errmsg = "";
            if (!string.IsNullOrEmpty(config.HttpReelID))
            {
                if (!GetHttpReelID(key, out errmsg))
                {
                    LogNet.log.Error("GetHttpReelID:" + errmsg);
                    return false;
                }
                //key["ReelID"] = newid;
            }
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (extensions[i].Key.ToLower() == "reelid" && key.ContainsKey("reelid"))
                        extensions[i].Control.Text = key["reelid"];
                }
            }
            //SaveRetrospect?.Invoke(key);
            return true;
        }

        public void Update()
        {
        }

        private string GetReelid()
        {
            LogNet.log.Debug("Enter GetReelid Method");
            if (extensions != null)
            {
                int idIndex = extensions.FindIndex(match => match.Key == config.ReelIDKeyWord);
                if (idIndex == -1) return "";
            }
            //读取参数
            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++)
            {
                if (keys[i].ToLower().StartsWith("datetime"))
                {
                    string ov = string.Format("[{0}]", keys[i]);
                    var d = keys[i].Split(':');
                    if (d.Length == 2)
                    {
                        matchID = matchID.Replace(ov, DateTime.Now.ToString(d[1]));
                    }
                    else
                    {
                        matchID = matchID.Replace(ov, DateTime.Now.ToString());
                    }
                    continue;
                }

                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);
            }
            //SaveAddReelID();
            var reelID = ReadReelID();
            //填充0
            string text = matchPrefix + matchID;
            if (matchFill)
                text += string.Format("{0:d" + matchPlace + "}", reelID);
            else
                text += reelID.ToString();

            text += matchPostfix;
            return text;
        }

        private int ReadReelID()
        {
            int reelID = 1;
            try
            {
                var reelidfile = FilePath.CONFIG_REELID;
                if (Config.REEL_ID_AutoResetStrategy==1)
                {
                    Directory.CreateDirectory(reelidfile + "_dir");
                    reelidfile = Path.Combine(FilePath.CONFIG_REELID + "_dir", DateTime.Now.ToString("yyyyMMdd"));
                }
                else if (Config.REEL_ID_AutoResetStrategy == 2)
                {
                    Directory.CreateDirectory(reelidfile + "_dir");
                    reelidfile = Path.Combine(FilePath.CONFIG_REELID + "_dir", DateTime.Now.ToString("yyyyMM"));
                }
                if (File.Exists(reelidfile))
                {
                    string text = File.ReadAllText(reelidfile);
                    bool bln = int.TryParse(text, out reelID);
                    LogNet.log.Info($"ReadReelID {reelidfile}, {bln}, text={text}");
                    File.WriteAllText(reelidfile, (reelID + 1).ToString());
                    LogNet.log.Info($"Save ReelID:{reelID + 1}");
                }
                else
                {
                    reelID = 1;
                    File.WriteAllText(reelidfile, (reelID + 1).ToString());
                    LogNet.log.Info($"ReadReelID {reelidfile} Create");
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("ReadReelID", ex);
                MessageBox.Show(ex.Message, "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
            return reelID;
        }

        private void GetHttpReelID(object sender, EventArgs e)
        {
            updatereelid(lastkey, out _);
        }
        private void PrintLabel(object sender, EventArgs e)
        {
            LogNet.log.Debug("Enter PrintLabel Method");
            if (lastkey == null) return;
            //Dictionary<string, string> key = new();
            for (int i = 0; i < extensions.Count; i++)
            {
                if (extensions[i].Key == "") continue;
                if (lastkey.ContainsKey(extensions[i].Key))
                    lastkey[extensions[i].Key] = extensions[i].Control.Text;
                else
                    lastkey.Add(extensions[i].Key, extensions[i].Control.Text);
            }
            //var keys =new List<string>(lastkey.Keys);

            Printing?.Invoke(lastkey);

        }
        private bool GetHttpReelID(Dictionary<string, string> key, out string errmsg)
        {
            errmsg = "";
            string url = config.HttpReelID;
            string json = Http.PostJson(url, null, key);
            if (json == "")
            {
                errmsg = "Api error";
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    new FaceMessageBox("BoxReelIDInfoMaintain", errmsg, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();

                return false;
            }
            JavaScriptSerializer serializer = new();
            Dictionary<string, object> dic;
            try
            {
                dic = (Dictionary<string, object>)serializer.DeserializeObject(json);
            }
            catch
            {
                errmsg = "Api parse error:\r\n" + json;
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    new FaceMessageBox("BoxReelIDInfoMaintain", errmsg, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();

                return false;
            }

            if (!dic.TryGetValue("CODE", out object value))
            {
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    new FaceMessageBox("BoxReelIDInfoMaintain", "Api return data error:\r\n" + json, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                else
                    errmsg = "Api return data error:\r\n" + json;
                return false;
            }

            if (Convert.ToInt32(value) != 0)
            {
                errmsg = "Api parse error:\r\n" + dic["MSG"].ToString();
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    new FaceMessageBox("BoxReelIDInfoMaintain", errmsg, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();

                return false;
            }

            foreach (var kc in key.Keys)
            {
                if (dic.TryGetValue(kc, out value))
                {
                    key[kc] = value.ToString();
                }
            }

            if (!string.IsNullOrEmpty(key["ReelID"]))
            {
                return true;
            }
            else
                return false;

        }




    }
}