public TrainRepository(DB dc)
 {
     _dc       = dc;
     _rootRepo = RepositoryFactory.CreateRootRepo();
     _pwfRepo  = RepositoryFactory.CreateProcessWorkflowRepo();
     _handler  = RepositoryFactory.CreateAutoInsert();
     IsConnect = _dc.TestConnection();
 }
        /// <summary>
        /// 上呈簽核SQL(判斷是否還有上層需要簽核)
        /// </summary>
        /// <param name="mainModel"></param>
        /// <param name="currentSignerID"></param>
        /// <returns></returns>
        public List <MultiConditions> GetNextSQLDML(ProcessWorkflowViewModel mainModel, string currentSignerID)
        {
            var result = new List <MultiConditions>();

            //取出指定明細
            //var detailModel = mainModel.WorkflowDetailList.Single(row => currentSignerID.Equals(row.ChiefID_FK));

            #region 0020 會有多筆資料 不該用Single

            var detailModel = mainModel.WorkflowDetailList.FirstOrDefault(row => currentSignerID.Equals(row.ChiefID_FK));

            #endregion 0020 會有多筆資料 不該用Single

            //更新時間
            mainModel.ModifyDate   = DateTime.Now;
            detailModel.ModifyDate = mainModel.ModifyDate;
            mainModel.Creator      = null;
            mainModel.CreateDate   = new DateTime();

            //更新修改人員
            mainModel.Modifier = detailModel.Modifier;

            //找尋上層簽核部門資料
            var upperDeptData = FindUpperDeptData(mainModel.CurrentSignLevelDeptID_FK, currentSignerID);
            var isFollowRule  = IsFollowFlowRule(mainModel.RuleID_FK, upperDeptData.Values.Single(), mainModel.Remainder);

            var        sql        = String.Empty;
            Conditions conditions = null;
            //確認當前部門是否符合上呈簽核規則
            if (isFollowRule)
            {
                //符合上呈簽核規則 卻沒有上層簽核 => 發生Exception
                if (upperDeptData == null || upperDeptData.Count == 0)
                {
                    throw new MissingMemberException(String.Format("簽核發生符合規則卻找不到上層簽核部門的例外!"));
                }

                //符合上呈簽核規則 且 有上層簽核

                //確認是否有額外的會簽人員
                var otherChiefCount = GetWorkflowDataDetail(mainModel.SignDocID).Count;
                if (otherChiefCount > 1)
                {
                    //刪除不是當前簽核主管的會簽人員
                    sql =
                        @"Delete SignForm_Detail Where SignDocID_FK = @SignDocID_FK and ChiefID_FK <> @OrgSupervisorID ";
                    conditions = new Conditions();
                    conditions.Add("@SignDocID_FK", detailModel.SignDocID_FK);
                    conditions.Add("@OrgSupervisorID", currentSignerID);
                    result.Add(new MultiConditions()
                    {
                        { sql, conditions }
                    });
                }

                //更改主表簽核部門
                mainModel.CurrentSignLevelDeptID_FK = upperDeptData.Values.Single();
                sql =
                    @"UPDATE signform_main
                SET currentsignleveldeptid_fk = @CurrentSignLevelDeptID_FK, remainder = @Remainder, modifier = @Modifier, modifydate = @ModifyDate WHERE  signdocid = @SignDocID ";
                conditions = new Conditions();
                conditions.Add("@CurrentSignLevelDeptID_FK", mainModel.CurrentSignLevelDeptID_FK);
                conditions.Add("@Remainder", --mainModel.Remainder);
                conditions.Add("@Modifier", mainModel.Modifier);
                conditions.Add("@ModifyDate", mainModel.ModifyDate);
                conditions.Add("@SignDocID", mainModel.SignDocID);
                result.Add(new MultiConditions()
                {
                    { sql, conditions }
                });

                //更改子表簽核人員
                detailModel.ChiefID_FK = upperDeptData.Keys.Single();
                detailModel.Status     = 2;
                detailModel.Remark     = String.Empty;
                sql =
                    @"UPDATE signform_detail
                SET chiefid_fk = @ChiefID_FK, status = @Status, remark = @Remark,modifier = @Modifier, modifydate = @ModifyDate WHERE  signdocid_fk = @SignDocID AND chiefid_fk = @OrgSupervisorID ";
                conditions = new Conditions();
                conditions.Add("@ChiefID_FK", detailModel.ChiefID_FK);
                conditions.Add("@Status", detailModel.Status);
                conditions.Add("@Remark", detailModel.Remark);
                conditions.Add("@SignDocID", detailModel.SignDocID_FK);
                conditions.Add("@OrgSupervisorID", currentSignerID);
                conditions.Add("@Modifier", detailModel.Modifier);
                conditions.Add("@ModifyDate", detailModel.ModifyDate);
                result.Add(new MultiConditions()
                {
                    { sql, conditions }
                });
            }
            else
            {
                //不符合規則,表示已經到終點

                //指派當前簽核人員
                detailModel.ChiefID_FK = currentSignerID;

                //更改主表狀態 為結案
                sql =
                    @"Update SignForm_Main Set FinalStatus = '6', remainder = @Remainder, modifier = @Modifier, modifydate = @ModifyDate Where SignDocID = @SignDocID ";
                mainModel.FinalStatus = 6;
                conditions            = new Conditions();
                conditions.Add("@Remainder", --mainModel.Remainder);
                conditions.Add("@SignDocID", mainModel.SignDocID);
                conditions.Add("@Modifier", mainModel.Modifier);
                conditions.Add("@ModifyDate", mainModel.ModifyDate);
                result.Add(new MultiConditions()
                {
                    { sql, conditions }
                });

                //更改子表狀態
                sql =
                    @"Update SignForm_Detail Set Status = @Status, modifier = @Modifier, modifydate = @ModifyDate Where SignDocID_FK = @SignDocID_FK ";
                conditions         = new Conditions();
                detailModel.Status = 6;
                detailModel.Remark = String.Empty;
                conditions.Add("@Status", detailModel.Status);
                conditions.Add("@SignDocID_FK", detailModel.SignDocID_FK);
                conditions.Add("@Modifier", detailModel.Modifier);
                conditions.Add("@ModifyDate", detailModel.ModifyDate);
                result.Add(new MultiConditions()
                {
                    { sql, conditions }
                });

                //轉交 AutoInsertHandler

                #region 決定將寫入志元與否

                AutoInsertHandler autoInsert = RepositoryFactory.CreateAutoInsert(mainModel.SignDocID);

                #endregion 決定將寫入志元與否

                var autoInsertDML = autoInsert.GetDML();
                if (autoInsertDML != null)
                {
                    //windows server2003 DTC 設定 交易管理通訊雙方必須設定為 不需驗證
                    result.Add(autoInsert.GetXACTABORTON());
                    result.AddRange(autoInsertDML);
                }
            }

            //log
            conditions = new Conditions()
            {
                { "@SignDocID_FK", mainModel != null ? mainModel.SignDocID : (string)null },
                { "@FormID_FK", mainModel != null?mainModel.FormID_FK.ToString() : (string)null },
                { "@EmployeeID_FK", mainModel != null ? mainModel.EmployeeID_FK : (string)null },
                { "@SendDate", mainModel != null?mainModel.SendDate.Value.FormatDatetime() : (string)null },
                { "@CurrentSignLevelDeptID_FK", mainModel != null ? mainModel.CurrentSignLevelDeptID_FK : (string)null },
                { "@FinalStatus", mainModel != null?mainModel.FinalStatus.ToString() : (string)null },
                { "@Remainder", mainModel != null?mainModel.Remainder.ToString() : (string)null },
                { "@Creator_Main", mainModel != null ? mainModel.Creator : (string)null },
                { "@CreateDate_Main", mainModel != null && mainModel.CreateDate != DateTime.MinValue ? mainModel.CreateDate.FormatDatetime() : (string)null },
                { "@Modifier_Main", mainModel != null ? mainModel.Modifier : (string)null },
                { "@ModifyDate_Main", mainModel != null && mainModel.ModifyDate != DateTime.MinValue ? mainModel.ModifyDate.Value.FormatDatetime() :(string)null },
                { "@DetailSignDocID_FK", detailModel != null ? detailModel.SignDocID_FK : (string)null },
                { "@ChiefID_FK", detailModel != null ? detailModel.ChiefID_FK : (string)null },
                { "@Remark", detailModel != null ? detailModel.Remark : (string)null },
                { "@Status", detailModel != null?detailModel.Status.ToString() : (string)null },
                { "@Creator_Detail", detailModel != null ? detailModel.Creator : (string)null },
                { "@CreateDate_Detail", detailModel != null && detailModel.CreateDate != DateTime.MinValue ? detailModel.CreateDate.FormatDatetime() : (string)null },
                { "@Modifier_Detail", detailModel != null ? detailModel.Modifier : (string)null },
                { "@ModifyDate_Detail", detailModel != null && detailModel.ModifyDate != DateTime.MinValue ? detailModel.ModifyDate.Value.FormatDatetime(): (string)null },
                { "@LogDatetime", DateTime.Now },
            };

            var log = _dc.ConstructInsertDML("SignForm_Log", conditions);
            result.Add(new MultiConditions()
            {
                { log, conditions }
            });

            return(result);
        }
        protected void SaveBtn_Click(object sender, EventArgs e)
        {
            //btn處理
            ViewUtils.ButtonOff(SaveBtn, CoverBtn);


            //存檔
            var responseMessage = "";
            var successRdUrl    = String.Empty;

            try
            {
                var signDocID = Request["SignDocID"];
                _handler = RepositoryFactory.CreateAutoInsert(signDocID);

                var payRange = _handler.ParsePayRange(PayRange.SelectedValue);
                var columns  = OvertimeSettingGridView.Columns.Cast <DataControlField>();
                //var paggerParms = WebUtils.ParseQueryString<PaggerParms>(Page.Request);
                //var manageListParms = WebUtils.ParseQueryString<ManageListParms>(Page.Request);
                //var pagination = _repo.GetPagination(manageListParms, paggerParms);
                //ViewUtils.SetGridView(OvertimeSettingGridView, pagination.Data);
                var rows = OvertimeSettingGridView.Rows.Cast <GridViewRow>();

                List <MultiConditions> dmlList = rows.Select(row =>
                {
                    var controls = row.Controls.Cast <Control>();
                    var data     = controls.Zip(columns, (control, column) =>
                    {
                        var value = ((Label)control.FindControl(column.HeaderText)).Text;
                        return(new KeyValuePair <string, object>(column.HeaderText, value));
                    }).ToDictionary(k => k.Key, v => v.Value);

                    // ViewModelMapping
                    var model = WebUtils.ViewModelMapping <OvertimeViewModel>(data);

                    // check employee is settle account or not
                    if (_handler.IsSettledAccounts(model.EmployeeID_FK, payRange))
                    {
                        throw new Exception(String.Format("員工{0}已經結過{1}月薪資", model.EmployeeID_FK, payRange.Date.ToString("yyyyMM")));
                    }
                    // get dml
                    return(_handler.GetOvertimeDML(model, payRange));
                }).ToList();

                var workFlowRepo = RepositoryFactory.CreateProcessWorkflowRepo();
                //insert index:0 XACT_ABORT ON
                dmlList.Insert(0, _handler.GetXACTABORTON());
                //update autoinsert true
                dmlList.Add(_repo.GetAutoInserDML(signDocID, User.Identity.Name));
                //insert into db
                //workFlowRepo.ExecuteSQL(dmlList);

                responseMessage = "成功寫入SmartMan".ToAlertAndCloseAndRedirect(@"OvertimeReport.aspx?finalStatus=6&StartDateTime=" + Session["StartDateTime"] + "&EndDateTime=" + Session["EndDateTime"] + "&orderField=AutoInsert&descending=False");
            }
            catch (Exception ex)
            {
                responseMessage = String.Concat("寫入SmartMan失敗!\r\n錯誤訊息: ", ex.Message).ToAlertFormat();
                ViewUtils.ShowRefreshBtn(CoverBtn, RefreshBtn);
            }
            finally
            {
                Response.Write(responseMessage);
            }
        }