private static string MakeSure_source_2_lines(string temp_source)
        {
            Com_clDataContext dc = new Com_clDataContext();

            string[] s        = temp_source.Replace("<br>", "|").Split('|');
            string   o_source = s[1];
            var      q1       = from p1 in dc.p_source
                                where p1.source_id == o_source
                                select p1;

            if (q1.Count() == 0)
            {
                p_source new_source = new p_source()
                {
                    source_id   = s[1],
                    source_name = s[0]
                };
                dc.p_source.InsertOnSubmit(new_source);
                dc.SubmitChanges();
            }
            return(o_source);
        }
        private static int Write_sch_up(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Info($"        Enter Write_sch_up. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_drug = string.Empty, drug_name = string.Empty, o_STIME = string.Empty, o_clinic = string.Empty;
            int      o_t_dose = 0, o_t_DDD = 0, row_left = 0, row_n = 0;
            DateTime o_SDATE = new DateTime();
            int      order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    if (row_left > 0)
                    {
                        row_left--;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        // header(order_n)是資料表的位置與實際table的對照
                        // order_n是table的位置, header(order_n)的值是資料表的位置
                        // 有rowspan會干擾
                        int actual_n;

                        if ((row_left != row_n) && (row_left > 0) && (order_n > 0))
                        {
                            actual_n = order_n + 1;
                            o_drug   = drug_name;
                        }
                        else
                        {
                            actual_n = order_n;
                        }
                        //' 第一輪

                        if ((order_n == 1) && int.Parse(td.GetAttributeValue("rowspan", "1")) > 1)
                        {
                            //' order_n=1 名義上第一輪成分名稱的位置
                            drug_name = td.InnerHtml.Replace("<br>", " ");
                            row_n     = int.Parse(td.GetAttributeValue("rowspan", "1"));
                            row_left  = row_n;
                        }
                        switch (header_order[actual_n])
                        {
                        case 0:
                            // 成分名稱
                            o_drug = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 1:
                            // 就診日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 2:
                            // 就診時間
                            o_STIME = td.InnerText;
                            break;

                        case 3:
                            // 本院/他院
                            o_clinic = td.InnerText;
                            break;

                        case 4:
                            // 總劑量
                            if (td.InnerText != string.Empty)
                            {
                                o_t_dose = int.Parse(td.InnerText);
                            }
                            break;

                        case 5:
                            // 總DDD數
                            if (td.InnerText != string.Empty)
                            {
                                o_t_DDD = int.Parse(td.InnerText);
                            }
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudSCH_U
                            where (p.uid == strUID) && (p.drugname == o_drug) && (p.SDATE == o_SDATE)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudSCH_U newU = new tbl_cloudSCH_U()
                        {
                            uid      = strUID,
                            QDATE    = current_date,
                            SDATE    = o_SDATE,
                            drugname = o_drug,
                            STIME    = o_STIME,
                            clinic   = o_clinic,
                            t_dose   = (short?)o_t_dose,
                            t_DDD    = (short?)o_t_DDD
                        };

                        // 存檔

                        dc.tbl_cloudSCH_U.InsertOnSubmit(newU);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Info($"        Exit Write_sch_up. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        SCH_UP of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_drug}]");
                log.Info($"        Exit Write_sch_up. Current ID: {strUID}.");
                return(0);
            }
        }
        private static int Write_sch_re(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_sch_re. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int    count = 0;
            string o_drug = string.Empty, o_YM = string.Empty, drug_name = string.Empty;
            int    o_visit_n = 0, o_clinic_n = 0, o_t_dose = 0, o_t_DDD = 0, row_left = 0, row_n = 0;
            int    order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    if (row_left > 0)
                    {
                        row_left--;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        //' header(order_n)是資料表的位置與實際table的對照
                        //' order_n是table的位置, header(order_n)的值是資料表的位置
                        //' 有rowspan會干擾
                        int actual_n;

                        if ((row_left != row_n) && (row_left > 0) && (order_n > 0))
                        {
                            actual_n = order_n + 1;
                            o_drug   = drug_name;
                        }
                        else
                        {
                            actual_n = order_n;
                        }
                        //' 第一輪

                        if ((order_n == 1) && int.Parse(td.GetAttributeValue("rowspan", "1")) > 1)
                        {
                            //' order_n=1 名義上第一輪成分名稱的位置
                            drug_name = td.InnerHtml.Replace("<br>", " ");
                            row_n     = int.Parse(td.GetAttributeValue("rowspan", "1"));
                            row_left  = row_n;
                        }
                        switch (header_order[actual_n])
                        {
                        case 0:
                            // 成分名稱
                            o_drug = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 1:
                            // 就醫年月
                            o_YM = td.InnerText;
                            break;

                        case 2:
                            // 就醫次數
                            if (td.InnerText != string.Empty)
                            {
                                o_visit_n = int.Parse(td.InnerText);
                            }
                            break;

                        case 3:
                            // 就醫院所數
                            if (td.InnerText != string.Empty)
                            {
                                o_clinic_n = int.Parse(td.InnerText);
                            }
                            break;

                        case 4:
                            // 總劑量
                            if (td.InnerText != string.Empty)
                            {
                                o_t_dose = int.Parse(td.InnerText);
                            }
                            break;

                        case 5:
                            // 總DDD數
                            if (td.InnerText != string.Empty)
                            {
                                o_t_DDD = int.Parse(td.InnerText);
                            }
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudSCH_R
                            where (p.uid == strUID) && (p.drug_name == o_drug) && (p.YM == o_YM)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudSCH_R newR = new tbl_cloudSCH_R()
                        {
                            uid       = strUID,
                            QDATE     = current_date,
                            YM        = o_YM,
                            drug_name = o_drug,
                            visit_n   = (byte?)o_visit_n,
                            clinic_n  = (byte?)o_clinic_n,
                            t_dose    = (short?)o_t_dose,
                            t_DDD     = (short?)o_t_DDD
                        };

                        // 存檔

                        dc.tbl_cloudSCH_R.InsertOnSubmit(newR);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Debug($"        Exit Write_sch_re. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        SCH_RE of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_drug}]");
                log.Debug($"        Exit Write_sch_re. Current ID: {strUID}.");
                return(0);
            }
        }
Exemplo n.º 4
0
        private static int Write_reh(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_reh. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_class = string.Empty, o_source = string.Empty, o_diagnosis = string.Empty, o_type = string.Empty;
            string   o_curegrade = string.Empty, o_loca = string.Empty;
            int      o_amt = 0;
            DateTime o_begin_date = new DateTime(), o_end_date = new DateTime(), o_SDATE = new DateTime(), o_EDATE = new DateTime();

            int order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 診別
                            o_class = td.InnerText;
                            break;

                        case 1:
                            // 來源, 與別人有所不同, 只有兩行
                            if (td.InnerText != string.Empty)
                            {
                                o_source = MakeSure_source_2_lines(td.InnerHtml);
                            }
                            break;

                        case 2:
                            // 主診斷碼
                            o_diagnosis = td.InnerText;
                            break;

                        case 3:
                            // 治療類別
                            o_type = td.InnerText;
                            break;

                        case 4:
                            // 強度
                            o_curegrade = td.InnerText;
                            break;

                        case 5:
                            // 醫令總量
                            if (td.InnerText != string.Empty)
                            {
                                o_amt = int.Parse(td.InnerText);
                            }
                            break;

                        case 6:
                            // 就醫日期/住院日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_begin_date = d;
                            }
                            break;

                        case 7:
                            // 治療結束日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_end_date = d;
                            }
                            break;

                        case 8:
                            // 診療部位
                            o_loca = td.InnerText;
                            break;

                        case 9:
                            // 執行時間-起
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 10:
                            // 執行時間-迄
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_EDATE = d;
                            }
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudREH
                            where (p.uid == strUID) && (p.source == o_source) && (p.SDATE == o_SDATE) && (p.EDATE == o_EDATE)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudREH newREH = new tbl_cloudREH()
                        {
                            uid        = strUID,
                            QDATE      = current_date,
                            @class     = o_class,
                            source     = o_source,
                            type       = o_type,
                            diagnosis  = o_diagnosis,
                            curegrade  = o_curegrade,
                            amt        = (byte?)o_amt,
                            begin_date = o_begin_date,
                            end_date   = o_end_date,
                            loca       = o_loca,
                            SDATE      = o_SDATE,
                            EDATE      = o_EDATE
                        };

                        // 存檔

                        dc.tbl_cloudREH.InsertOnSubmit(newREH);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Debug($"        Exit Write_reh. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        REH of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_diagnosis}]");
                log.Debug($"        Exit Write_reh. Current ID: {strUID}.");
                return(0);
            }
        }
