Item_General.cs 22.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
/*
 * kaifa
 * 
 */

using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Model;
using Asa;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.IO;
using static BLL.Extension;
using System.Web.UI;
using Asa.FaceControl;
using System.Configuration;
using System.Linq;
using static BLL.Replacekeywords;
using RestSharp;
using System.Web;
using Http = Model.Http;
using System.Drawing;

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++)
                {
                    extensions[i].Control.ForeColor = Color.White;
                    if (key.ContainsKey(extensions[i].Key))
                        extensions[i].Control.Text = key[extensions[i].Key].Replace("<OCR>", "");
                }
            }
            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)
            {
                //使用key填充时,请处理字段开头的<OCR>字段
                if(key.ContainsKey(Config.DataSource_DataKey))
                {
                    string CleanData = key[Config.DataSource_DataKey].Replace("<OCR>", "");
                    if (key.ContainsKey(Config.DataSource_DataKey) && ExtraFileData.AllData.ContainsKey(CleanData))
                    {
                        var extraData = ExtraFileData.AllData[CleanData];
                        foreach (var d in extraData)
                        {
                            key[d.Key] = d.Value;
                        }
                    }
                }

                //第二次刷新界面
                for (int i = 0; i < extensions.Count; i++)
                {
                    extensions[i].Control.ForeColor = Color.White;
                    if (key.ContainsKey(extensions[i].Key))
                        extensions[i].Control.Text = key[extensions[i].Key].Replace("<OCR>", "");
                }
            }
            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))
            {
                Dictionary<string, object> pairs = new Dictionary<string, object>(); 
                if (!GetHttpReelID(key, out errmsg,out pairs))
                {
                    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);
            }

            Printing?.Invoke(lastkey);  
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="errmsg"></param>
        /// <param name="dic">返回请求后,替换完成的键值对</param>
        /// <returns></returns>
        private bool GetHttpReelID(Dictionary<string, string> key, out string errmsg,out Dictionary<string,object> dic)
        {
            errmsg = "";
            dic = null;
            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;
        }

        // 定义动态按钮点击事件处理方法
        private void DynamicButtonClick(object sender, EventArgs e)
        {
            var listexten = extensions.Where(a => a.Type == "TextBox").ToDictionary(kvp => kvp.Key, kvp => kvp.Control.Text);
            string jsondata = Replacekeywordss(listexten);
            ResponseDatas lists = JsonConvert.DeserializeObject<ResponseDatas>(jsondata);
            foreach (var responseItems in lists.Items)
            {
                foreach (var item in responseItems)
                {
                    foreach (var items in extensions.Where(a => a.Type == "TextBox"))
                    {
                        if (items.Key == item.Name)
                        {
                            items.Control.Text = item.Value.ToString();
                        }
                        //items.Control.Text = item.Value.ToString();
                    }
                }
            }
        }

        #region        
        //public void Replacekeywordss() 
        //{

        //try
        //{
        //    //未找到任何关键字信息
        //    if (lastkey == null || lastkey.Count < 0)
        //    {
        //        throw new Exception("未找到任何关键字信息,请重新设置!");
        //    }
        //    string Tokensurl = "";
        //    // 判断并处理 grn_num 和 grn_line
        //    if (lastkey.ContainsKey("grn_num") && lastkey.ContainsKey("grn_line"))
        //    {
        //        string grn_numValue = lastkey["grn_num"];
        //        string grn_lineValue = lastkey["grn_line"];

        //        // 发起 HTTP 请求,获取 token 的值
        //        string tokensValue = Http.Get(Tokensurl);
        //        if (string.IsNullOrEmpty(tokensValue))
        //        {
        //            LogNet.log.Info($"{Tokensurl}:获取token为空!");
        //            throw new Exception("获取tokens失败!");

        //        }
        //        string ido = "IR_SLAPIs";
        //        string props = "GRNNUM,GRNLine,vendnum,vendor_name,po_num,po_line,po_release,item_code,Rating,qty_ordered,qty_received,rcvd_dat";
        //        string customloadmethodparms = $"{grn_numValue},,{grn_lineValue},";
        //        string url = $"http://IRI002S/IDORequestService/MGRestService.svc/json/{ido}/{props}/adv?customloadmethod=IR_GetGrnDetailSp&customloadmethodparms={customloadmethodparms}&loadtype=NEXT&readonly=true&rowcap=-1";
        //        // 发起第二个 HTTP 请求,并处理返回值
        //        string result = Http.SendGetRequest(url, tokensValue);
        //        var lists = JsonConvert.DeserializeObject<ResponseData>(result);
        //        if (lists.MessageCode != 0 || lists.Items.Count == 0)
        //        {
        //            throw new Exception($"{lists.Message}");
        //        }
        //        LogNet.log.Info($"{url}:返回数据{lists}");
        //        // 处理 result 返回的数据
        //        // 刷新关键字的值
        //        foreach (var item in lists.Items)
        //        {
        //            for (int i = 0; i < extensions.Count; i++)
        //            {
        //                if (extensions[i].Key == item.Name)
        //                {
        //                    extensions[i].Control.Text = item.Value.ToString();
        //                }
        //            }
        //        }
        //    }
        //}
        //catch (Exception ex)
        //{
        //    MessageBox.Show(ex.Message,"提示");
        //    //throw new Exception(ex.Message);
        //}
        //    try
        //    {
        //        //是否需要请求token           
        //        string RequestMethod = ConfigurationManager.AppSettings["RequestMethod"];
        //        //是否需要请求token           
        //        bool isTokenRequired = Convert.ToBoolean(ConfigurationManager.AppSettings["isTokenRequired"]);
        //        //请求tokenurl
        //        string tokenurl = ConfigurationManager.AppSettings["tokenurl"];
        //        //请求正常数据
        //        string url = ConfigurationManager.AppSettings["url"];
        //        //关键字,请用,号分割
        //        string keywords = ConfigurationManager.AppSettings["keywords"];
        //        if (isTokenRequired && tokenurl != null)
        //        {
        //            throw new Exception("需要请求token,请填写tokenurl!");
        //        }
        //        if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(keywords))
        //        {
        //            throw new Exception("URL和关键字不能为空");
        //        }
        //        //用户提供需要更换的关键字
        //        var UserKeyword = keywords.Split(',').ToList();
        //        //未找到任何ns100设置的关键字信息
        //        if (lastkey == null || lastkey.Count < 0)
        //        {
        //            throw new Exception("未找到任何关键字信息,请重新设置!");
        //        }
        //        //判断ns100关键字,是否包含用户提供的关键字
        //        bool allinkey = UserKeyword.All(value => lastkey.ContainsKey(value));
        //        if (!allinkey)
        //        {
        //            throw new Exception($"关键字未包含;{keywords}");
        //        }
        //        ResponseData lists = null;
        //        if (isTokenRequired)
        //        {
        //            string tokensValue = Http.Get(tokenurl);
        //            if (string.IsNullOrEmpty(tokensValue))
        //            {
        //                LogNet.log.Info($"{tokenurl}:获取token为空!");
        //                throw new Exception("获取tokens失败!");
        //            }
        //            string ido = "IR_SLAPIs";
        //            string props = "GRNNUM,GRNLine,vendnum,vendor_name,po_num,po_line,po_release,item_code,Rating,qty_ordered,qty_received,rcvd_dat";
        //            string customloadmethodparms = $"{UserKeyword},";
        //            //string url = $"http://IRI002S/IDORequestService/MGRestService.svc/json/{ido}/{props}/adv?customloadmethod=IR_GetGrnDetailSp&customloadmethodparms={customloadmethodparms}&loadtype=NEXT&readonly=true&rowcap=-1";
        //            url += $"?key={customloadmethodparms}";
        //            LogNet.log.Info($"请求url:{url}");
        //            string result = Http.SendGetRequest(url, tokensValue);
        //            lists = JsonConvert.DeserializeObject<ResponseData>(result);
        //            if (lists.MessageCode != 0 || lists.Items.Count == 0)
        //            {
        //                throw new Exception($"{lists.Message}");
        //            }
        //            LogNet.log.Info($"{url}:返回数据{lists}");
        //        }
        //        else
        //        {
        //            string customloadmethodparms = $"{UserKeyword},";
        //            url += $"?key={customloadmethodparms}";
        //            LogNet.log.Info($"请求url:{url}");
        //            string result = Http.Requestdata(url);
        //            lists = JsonConvert.DeserializeObject<ResponseData>(result);
        //            if (lists.MessageCode != 0 || lists.Items.Count == 0)
        //            {
        //                throw new Exception($"{lists.Message}");
        //            }
        //            LogNet.log.Info($"{url}:返回数据{lists}");
        //        }
        //        foreach (var item in lists.Items)
        //        {
        //            for (int i = 0; i < extensions.Count; i++)
        //            {
        //                if (extensions[i].Key == item.Name)
        //                {
        //                    extensions[i].Control.Text = item.Value.ToString();
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        MessageBox.Show(ex.Message); ;
        //    }         
        //}
        #endregion

        public void DrawTextBackground(Dictionary<string, string> key)
        {
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                bool focused = false; // 用于跟踪是否已经聚焦到第一个匹配的文本框
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (key.ContainsKey(extensions[i].Key))
                    {
                        if (key[extensions[i].Key].StartsWith("<OCR>"))
                        {
                            extensions[i].Control.ForeColor = Color.Yellow;
                        }
                        if (!focused && key[extensions[i].Key].StartsWith("<OCR>"))
                        {
                            extensions[i].Control.Focus();
                            focused = true; // 已经聚焦,不再继续
                        }
                    }

                }
            }
            Application.DoEvents();
        }

        public void Print(bool match, Dictionary<string, string> key)
        {
            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                //自动打印and模板匹配成功,只负责打印标签
                if (config.AutoPrint && match)
                {
                    PrintLabel(null, EventArgs.Empty);
                }
            }     
            //进行追溯配置保存
            SaveRetrospect?.Invoke(key);
        }

        public Dictionary<string, string> ReplaceData(Dictionary<string, string> key)
        {
            string err = null;
            Dictionary<string, object> dic=new Dictionary<string, object>();
            if (!GetHttpReelID(key, out err, out dic))
            {
                return key;
            }           
            return dic?.ToDictionary(a=>a.Key,a=>a.Value.ToString());
        }
    }
}