Item_General.cs 8.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;

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

        private Config config;
        private int reelID = 0;
        private List<ExtensionControl> extensions;
      

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

        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;
            ReadReelID();
        }
        static bool mesResult = false;
        Dictionary<string, string> lastkey = null;
        //读码后第一步
        public void SetKey(string[] originalCode, Dictionary<string, string> key, bool hasMatch)
        {
            lastkey = key;
            mesResult = false;            
            var now = DateTime.Now;            
            if (!string.IsNullOrEmpty(config.ReelIDKeyWord))
            {
                var Reelidstr = GetReelid();
                if (key.ContainsKey(config.ReelIDKeyWord))
                    key[config.ReelIDKeyWord] = Reelidstr;
                else
                    key.Add(config.ReelIDKeyWord, Reelidstr);
            }
            //第一次刷新界面
            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))
                return;

            Application.DoEvents();
            
            if (config.AutoPrint && hasMatch)
            {
                //if (CanPrint())
                    PrintLabel(null, EventArgs.Empty);
            }
        }
        bool updatereelid(Dictionary<string, string> key) {
            if (!string.IsNullOrEmpty(config.HttpReelID))
            {
                var newid = GetHttpReelID(key);
                if (string.IsNullOrEmpty(newid))
                    return false;
                key["ReelID"] = newid;                
            }

            for (int i = 0; i < extensions.Count; i++)
            {
                if (extensions[i].Key.ToLower() == "reelid")
                    extensions[i].Control.Text = key["reelid"];
            }
            SaveRetrospect?.Invoke(key);
            return true;
        }

        public void Update()
        {
        }

        private string GetReelid()
        {

            LogNet.log.Debug("Enter GetReelid Method");
            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++)
            {
                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();

            //填充0
            string text = matchPrefix;
            if (matchFill)
                text += string.Format("{0:d" + matchPlace + "}", reelID);
            else
                text += reelID.ToString();
            text += matchPostfix;
            return text;
        }

        private void ReadReelID()
        {
            try
            {
                if (System.IO.File.Exists(FilePath.CONFIG_REELID))
                {
                    string text = System.IO.File.ReadAllText(FilePath.CONFIG_REELID);
                    bool bln = int.TryParse(text, out reelID);
                    LogNet.log.Info($"ReadReelID {bln} text={text}");
                }
                else
                {
                    System.IO.FileStream fs = System.IO.File.Create(FilePath.CONFIG_REELID);
                    fs.Close();
                    reelID = 0;
                    LogNet.log.Info("ReadReelID Create");
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("ReadReelID", ex);
                System.Windows.Forms.MessageBox.Show(ex.Message, "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
        }

        private void SaveAddReelID()
        {
            try
            {
                LogNet.log.Debug("打印标签前的ID:" + reelID);
                reelID++;
                System.IO.File.WriteAllText(FilePath.CONFIG_REELID, reelID.ToString());
                LogNet.log.Info($"Save ReelID:{reelID}");
            }
            catch (Exception ex)
            {
                LogNet.log.Error("SaveAddReelID error", ex);
            }
        }

        private void GetHttpReelID(object sender, EventArgs e) {
            updatereelid(lastkey);
        }
        private void PrintLabel(object sender, EventArgs e)
        {
            LogNet.log.Debug("Enter PrintLabel Method");
            
            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);
            }
            var keys =new List<string>(key.Keys);
            
            Printing?.Invoke(key);
        }
        private string GetHttpReelID(Dictionary<string, string> key)
        {
            //return "test";
            string url = config.HttpReelID;
            string json = Http.PostJson(url,null, key);
            if (json == "") {
                new FaceMessageBox("BoxReelIDInfoMaintain", "Api error", System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                return "";
            }
            JavaScriptSerializer serializer = new();
            Dictionary<string, object> dic;
            try
            {
                dic = (Dictionary<string, object>)serializer.DeserializeObject(json);
            }
            catch {
                new FaceMessageBox("BoxReelIDInfoMaintain", "Api parse error:\r\n" + json, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                return "";
            }

            if (!dic.TryGetValue("CODE", out object value))
            {
                new FaceMessageBox("BoxReelIDInfoMaintain", "Api return data error:\r\n" + json, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                return "";
            }

            if (Convert.ToInt32(value)!=0)
            {
                new FaceMessageBox("BoxReelIDInfoMaintain", dic["MSG"].ToString(), System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                return "";
            }

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

        }




    }
}