Exemplo n.º 5
0
        private async void ParsingTables(string o)
        {
            tb.ShowBalloonTip($"讀取完成 [{current_op?.UID}]", "開始解析與寫入資料庫", BalloonIcon.Info);
            log.Info($"[Info] all HTML loaded into memory. start to analyze. [{current_op?.UID}]");

            // Count = 0 代表最後一個 tab
            // 20200504 這裡一個BUG, 漏了把F_DATA_Loadcompleted刪掉,以至於不斷重複多次. ******

            /// 確定是最後一個tab這段程式到此結束
            /// 4. Parsing & Saving to SQL: async
            ///     4-1. 多工同時處理, 快速
            ///     4-2. 依照欄位資料/位置 Parsing
            ///     4-3. 存入SQL
            ///     4-4. 製作Query
            /// 查核機制?
            log.Debug($"[Start] async process, {current_op?.UID}");
            List <Response_DataModel> rds = await VPN_Dictionary.RunWriteSQL_Async(ListRetrieved);

            log.Debug($"[End] async process, {current_op?.UID}");

            /// 1. 讀取特殊註記, 如果有的話
            ///    這是在ContentPlaceHolder1_tab02
            ///    是個table
            // 每當刷新後都要重新讀一次
            // d 是parent HTML document
            HTMLDocument d = (HTMLDocument)g.Document;

            IHTMLElement Special_remark  = d?.getElementById("ContentPlaceHolder1_tab02");
            string       _special_remark = Special_remark?.innerText;

            // 製作紀錄by rd
            try
            {
                short?med_N = (short?)(from p1 in rds
                                       where p1.SQL_Tablename == SQLTableName.Medicine
                                       select p1.Count).Sum(),
                     lab_N = (short?)(from p1 in rds
                                      where p1.SQL_Tablename == SQLTableName.Laboratory
                                      select p1.Count).Sum(),
                     schedule_N = (short?)(from p1 in rds
                                           where p1.SQL_Tablename == SQLTableName.Schedule_report
                                           select p1.Count).Sum(),
                     op_N = (short?)(from p1 in rds
                                     where p1.SQL_Tablename == SQLTableName.Operations
                                     select p1.Count).Sum(),
                     dental_N = (short?)(from p1 in rds
                                         where p1.SQL_Tablename == SQLTableName.Dental
                                         select p1.Count).Sum(),
                     allergy_N = (short?)(from p1 in rds
                                          where p1.SQL_Tablename == SQLTableName.Allergy
                                          select p1.Count).Sum(),
                     discharge_N = (short?)(from p1 in rds
                                            where p1.SQL_Tablename == SQLTableName.Discharge
                                            select p1.Count).Sum(),
                     rehab_N = (short?)(from p1 in rds
                                        where p1.SQL_Tablename == SQLTableName.Rehabilitation
                                        select p1.Count).Sum(),
                     tcm_N = (short?)(from p1 in rds
                                      where p1.SQL_Tablename == SQLTableName.TraditionalChineseMedicine_detail
                                      select p1.Count).Sum();
                Com_clDataContext dc = new Com_clDataContext();
                tbl_Query2        q  = new tbl_Query2()
                {
                    uid    = ListRetrieved.First().UID,
                    QDATE  = ListRetrieved.First().QDate,
                    EDATE  = DateTime.Now,
                    remark = _special_remark
                };
                q.cloudmed_N  = med_N;
                q.cloudlab_N  = lab_N;
                q.schedule_N  = schedule_N;
                q.op_N        = op_N;
                q.dental_N    = dental_N;
                q.allergy_N   = allergy_N;
                q.discharge_N = discharge_N;
                q.rehab_N     = rehab_N;
                q.tcm_N       = tcm_N;
                dc.tbl_Query2.InsertOnSubmit(q);
                dc.SubmitChanges();
                log.Info($"[Final Step]Successfully write into tbl_Query2. From: {ListRetrieved.First().UID}, [{ListRetrieved.First().QDate}]");
                tb.ShowBalloonTip($"寫入完成 [{current_op?.UID}]", "已寫入資料庫", BalloonIcon.Info);
            }
            catch (Exception ex)
            {
                log.Error($"[Final Step]Failed to write into tbl_Querry2. From:  {ListRetrieved.First().UID}, [{ListRetrieved.First().QDate}] Error: {ex.Message}");
            }

            // 更新顯示資料
            string tempSTR = s.m.Label1.Text;

            s.m.Label1.Text = string.Empty;
            s.m.Label1.Text = tempSTR;
            s.m.Web_refresh();

            // activate hotkeys 4
            Activate_Hotkeys();

            log.Debug(o);
            log.Info("===========================================================================");
            log.Info($" ");
        }
        private void F_LoadCompleted(object sender, FrameLoadCompleteEventArgs e)
        {
            log.Debug($"++ Enter F_LoadCompleted from {e.Message}.");
            // 20200509 因為沒有先 -= F_LoadComplted, 造成了幽靈, 因此一定要 -= F_LoadComplted 在任何Exit之前.
            // 每次作業F_LoadCompleted只會被呼叫一次,沒有被洗掉的情形
            fm.FrameLoadComplete -= F_LoadCompleted;
            log.Debug($"@@ delete delegate F_LoadCompleted.");

            // 使用DocumentLoadCompletedButNotFrame, 會造成偶而不動作的症狀, 要找別的方式來處理沒插健保卡的判別
            // 方法

            if (e.Message == FrameLoadStates.DocumentLoadCompletedButNotFrame)
            {
                // 沒有lbluserID, 例如沒插健保卡
                // activate hotkeys 1
                Activate_Hotkeys();
                log.Debug($"++ Exit F_LoadCompleted (1/5). No NHI card inserted.");
                log.Info("===========================================================================");
                log.Info($" ");
                return;
            }
            /// 會有兩次
            /// 第一次讀完檔案會再執行javascript, 在local用來認證健保卡, 沒過就不會有第二次
            /// 如果認證OK, 會再透過javascript下載個案雲端資料, 觸發第二次
            /// 這段程式的目的:
            /// 1. 取得身分證字號
            /// 2. 讀取有哪些tab

            // 20210719: mark this line to simplify logging
            // log.Info($"Entered F_LoadCompleted");

            HTMLDocument d = (HTMLDocument)g.Document;
            // 確定身分證字號
            string strUID = MakeSure_UID(d.getElementById("ContentPlaceHolder1_lbluserID").innerText);

            // if (strUID = string.Empty) 離開
            if (strUID == string.Empty)
            {
                tb.ShowBalloonTip("醫療系統資料庫查無此人", "請與杏翔系統連動, 或放棄操作", BalloonIcon.Warning);

                // activate hotkeys 2
                Activate_Hotkeys();
                log.Debug($"++ Exit F_LoadCompleted (2/5). NHI card inserted but no such person.");
                log.Info("===========================================================================");
                log.Info($" ");
                return;
            }
            else
            {
                /// 表示讀卡成功
                /// show balloon with built-in icon
                tb.ShowBalloonTip("讀卡成功", $"身分證號: {strUID}", BalloonIcon.Info);
                log.Info($"  Successful NHI card read, VPN id: {strUID}.");

                /// 讀卡成功後做三件事: 讀特殊註記, 讀提醒, 開始準備讀所有資料

                /// 2. 讀取提醒, 如果有的話
                ///    這是在ContentPlaceHolder1_GV
                ///    也是個table
                IHTMLElement List_NHI_lab_reminder = d?.getElementById("ContentPlaceHolder1_GV");
                if (List_NHI_lab_reminder != null)
                {
                    HtmlDocument Html_NHI_lab_reminder = new HtmlDocument();
                    Html_NHI_lab_reminder.LoadHtml(List_NHI_lab_reminder?.outerHTML);

                    // 寫入資料庫
                    foreach (HtmlNode tr in Html_NHI_lab_reminder.DocumentNode.SelectNodes("//table/tbody/tr"))
                    {
                        HtmlDocument h_ = new HtmlDocument();
                        h_.LoadHtml(tr.InnerHtml);
                        HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                        if ((tds == null) || (tds.Count == 0))
                        {
                            continue;
                        }
                        string Lab_Name = string.Empty, Last_Date = string.Empty;
                        // tds[0] 是檢查(驗)項目類別名稱
                        Lab_Name = tds[0]?.InnerText;
                        // tds[1] 是最近1次檢查日期
                        Last_Date = tds[1]?.InnerText;

                        using (Com_clDataContext dc = new Com_clDataContext())
                        {
                            var q1 = from p1 in dc.tbl_NHI_lab_reminder
                                     where (p1.uid == strUID) && (p1.lab_name == Lab_Name) && (p1.last_date == Last_Date)
                                     select p1;
                            if (q1.Count() == 0)
                            {
                                tbl_NHI_lab_reminder newReminder = new tbl_NHI_lab_reminder()
                                {
                                    uid       = strUID,
                                    QDATE     = DateTime.Now,
                                    lab_name  = Lab_Name,
                                    last_date = Last_Date
                                };
                                dc.tbl_NHI_lab_reminder.InsertOnSubmit(newReminder);
                                dc.SubmitChanges();
                            }
                        };
                    }
                }

                /// 準備: 初始化, 欄位基礎資料/位置, 可在windows生成時就完成

                #region 準備 - 製造QueueOperation

                // Initialization
                QueueOperation?.Clear();
                ListRetrieved?.Clear();
                current_page = total_pages = 0;

                log.Info($"  start reading Operation(s).");
                // 讀取所有要讀的tab, 這些資料位於"ContentPlaceHolder1_tab"
                // IHTMLElement 無法轉型為 HTMLDocument
                // 20200429 tested successful
                IHTMLElement List_under_investigation = d?.getElementById("ContentPlaceHolder1_tab");
                // li 之下就是 a
                List <string> balloonstring = new List <string>();
                string        BalloonTip    = string.Empty;
                foreach (IHTMLElement hTML in List_under_investigation?.all)
                {
                    if (tab_id_wanted.Contains(hTML.id))
                    {
                        // 僅將要讀入的排入, 並沒有真的讀取資料
                        VPN_Operation vOP = VPN_Dictionary.Making_new_operation(hTML.id, strUID, DateTime.Now);
                        QueueOperation.Enqueue(vOP);
                        log.Info($"    讀入operation: {vOP.Short_Name}, [{strUID}]");
                        balloonstring.Add(vOP.Short_Name);
                    }
                }

                for (int i = 0; i < balloonstring.Count; i++)
                {
                    if (i == 0)
                    {
                        BalloonTip = balloonstring[i];
                    }
                    else if ((i % 3) == 0)
                    {
                        BalloonTip += $";\r\n{balloonstring[i]}";
                    }
                    else
                    {
                        BalloonTip += $"; {balloonstring[i]}";
                    }
                }
                log.Info($"  end of Reading Operation(s), 共{QueueOperation?.Count}個Operation(s).");

                #endregion 準備 - 製造QueueOperation

                #region 執行

                if (QueueOperation.Count > 0)
                {
                    // 流程控制, fm = framemonitor

                    // 載入第一個operation
                    //log.Info($"  the first operation loaded.");
                    current_op = QueueOperation.Dequeue();
                    tb.ShowBalloonTip($"開始讀取 [{current_op.UID}]", BalloonTip, BalloonIcon.Info);

                    // 判斷第一個operation是否active, (小心起見, 其實應該不可能不active)
                    // 不active就要按鍵
                    // 要注意class這個attribute是在上一層li層, 需把它改過來
                    if (d.getElementById(current_op.TAB_ID.Replace("_a_", "_li_")).className == "active")
                    {
                        // 由於此時沒有按鍵, 因此無法觸發LoadComplete, 必須人工觸發
                        fm.FrameLoadComplete += F_Data_LoadCompleted;
                        log.Debug($"@@ Add delegate F_Data_LoadCompleted.");
                        FrameLoadCompleteEventArgs ex = new FrameLoadCompleteEventArgs()
                        {
                            Message = FrameLoadStates.DirectCall
                        };
                        log.Debug($"++ Exit F_LoadCompleted (3/5). Goto F_Data_LoadCompleted by direct call.");
                        F_Data_LoadCompleted(this, ex);
                        return;
                    }
                    else
                    {
                        // 不active反而可以用按鍵, 自動會觸發F_Data_LoadCompleted
                        fm.FrameLoadComplete += F_Data_LoadCompleted;
                        log.Debug($"@@ Add delegate F_Data_LoadCompleted.");
                        // 20210719 有時候不fire
                        Thread.Sleep(150);
                        d.getElementById(current_op.TAB_ID).click();
                        log.Info($"[Action] push TAB {current_op.TAB_ID} Button.");
                        log.Debug($"++ Exit F_LoadCompleted (4/5). Go to next tab by pushing tab button.");
                        return;
                    }
                }
                else
                {
                    // 做個紀錄
                    // 一個都沒有
                    log.Info($"  no record at all.");
                    tb.ShowBalloonTip("沒有資料", "健保資料庫裡沒有資料可讀取", BalloonIcon.Info);
                    // 製作紀錄by rd
                    tbl_Query2 q = new tbl_Query2()
                    {
                        uid         = strUID,
                        QDATE       = DateTime.Now,
                        cloudmed_N  = 0,
                        cloudlab_N  = 0,
                        schedule_N  = 0,
                        op_N        = 0,
                        dental_N    = 0,
                        allergy_N   = 0,
                        discharge_N = 0,
                        rehab_N     = 0,
                        tcm_N       = 0
                    };
                    using (Com_clDataContext dc = new Com_clDataContext())
                    {
                        dc.tbl_Query2.InsertOnSubmit(q);
                        dc.SubmitChanges();
                    };

                    // activate hotkeys 3
                    Activate_Hotkeys();
                    log.Debug($"++ Exit F_LoadCompleted (5/5). NHI inserted and verified but completey no data.");
                    log.Info("===========================================================================");
                    log.Info($" ");
                }

                #endregion 執行
            }
        }
        private static int Write_dental(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_dental. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_source = string.Empty, o_diagnosis = string.Empty, o_NHI_code = string.Empty;
            string   o_op_name = string.Empty, o_loca = string.Empty;
            int      o_amt = 0;
            DateTime o_SDATE = new DateTime(), o_EDATE = new DateTime();

            int order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 來源
                            if (td.InnerText != string.Empty)
                            {
                                o_source = MakeSure_source_3_lines(td.InnerHtml);
                            }
                            break;

                        case 1:
                            // 主診斷名稱
                            o_diagnosis = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 2:
                            // 牙醫處置代碼
                            o_NHI_code = td.InnerText;
                            break;

                        case 3:
                            // 牙醫處置名稱
                            o_op_name = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 4:
                            // 診療部位
                            o_loca = td.InnerText;
                            break;

                        case 5:
                            // 執行時間-起
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 6:
                            // 執行時間-迄
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_EDATE = d;
                            }
                            break;

                        case 7:
                            // 醫令總量
                            if (td.InnerText != string.Empty)
                            {
                                o_amt = int.Parse(td.InnerText);
                            }
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudDEN
                            where (p.uid == strUID) && (p.source == o_source) && (p.NHI_code == o_NHI_code) &&
                            (p.SDATE == o_SDATE) && (p.EDATE == o_EDATE)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudDEN newDEN = new tbl_cloudDEN()
                        {
                            uid       = strUID,
                            QDATE     = current_date,
                            source    = o_source,
                            diagnosis = o_diagnosis,
                            NHI_code  = o_NHI_code,
                            op_name   = o_op_name,
                            loca      = o_loca,
                            SDATE     = o_SDATE,
                            EDATE     = o_EDATE,
                            amt       = (byte?)o_amt
                        };

                        // 存檔

                        dc.tbl_cloudDEN.InsertOnSubmit(newDEN);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Debug($"        Exit Write_den. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        Dental of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_op_name}]");
                log.Debug($"        Exit Write_den. Current ID: {strUID}.");
                return(0);
            }
        }
        private static int Write_med(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_med. Current ID: {strUID}.");
            int count = 0, order_n = 0;

            try
            {
                Com_clDataContext dc = new Com_clDataContext();
                count = 0;
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    tbl_cloudmed_temp newCloud = new tbl_cloudmed_temp()
                    {
                        uid   = strUID,
                        QDATE = current_date
                    };

                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 項次
                            if (td.InnerText != string.Empty)
                            {
                                newCloud.item_n = short.Parse(td.InnerText);
                            }
                            break;

                        case 1:
                            newCloud.source = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 2:
                            newCloud.diagnosis = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 3:
                            newCloud.atc3 = td.InnerText;
                            break;

                        case 4:
                            newCloud.atc5 = td.InnerText;
                            break;

                        case 5:
                            newCloud.comp = td.InnerText;
                            break;

                        case 6:
                            newCloud.NHI_code = td.InnerText;
                            break;

                        case 7:
                            newCloud.drug_name = td.InnerText;
                            break;

                        case 8:
                            newCloud.dosing = td.InnerText;
                            break;

                        case 9:
                            newCloud.days = td.InnerText;
                            break;

                        case 10:
                            newCloud.amt = td.InnerText;
                            break;

                        case 11:
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                newCloud.SDATE = d;
                            }
                            break;

                        case 12:
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                newCloud.EDATE = d;
                            }
                            break;

                        case 13:
                            newCloud.o_source = td.InnerText;
                            break;
                        }
                        order_n++;
                    }
                    dc.tbl_cloudmed_temp.InsertOnSubmit(newCloud);
                    dc.SubmitChanges();
                    count++;
                }

                // 匯入大表
                try
                {
                    dc.sp_insert_tbl_cloudmed(current_date);
                }
                catch (Exception ex)
                {
                    log.Error($"        med of {strUID}, Error: {ex.Message}");
                    log.Error($"        Count: {count}; Order: {order_n}]");
                    Logging.Record_error(ex.Message);
                }
                try
                {
                    dc.sp_insert_p_cloudmed(current_date);
                }
                catch (Exception ex)
                {
                    log.Error($"        med of {strUID}, Error: {ex.Message}");
                    log.Error($"        Count: {count}; Order: {order_n}]");
                    Logging.Record_error(ex.Message);
                }
                // 這裡原本多了一次沒有try包覆的insert_p_cloudmed, 一但p_cloudmed有錯誤就沒辦法處理source
                // 處理source
                var r = (from p in dc.tbl_cloudmed_temp
                         where p.QDATE == current_date
                         select p.source).Distinct().ToList();  //this is a query
                for (int i = 0; i < r.Count(); i++)
                {
                    string[] s = r[i].Split(' ');
                    // source_id s(2).substring(1)
                    // class s(1).substring(1)
                    // source_name s(0)
                    var qq = from pp in dc.p_source
                             where pp.source_id == s[2].Substring(1)
                             select pp;
                    if (qq.Count() == 0)
                    {
                        p_source so = new p_source()
                        {
                            source_id   = s[2].Substring(1),
                            @class      = s[1].Substring(1),
                            source_name = s[0]
                        };
                        dc.p_source.InsertOnSubmit(so);
                        dc.SubmitChanges();
                    }
                }
                log.Debug($"        Exit Write_med. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        med of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}]");
                log.Debug($"        Exit Write_med. Current ID: {strUID}.");
                return(0);
            }
        }
        private static int Write_lab(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_lab. Current ID: {strUID}.");
            int count = 0, order_n = 0;
            Com_clDataContext dc = new Com_clDataContext();

            count = 0;
            // 寫入資料庫
            foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
            {
                HtmlDocument h_ = new HtmlDocument();
                h_.LoadHtml(tr.InnerHtml);
                HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                if ((tds == null) || (tds.Count == 0))
                {
                    continue;
                }
                tbl_cloudlab_temp newLab = new tbl_cloudlab_temp()
                {
                    uid   = strUID,
                    QDATE = current_date
                };

                order_n = 0;
                foreach (HtmlNode td in tds)
                {
                    try
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 項次
                            if (td.InnerText != string.Empty)
                            {
                                newLab.item_n = short.Parse(td.InnerText);
                            }
                            break;

                        case 1:
                            newLab.source = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 2:
                            newLab.dep = td.InnerText;
                            break;

                        case 3:
                            newLab.diagnosis = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 4:
                            newLab.@class = td.InnerText;
                            break;

                        case 5:
                            newLab.order_name = td.InnerText;
                            break;

                        case 6:
                            newLab.lab_item = td.InnerText;
                            break;

                        case 7:
                            newLab.result = td.InnerText;
                            break;

                        case 8:
                            newLab.range = td.InnerText;
                            break;

                        case 9:
                            // 原本空白日期會有錯誤, 一有錯誤就直接跳到最外層try-catch,該條之後整頁都沒有讀入, 20200514修正
                            // 加入if, 排除空白日期造成的錯誤, 把try 縮小範圍, 有錯不至於放棄整頁
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                newLab.SDATE = d;
                            }
                            break;

                        case 10:
                            newLab.NHI_code = td.InnerText;
                            break;
                        }
                        order_n++;
                    }
                    catch (Exception ex)
                    {
                        log.Error($"        lab of {strUID}, Error: {ex.Message}");
                        log.Error($"        Count: {count}; Order: {order_n}]");
                    }
                }
                dc.tbl_cloudlab_temp.InsertOnSubmit(newLab);
                dc.SubmitChanges();
                count++;
            }
            // 匯入大表
            try
            {
                dc.sp_insert_tbl_cloudlab(current_date);
            }
            catch (Exception ex)
            {
                log.Error($"        lab of {strUID}, Error: {ex.Message}");
                log.Error($"        Error with writing into big table");
                Logging.Record_error(ex.Message);
            }
            try
            {
                dc.sp_insert_p_cloudlab(current_date);
            }
            catch (Exception ex)
            {
                log.Error($"        lab of {strUID}, Error: {ex.Message}");
                log.Error($"        Error with writing into p_cloudlab.");
                Logging.Record_error(ex.Message);
            }
            // 處理source
            var r = (from p in dc.tbl_cloudlab_temp
                     where p.QDATE == current_date
                     select p.source).Distinct().ToList(); // this is a query

            for (int i = 0; i < r.Count(); i++)
            {
                string[] s  = r[i].Split(' ');
                var      qq = from pp in dc.p_source
                              where pp.source_id == s[2].Substring(1)
                              select pp;
                if (qq.Count() == 0)
                {
                    p_source so = new p_source()
                    {
                        source_id   = s[2].Substring(1),
                        @class      = s[1].Substring(1),
                        source_name = s[0]
                    };
                    dc.p_source.InsertOnSubmit(so);
                    dc.SubmitChanges();
                }
            }
            log.Debug($"        Exit Write_lab. Current ID: {strUID}.");
            return(count);
        }
        private static int Write_dis(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_dis. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_source = string.Empty, o_dep = string.Empty, o_diagnosis = string.Empty;
            DateTime o_SDATE = new DateTime(), o_EDATE = new DateTime();

            int order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 來源
                            if (td.InnerText != string.Empty)
                            {
                                o_source = MakeSure_source_2_lines(td.InnerHtml);
                            }
                            break;

                        case 1:
                            // 出院科別
                            o_dep = td.InnerText;
                            break;

                        case 2:
                            // 出院診斷
                            o_diagnosis = td.InnerText;
                            break;

                        case 3:
                            // 住院日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 4:
                            // 出院日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_EDATE = d;
                            }
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudDIS
                            where (p.uid == strUID) && (p.source == o_source) &&
                            (p.SDATE == o_SDATE) && (p.EDATE == o_EDATE)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudDIS newDIS = new tbl_cloudDIS()
                        {
                            uid       = strUID,
                            QDATE     = current_date,
                            source    = o_source,
                            dep       = o_dep,
                            diagnosis = o_diagnosis,
                            SDATE     = o_SDATE,
                            EDATE     = o_EDATE
                        };

                        // 存檔

                        dc.tbl_cloudDIS.InsertOnSubmit(newDIS);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Debug($"        Exit Write_dis. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        Discharge of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_diagnosis}]");
                log.Debug($"        Exit Write_dis. Current ID: {strUID}.");
                return(0);
            }
        }
        private static int Write_tcm_gr(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_tcm_gr. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_source = string.Empty, o_diagnosis = string.Empty, o_chronic = string.Empty, o_serial = string.Empty;
            int      o_days = 0;
            DateTime o_SDATE = new DateTime(), o_EDATE = new DateTime();

            int order_n = 0;

            // 寫入資料庫
            foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
            {
                HtmlDocument h_ = new HtmlDocument();
                h_.LoadHtml(tr.InnerHtml);
                HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                if ((tds == null) || (tds.Count == 0))
                {
                    continue;
                }
                order_n = 0;
                foreach (HtmlNode td in tds)
                {
                    try
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 來源
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                o_source = MakeSure_source_3_lines(td.InnerHtml);
                            }
                            break;

                        case 1:
                            // 主診斷
                            o_diagnosis = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 2:
                            // 給藥日數
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                o_days = int.Parse(td.InnerText);
                            }
                            break;

                        case 3:
                            // 慢連箋
                            o_chronic = td.InnerText;
                            break;

                        case 4:
                            // 就醫(調劑)日期
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 5:
                            // 慢連箋領藥日
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_EDATE = d;
                            }
                            break;

                        case 6:
                            // 就醫序號
                            o_serial = td.InnerText;
                            break;
                        }
                        order_n++;
                    }
                    catch (Exception ex)
                    {
                        log.Error($"        TCM_GR of {strUID}, Error: {ex.Message}");
                        log.Error($"        Count: {count}; Order: {order_n}, [{o_diagnosis}]");
                    }
                }
                var q = from p in dc.tbl_cloudTCM_G
                        where (p.uid == strUID) && (p.SDATE == o_SDATE) && (p.serial == o_serial)
                        select p;
                if (q.Count() == 0)
                {
                    tbl_cloudTCM_G newTCMG = new tbl_cloudTCM_G()
                    {
                        uid       = strUID,
                        QDATE     = current_date,
                        source    = o_source,
                        diagnosis = o_diagnosis,
                        days      = (byte?)o_days,
                        chronic   = o_chronic,
                        SDATE     = o_SDATE,
                        EDATE     = o_EDATE,
                        serial    = o_serial
                    };

                    // 存檔

                    dc.tbl_cloudTCM_G.InsertOnSubmit(newTCMG);
                    dc.SubmitChanges();
                }
                count++;
            }
            log.Debug($"        Exit Write_tcm_gr. Current ID: {strUID}.");
            return(count);
        }
        private static int Write_tcm_de(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_tcm_de. Current ID: {strUID}.");
            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_diagnosis = string.Empty, o_NHI_code = string.Empty, o_complex = string.Empty;
            string   o_base = string.Empty, o_effect = string.Empty, o_dosing = string.Empty;
            string   o_type = string.Empty, o_serial = string.Empty;
            int      o_days = 0;
            float    o_amt = 0;
            DateTime o_SDATE = new DateTime(), o_EDATE = new DateTime();

            int order_n = 0;

            // 寫入資料庫
            foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
            {
                HtmlDocument h_ = new HtmlDocument();
                h_.LoadHtml(tr.InnerHtml);
                HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                if ((tds == null) || (tds.Count == 0))
                {
                    continue;
                }
                order_n = 0;
                foreach (HtmlNode td in tds)
                {
                    try
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 主診斷名稱
                            o_diagnosis = td.InnerHtml.Replace("<br>", " ");
                            break;

                        case 1:
                            // 藥品代碼
                            o_NHI_code = td.InnerText;
                            break;

                        case 2:
                            // 複方註記
                            o_complex = td.InnerText;
                            break;

                        case 3:
                            // 基準方名
                            o_base = td.InnerText;
                            break;

                        case 4:
                            // 效能名稱
                            o_effect = td.InnerText;
                            break;

                        case 5:
                            // 用法用量
                            o_dosing = td.InnerText;
                            break;

                        case 6:
                            // 給藥日數
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                o_days = int.Parse(td.InnerText);
                            }
                            break;

                        case 7:
                            // 濟型
                            o_type = td.InnerText;
                            break;

                        case 8:
                            // 給藥總量
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                o_amt = float.Parse(td.InnerText);
                            }
                            break;

                        case 9:
                            // 就醫(調劑)日期
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 10:
                            // 慢連箋領藥日
                            if (!string.IsNullOrEmpty(td.InnerText))
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_EDATE = d;
                            }
                            break;

                        case 11:
                            // 就醫序號
                            o_serial = td.InnerText;
                            break;
                        }
                        order_n++;
                    }
                    catch (Exception ex)
                    {
                        log.Error($"        TCM_DE of {strUID}, Error: {ex.Message}");
                        log.Error($"        Count: {count}; Order: {order_n}, [{o_diagnosis}]");
                    }
                }
                // 20200515 有時候amt會有小數點, 直接轉換就會報錯, 因此先轉換成float, 再換回整數, 就可以通過

                var q = from p in dc.tbl_cloudTCM_D
                        where (p.uid == strUID) && (p.NHI_code == o_NHI_code) &&
                        (p.SDATE == o_SDATE) && (p.serial == o_serial)
                        select p;
                if (q.Count() == 0)
                {
                    tbl_cloudTCM_D newTCMD = new tbl_cloudTCM_D()
                    {
                        uid       = strUID,
                        QDATE     = current_date,
                        diagnosis = o_diagnosis,
                        NHI_code  = o_NHI_code,
                        complex   = o_complex,
                        @base     = o_base,
                        effect    = o_effect,
                        dosing    = o_dosing,
                        days      = (byte?)o_days,
                        type      = o_type,
                        amt       = (short?)o_amt,
                        SDATE     = o_SDATE,
                        EDATE     = o_EDATE,
                        serial    = o_serial
                    };

                    // 存檔

                    dc.tbl_cloudTCM_D.InsertOnSubmit(newTCMD);
                    dc.SubmitChanges();
                }
                count++;
            }
            log.Debug($"        Exit Write_tcm_de. Current ID: {strUID}.");
            return(count);
        }
        private static int Write_all(HtmlDocument html, List <int> header_order, string strUID, DateTime current_date)
        {
            log.Debug($"        Enter Write_all. Current ID: {strUID}.");

            Com_clDataContext dc = new Com_clDataContext();
            int      count = 0;
            string   o_source = string.Empty, o_remark = string.Empty, o_drug_name = string.Empty;
            DateTime o_SDATE = new DateTime();
            int      order_n = 0;

            try
            {
                // 寫入資料庫
                foreach (HtmlNode tr in html.DocumentNode.SelectNodes("//table/tbody/tr"))
                {
                    HtmlDocument h_ = new HtmlDocument();
                    h_.LoadHtml(tr.InnerHtml);
                    HtmlNodeCollection tds = h_.DocumentNode.SelectNodes("//td");

                    if ((tds == null) || (tds.Count == 0))
                    {
                        continue;
                    }
                    order_n = 0;
                    foreach (HtmlNode td in tds)
                    {
                        switch (header_order[order_n])
                        {
                        case 0:
                            // 上傳日期
                            if (td.InnerText != string.Empty)
                            {
                                string[] temp_d = td.InnerText.Split('/');
                                DateTime.TryParse($"{int.Parse(temp_d[0]) + 1911}/{temp_d[1]}/{temp_d[2]}", out DateTime d);
                                o_SDATE = d;
                            }
                            break;

                        case 1:
                            // 醫療院所
                            // 20200504: 發現是兩行的不是三行的
                            // 來源, 與別人有所不同, 只有兩行
                            if (td.InnerText != string.Empty)
                            {
                                o_source = MakeSure_source_2_lines(td.InnerHtml);
                            }
                            break;

                        case 2:
                            // 上傳註記
                            o_remark = td.InnerText;
                            break;

                        case 3:
                            // 過敏藥物
                            o_drug_name = td.InnerText;
                            break;
                        }
                        order_n++;
                    }

                    var q = from p in dc.tbl_cloudALL
                            where (p.uid == strUID) && (p.source == o_source) && (p.SDATE == o_SDATE) &&
                            (p.remark == o_remark) && (p.drug_name == o_drug_name)
                            select p;
                    if (q.Count() == 0)
                    {
                        tbl_cloudALL newALL = new tbl_cloudALL()
                        {
                            uid       = strUID,
                            QDATE     = current_date,
                            source    = o_source,
                            SDATE     = o_SDATE,
                            remark    = o_remark,
                            drug_name = o_drug_name
                        };
                        // 存檔

                        dc.tbl_cloudALL.InsertOnSubmit(newALL);
                        dc.SubmitChanges();
                    }
                    count++;
                }
                log.Debug($"        Exit Write_all. Current ID: {strUID}.");
                return(count);
            }
            catch (Exception ex)
            {
                log.Error($"        Allergy of {strUID}, Error: {ex.Message}");
                log.Error($"        Count: {count}; Order: {order_n}, [{o_drug_name}]");
                log.Debug($"        Exit Write_all. Current ID: {strUID}.");
                return(-1);
            }
        }