Item_KaiFa.cs 10.2 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 KaiFa : IExtension
    {
        public event IExtension.PrintDelegate Printing;
        public event IExtension.PrintDelegate SaveRetrospect;
        private Config config;
        private int reelID = 0;
        private List<ExtensionControl> extensions;
      

        public KaiFa(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;
        public bool SetKey(string[] originalCode, Dictionary<string, string> key, bool hasMatch,out string errmsg)
        {
            errmsg = "";
            mesResult = false;
            SaveAddReelID();
            var now = DateTime.Now;
            var Reelidstr = $"DP{now:yy}{reelID:000000000}";
            if (key.ContainsKey("Reelid"))
            {
                key["Reelid"] = Reelidstr;
            }
            else
                key.Add("Reelid", Reelidstr);



            for (int i = 0; i < extensions.Count; i++)
            {
                if (key.ContainsKey(extensions[i].Key))
                    extensions[i].Control.Text = key[extensions[i].Key];
            }



            Application.DoEvents();
            mesResult = GetMESInfo(key);            
            

            for (int i = 0; i < extensions.Count; i++)
            {
                if (key.ContainsKey(extensions[i].Key))
                    extensions[i].Control.Text = key[extensions[i].Key];
            }
            if (!mesResult)
            {
                return false;
            }
            if (config.AutoPrint)
            {
                //if (CanPrint())
                    PrintLabel(null, EventArgs.Empty);
            }
            return true;
        }

        public void Update()
        {
        }

        private bool CanPrint()
        {
            int index = extensions.FindIndex(match => match.Control.Name == "TxtPart");
            if (index == -1) return false;
            if (extensions[index].Control.Text == "") return false;
            index = extensions.FindIndex(match => match.Control.Name == "TxtQty");
            if (index == -1) return false;
            if (extensions[index].Control.Text == "") return false;

            return true;
        }

        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 PrintLabel(object sender, EventArgs e)
        {


            LogNet.log.Debug("Enter PrintLabel Method");
            Dictionary<string, string> key = new(StringComparer.OrdinalIgnoreCase);
            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 (!mesResult)
            {
                LogNet.log.Debug("Enter PrintLabel Check mesResult");
                mesResult = GetMESInfo(key);

                for (int i = 0; i < extensions.Count; i++)
                {
                    if (key.ContainsKey(extensions[i].Key))
                        extensions[i].Control.Text = key[extensions[i].Key];
                }
                if (!mesResult)
                {
                    return;
                }
            }
            var keys =new List<string>(key.Keys);

            foreach (var kk in keys)
            {
                if (string.IsNullOrEmpty(key[kk]))
                    key[kk] = "NA";
            }
            SaveRetrospect?.Invoke(key);
            Printing?.Invoke(key);
        }

        private bool GetMESInfo(Dictionary<string, string> keyv)
        {
            string url = config.HttpServer;

            if (string.IsNullOrWhiteSpace(url))
                return false;


            if (TryGetDictValue(keyv, "PART")=="" && TryGetDictValue(keyv, "MPN") == "")
            {
                var fm = new FaceMessageBox("MES MSG", "CPN,MPN均为空,无法继续", System.Windows.Forms.MessageBoxButtons.OK);
                fm.TopMost = true;
                fm.ShowDialog();
                return false;
            }

            //PART=C02-07129-01,QTY=10000,LOT=20211215,ASL=YAGEO,VEN=004284,DCODE=202150,TRACE=38K4420537,Reelid=KF2135800000212
            int qty = 0;
            int.TryParse(TryGetDictValue(keyv, "QTY"), out qty);
            InitPPID_Request_DPS initPPID_Request_DPS = new InitPPID_Request_DPS()
            {
                ReelID = TryGetDictValue(keyv,"Reelid"),
                CPN = TryGetDictValue(keyv, "PART"),
                QTY = qty,
                LOT = TryGetDictValue(keyv, "LOT"),
                ToLoc = TryGetDictValue(keyv, "ToLoc"),
                FromLoc = TryGetDictValue(keyv, "FromLoc"),
                DCODE = TryGetDictValue(keyv, "DCODE"),
                PN = TryGetDictValue(keyv, "PN"),
                LotNo = TryGetDictValue(keyv, "LotNo"),
                UserId = TryGetDictValue(keyv, "UserId"),
                PRODATE = TryGetDictValue(keyv, "PRODATE"),
                BATCH = TryGetDictValue(keyv, "BATCH"),
                MPN = TryGetDictValue(keyv, "MPN"),
                SiteCode = TryGetDictValue(keyv, "SiteCode"),
                VEN = TryGetDictValue(keyv, "VEN"),
                TraceCode = TryGetDictValue(keyv, "TRACE"),
            };

            if (string.IsNullOrWhiteSpace(initPPID_Request_DPS.ToLoc))
                initPPID_Request_DPS.ToLoc = "CP30";

            Dictionary<string, string> heads = new Dictionary<string, string>();
            heads.Add("Token", "0001A156-7283-402F-895F-D3AE435CBA40");
            LogNet.log.Info("Send:" + JsonConvert.SerializeObject(initPPID_Request_DPS));
            string json = Http.PostJson(url, heads, initPPID_Request_DPS);
            if (json == "") return false;

            var respjson = JsonConvert.DeserializeObject<APIResponse>(json);

            if (!respjson.Success)
            {
                var fm = new FaceMessageBox("MES MSG", respjson.Error, System.Windows.Forms.MessageBoxButtons.OK);
                fm.TopMost = true;
                fm.ShowDialog();
                return false;
            }
            keyv["PART"] = respjson.Data.ToString();
            //LogNet.log.Info(json);

            return true;
        }

        string TryGetDictValue(Dictionary<string, string> dic, string key)
        {
            if (dic.ContainsKey(key))
            {
                return dic[key];
            }
            else
                return "";
        }

        public void DrawTextBackground(Dictionary<string, string> key)
        {
        }

        public void Print(bool match, Dictionary<string, string> key)
        {

        }

        public class InitPPID_Request_DPS
        {
            /*
             * {
 "ReelID":"A000001",
"PN":"RC0603FR-0710KL",
"LOT":"38G15508220018",
"QTY":"5000",
"PRODATE":"1719",
"BATCH":"RS000212"

             */
            //PPID
            public string ReelID { get; set; }
            public string PN { get; set; }
            public string LOT { get; set; }
            public decimal QTY { get; set; }
            public string PRODATE { get; set; }
            public string BATCH { get; set; }

            public string MPN { get; set; }

            public string CPN { get; set; }
            //工厂代码
            public string SiteCode { get; set; }
            //转出库位
            public string FromLoc { get; set; }
            //转入库位
            public string ToLoc { get; set; }
            //操作员工号
            public string UserId { get; set; }
            public string LotNo { get; set; }
            public string DCODE { get; set; }
            public string TraceCode { get; set; }
            public string VEN { get; set; }
        }

        public class APIResponse
        {
            //错误消息
            public string Error { get; set; }
            public string Msg { get; set; }
            //是否处理成功
            public bool Success { get; set; }
            //业务数据
            public object Data { get; set; }
        }
    }
}