//建立後續叫修單
        public String[] FollowUpCreate(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[4];

            ret[0] = "false";
            ret[1] = "";
            ret[2] = "";    //area
            ret[3] = "";    //auto assign user name
            int  num = 0, childCaseID = 0;                        
            
            //String groupSW = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventViewModel.CustomerRef).Select(x => x.GroupSW).First();

            if (wBSEventViewModel.ExpectArriveDTStr == null)
                wBSEventViewModel.ExpectArriveDTStr = "19000101 00:01";
            if (wBSEventViewModel.ExpectFinishDTStr == null)
                wBSEventViewModel.ExpectFinishDTStr = "19000101 00:01";
            wBSEventViewModel.ExpectArriveDT = DateTime.ParseExact(wBSEventViewModel.ExpectArriveDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            wBSEventViewModel.ExpectFinishDT = DateTime.ParseExact(wBSEventViewModel.ExpectFinishDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);

            try
            {
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
                WBSEventC oldEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);

                if (oldEventC.EventStatus == 49)
                {
                    oldEventC.EventStatus = 50;
                    oldEventC.ModifyDateTime = DateTime.Now;
                    oldEventC.ModifyUserID = wBSEventViewModel.CreateUserID;
                }

                wBSEventM.CaseMStatus = "5";    //5為部分子單已解決
                num = db.WBSEventC.AsEnumerable().Select(x => x.Num).DefaultIfEmpty(0).Max(x => x) + 1;
                childCaseID = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == wBSEventM.CaseID).Select(x => x.ChildCaseID).DefaultIfEmpty(0).Max(x => x) + 1;
                ret[2] = GetCustomerArea(wBSEventM.CustomerRef);

                WBSEventC wBSEventC = new WBSEventC();
                ret[1] = num.ToString();
                wBSEventC.Num = num;
                wBSEventC.MomCaseID = oldEventC.MomCaseID;
                wBSEventC.ChildCaseID = childCaseID;
                wBSEventViewModel.WBSCaseNumberC = (wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString();
                wBSEventC.EventClass = wBSEventViewModel.EventClass;
                wBSEventC.ProductClass = oldEventC.ProductClass;
                wBSEventC.ItemClass = oldEventC.ItemClass;
                wBSEventC.QuestionClass = oldEventC.QuestionClass;
                wBSEventC.QuestionGrade = oldEventC.QuestionGrade;
                wBSEventC.QuestionServiceHours = oldEventC.QuestionServiceHours;
                wBSEventC.QuestionDescription = wBSEventViewModel.QuestionDescription;
                wBSEventC.QuestionCreateUserID = wBSEventViewModel.QuestionCreateUserID;
                wBSEventC.QuestionCreateDateTime = DateTime.Now;
                wBSEventC.ExpectArriveDateTime = wBSEventViewModel.ExpectArriveDT;
                wBSEventC.ExpectFinishDateTime = wBSEventViewModel.ExpectFinishDT;
                wBSEventC.ExpectArriveSW = wBSEventViewModel.ExpectArriveSW;
                //wBSEventC.DeleteMarkSW = wBSEventViewModel.DeleteMarkSW;
                //wBSEventC.DeleteReason = wBSEventViewModel.DeleteReason;
                //wBSEventC.DeleteMarkUserID = wBSEventViewModel.DeleteMarkUserID;
                //wBSEventC.DeleteMarkDateTime = wBSEventViewModel.DeleteMarkDT;
                wBSEventC.CreateDateTime = DateTime.Now;
                wBSEventC.CreateUserID = wBSEventViewModel.CreateUserID;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.CreateUserID;
                
                wBSEventC.SugProvideSpareMach = "F";
                wBSEventC.SugRetrieveSpareMach = "F";
                wBSEventC.SugRetrieveUserMach = "F";
                wBSEventC.SugReturnUserMach = "F";
                wBSEventC.SugMachMemo = (wBSEventViewModel.SugMachMemo == null) ? "" : wBSEventViewModel.SugMachMemo;   //建議備機說明
                wBSEventC.EventStatus = 11; //11為問題已開立

                if (wBSEventViewModel.ExpectArriveSW == "4")//自派新單
                {
                    String subAreaID = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventM.CustomerRef).Select(x => x.RegionID).First();
                    String AreaID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.AreaID).First();
                    int rID = 0;
                    if (db.SubArea.AsEnumerable().Where(x => x.AreaID == AreaID && x.ResponsibleClass.UserID == wBSEventViewModel.CreateUserID).Count() > 0)
                    {
                        rID = db.SubArea.AsEnumerable().Where(x => x.AreaID == AreaID && x.ResponsibleClass.UserID == wBSEventViewModel.CreateUserID).Select(x => x.ResponsibleClass.ID).First();
                    }
                    else if (db.ResponsibleClass.AsEnumerable().Where(x => x.UserID == wBSEventViewModel.CreateUserID).Count() > 0)
                    {
                        rID = db.ResponsibleClass.AsEnumerable().Where(x => x.UserID == wBSEventViewModel.CreateUserID).Select(x => x.ID).First();
                    }
                    else
                    {
                        rID = oldEventC.ResponsibleID.Value;
                    }                    
                    wBSEventC.ResponsibleID = rID;

                    wBSEventC.AssignCreateDT = DateTime.Now;
                    wBSEventC.AssignCreateUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignDT = DateTime.Now;
                    wBSEventC.AssignUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignModifyDT = DateTime.Now;
                    wBSEventC.AssignModifyUserID = wBSEventViewModel.CreateUserID;

                    wBSEventC.RespondSW = "Y";
                    wBSEventC.RespondDT = DateTime.Now;
                    wBSEventC.RespondReason = "";
                    wBSEventC.ScheduleStartDT = wBSEventViewModel.ExpectArriveDT;
                    wBSEventC.ScheduleEndDT = wBSEventViewModel.ExpectFinishDT;
                    wBSEventC.ScheduleServiceHours = wBSEventC.QuestionServiceHours;
                    
                    wBSEventC.EventStatus = 31; //31任務已接受已排程

                    String ExpectArriveSW, EventStatusStr;
                    ExpectArriveSW = "自派新單";
                   

                    String ExpectArriveDTStr = wBSEventC.ExpectArriveDateTime.Value.ToString("yyyy/MM/dd HH:mm");
                    if (wBSEventC.ExpectArriveSW == "0")
                        ExpectArriveDTStr = "自行約定";

                    EventStatusStr = "已接受已排程";


                    String UserID = wBSEventViewModel.CreateUserID;
                    String UserName = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.UserData2.UserName).First();

                    String url = "http://" + wBSEventViewModel.Url + "/Mobile/MobileCaseDetail?type=2&&mid=" + wBSEventC.MomCaseID + "&&cid=" + wBSEventC.Num;
                    String title = "";      //[燈號]-[推播事件說明]
                    String content = "";    //[被推播人員姓名]您好:案件-[客戶簡稱]-[到達約定選擇]:[應到達時間],[事件說明],請您盡速處理。
                    title = "綠燈-執行人已接受已排程";
                    content = UserName + "您好:案件-" + wBSEventM.Customer1.ShortName + "-" + ExpectArriveSW + ":" + ExpectArriveDTStr + "," + EventStatusStr + ",請您盡速處理。";

                    //messageRepository.AddMsgbyUser(UserID, title, content, url);
                }
                else if (wBSEventViewModel.ResponsibleID != "" && wBSEventViewModel.ResponsibleID != null)
                {
                    //String subAreaID = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventM.CustomerRef).Select(x => x.RegionID).First();
                    //String AreaID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.AreaID).First();
                    //int rID = 0;

                    //if (db.SystemSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AutoAssign == true).Count() > 0) //事件個別指定
                    //{
                    //    if (db.SystemSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AutoAssignUserType == 2).Count() > 0)
                    //        rID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.ResponsibleID).First();
                    //    else
                    //    {
                    //        if (db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                    //        else if (db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();                             
                    //    }
                    //}
                    //else //系統預設
                    //{
                    //    if (db.SystemSetting.Where(x => x.isSysDefault == true && x.AutoAssignUserType == 2).Count() > 0)
                    //        rID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.ResponsibleID).First();
                    //    else
                    //    {
                    //        if (db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                    //        else if (db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();                             
                    //    }

                    //}
                    int rID = int.Parse(wBSEventViewModel.ResponsibleID);
                    wBSEventC.ResponsibleID = rID;

                    wBSEventC.AssignCreateDT = DateTime.Now;
                    wBSEventC.AssignCreateUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignDT = DateTime.Now;
                    wBSEventC.AssignUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignModifyDT = DateTime.Now;
                    wBSEventC.AssignModifyUserID = wBSEventViewModel.CreateUserID;

                    wBSEventC.RespondSW = "Y";
                    wBSEventC.RespondDT = DateTime.Now;
                    wBSEventC.RespondReason = "";
                    //wBSEventC.ScheduleStartDT = wBSEventViewModel.ExpectArriveDT;
                    //wBSEventC.ScheduleEndDT = wBSEventViewModel.ExpectFinishDT;
                    //wBSEventC.ScheduleServiceHours = wBSEventC.QuestionServiceHours;

                    wBSEventC.EventStatus = 30; //30任務已接受未排程

                    String ExpectArriveSW, EventStatusStr;
                    if (wBSEventC.ExpectArriveSW == "0")
                        ExpectArriveSW = "自行約定";
                    else if (wBSEventC.ExpectArriveSW == "1")
                        ExpectArriveSW = "合約規定";
                    else if (wBSEventC.ExpectArriveSW == "2")
                        ExpectArriveSW = "建議期望";
                    else if (wBSEventC.ExpectArriveSW == "4")
                        ExpectArriveSW = "自派新單";
                    else
                        ExpectArriveSW = "客戶指定";

                    String ExpectArriveDTStr = wBSEventC.ExpectArriveDateTime.Value.ToString("yyyy/MM/dd HH:mm");
                    if (wBSEventC.ExpectArriveSW == "0")
                        ExpectArriveDTStr = "自行約定";

                    EventStatusStr = "已接受未排程";


                    String UserID = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.UserID).First();
                    String UserName = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.UserData2.UserName).First();
                    ret[3] = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.Name).First() + "-" + UserName;

                    String url = "http://" + wBSEventViewModel.Url + "/Mobile/MobileCaseDetail?type=2&&mid=" + wBSEventC.MomCaseID + "&&cid=" + wBSEventC.Num;
                    String title = "";      //[燈號]-[推播事件說明]
                    String content = "";    //[被推播人員姓名]您好:案件-[客戶簡稱]-[到達約定選擇]:[應到達時間],[事件說明],請您盡速處理。
                    title = "綠燈-執行人已接受未排程";
                    content = UserName + "您好:案件-" + wBSEventM.Customer1.ShortName + "-" + ExpectArriveSW + ":" + ExpectArriveDTStr + "," + EventStatusStr + ",請您盡速處理。";

                    //messageRepository.AddMsgbyUser(UserID, title, content, url);
                }

                //db.WBSEventM.Add(wBSEventM);
                db.WBSEventC.Add(wBSEventC);
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }
            return ret;

        }
        public ActionResult NewCase(WBSEventViewModel wbsModel, IEnumerable<HttpPostedFileBase> files, IEnumerable<HttpPostedFileBase> assignfiles)
        {
            ViewBag.type = wbsModel.type;
            ModelState.Remove("CCProduct");
            if (ModelState.IsValid)
            {
                if (wbsModel.type < 2 || wbsModel.type == 5)
                {
                    if (wbsModel.CustomerRef == 0 || wbsModel.CustomerRef == null)
                    {
                        ModelState.AddModelError("CustomerRef", "未選擇客戶");
                        return View();
                    }

                    if (wbsModel.CustomerUserName == "" || wbsModel.CustomerUserName == null)
                    {
                        ModelState.AddModelError("CustomerUserName", "叫修人員輸入錯誤");
                        return View();
                    }

                    if (wbsModel.CustomerUserPhone1 == "" || wbsModel.CustomerUserPhone1 == null)
                    {
                        ModelState.AddModelError("CustomerUserPhone1", "叫修電話輸入錯誤");
                        return View();
                    }
                    if (wbsModel.CustomerUserPhone1.Length > 20)
                    {
                        ModelState.AddModelError("CustomerUserPhone1", "叫修電話輸入錯誤");
                        return View();
                    }
                    if (wbsModel.CustomerUserPhone2 != null)
                    {
                        if (wbsModel.CustomerUserPhone2 != "" && (wbsModel.CustomerUserPhone1.Length > 20))
                        {
                            ModelState.AddModelError("CustomerUserPhone2", "叫修電話輸入錯誤");
                            return View();
                        }
                    }
                    if (wbsModel.CustomerCaseNum != null)
                    {
                        if (wbsModel.CustomerCaseNum.Length > 20)
                        {
                            ModelState.AddModelError("CustomerCaseNum", "客戶提供叫修單號輸入錯誤");
                            return View();
                        }
                    }
                    if (wbsModel.ProductClass == "" || wbsModel.ProductClass == null)
                    {
                        ModelState.AddModelError("ProductClass", "未選擇產品大類");
                        return View();
                    }
                    if (wbsModel.ItemClass == "" || wbsModel.ItemClass == null)
                    {
                        ModelState.AddModelError("ItemClass", "未選擇設備分類");
                        return View();
                    }
                    if (wbsModel.QuestionClass == "" || wbsModel.QuestionClass == null)
                    {
                        ModelState.AddModelError("QuestionClass", "未選擇問題分類");
                        return View();
                    }
                    //if (wbsModel.QuestionDescription == "" || wbsModel.QuestionDescription == null)
                    if (wbsModel.QuestionDescription == null)
                    {
                        ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                        return View();
                    }
                    else
                    {
                        if (wbsModel.QuestionDescription.Trim() == "")
                        {
                            ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                            return View();
                        }
                    }
                    if (wbsModel.Closed == "T")
                    {
                        if (wbsModel.AssignDescription == null)
                        {
                            ModelState.AddModelError("AssignDescription", "線上結案必需輸入建議解決方式描述作為服務報告,不可空白。");
                            return View();
                        }
                        else
                        {
                            if (wbsModel.AssignDescription == "")
                            {
                                ModelState.AddModelError("AssignDescription", "線上結案必需輸入建議解決方式描述作為服務報告,不可空白。");
                                return View();
                            }
                        }
                    }
                }
                // 先取得該使用者的 FormsIdentity
                FormsIdentity id = (FormsIdentity)User.Identity;
                // 再取出使用者的 FormsAuthenticationTicket
                FormsAuthenticationTicket ticket = id.Ticket;

                string[] ret;
                if (wbsModel.type == null || wbsModel.type == 0 || wbsModel.type == 5) //新增
                {
                    string AreaID = areaRespositiory.GetCustomerAreaID(wbsModel.CustomerRef);
                    //Boolean isAutoAssign = systemSettingRepository.IsAutoAssign(wbsModel.EventClass, AreaID);


                    wbsModel.CreateUserID = ticket.Name;
                    wbsModel.QuestionCreateUserID = ticket.Name;
                    //wbsModel.isAutoAssign = isAutoAssign.ToString();
                    //不再自動派工
                    wbsModel.isAutoAssign = "false";
                    wbsModel.Url = Request.Url.Authority;
                    
                    if (wbsModel.type == 5)
                        ret = wBSEventRepository.TwiceCreate(wbsModel);
                    else
                        ret = wBSEventRepository.Create(wbsModel);

                    if (ret[0] != "false")
                    {
                        string cu = wBSEventRepository.GetCShortNameAndProductName(int.Parse(ret[1]));
                        String msg = cu + "-新增成功,單號:" + ret[0];
                        string url = "http://" + Request.Url.Authority + "/WBSEvent/WBSAssignMain?area=" + ret[2];

                        if (wbsModel.ResponsibleID != "" && wbsModel.ResponsibleID != null && wbsModel.type == 5)
                        {
                            msg = cu + "-新增並派工成功,單號:" + ret[0];
                            //msg += ",系統已預設派工:" + ret[3] + "。";
                            //messageRepository.AddMsgbyRole("01", "新增叫修單", "新叫修單" + ret[0] + ",請盡速指派執行人!", url);
                        }
                        //else
                        messageRepository.AddMsgbyTypeAndCid("0", ret[1], url);
                        if (files != null)
                        {
                            //TempData["UploadedFiles"] = GetFileInfo(files)
                            Save(files, ret[0], ret[1], 1);
                        }
                        if (assignfiles != null)
                        {
                            //TempData["UploadedFiles"] = GetFileInfo(files)
                            Save(assignfiles, ret[0], ret[1], 2);
                        }
                        //if (isAutoAssign && wbsModel.type == 5)
                        //    return RedirectToAction("WBSEventMain", "WBSEvent", new { data = msg });
                        if (wbsModel.isAssign == "true")
                            return RedirectToAction("WBSAssignMain", "WBSEvent", new { area = ret[2], cid = ret[1], data = msg });

                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = msg });
                    }
                    else
                    {
                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = "新增失敗" });

                    }
                }
                else if (wbsModel.type == 1)//修改
                {
                    wbsModel.ModifyUserID = ticket.Name;
                    ret = wBSEventRepository.Update(wbsModel);
                    string cu = wBSEventRepository.GetCShortNameAndProductName(wbsModel.C_ID);
                    if (ret[0] != "false")
                    {
                        String msg = cu + "-修改成功,單號:" + ret[0];
                        if (files != null)
                        {
                            //TempData["UploadedFiles"] = GetFileInfo(files)
                            Save(files, ret[0], ret[1], 1);
                        }
                        if (assignfiles != null)
                        {
                            //TempData["UploadedFiles"] = GetFileInfo(files)
                            Save(assignfiles, ret[0], ret[1], 2);
                        }
                        if (wbsModel.isAssign == "true")
                            return RedirectToAction("WBSAssignMain", "WBSEvent", new { area = ret[2], cid = ret[1] });
                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = msg });
                    }                    
                    else
                    {
                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = "修改失敗" });

                    }
                }
                else if (wbsModel.type == 2)//刪除
                {
                    //wbsModel.ModifyUserID = ticket.Name;
                    wbsModel.DeleteMarkUserID = ticket.Name;
                    ret = wBSEventRepository.Delete(wbsModel);
                    string cu = wBSEventRepository.GetCShortNameAndProductName(wbsModel.C_ID);
                    if (ret[0] != "false")
                    {
                        String msg = cu + "-刪除成功,單號:" + ret[0];
                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = msg });
                    }
                    else
                    {
                        return RedirectToAction("WBSEventMain", "WBSEvent", new { data = "刪除失敗" });

                    }
                }
            }
            //return RedirectToAction("RegSuccess", "ActivityReg", new { data = msg });
            return View();
        }
        //電腦建立二次派工叫修單(20151221-增加自動派工)
        public String[] TwiceCreate(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[4];
            ret[0] = "false";
            ret[1] = "";
            ret[2] = "";    //area
            ret[3] = "";    //auto assign user name
            int num = 0, childCaseID = 0;
            
            
            num = db.WBSEventC.AsEnumerable().Select(x => x.Num).DefaultIfEmpty(0).Max(x => x) + 1;
            childCaseID = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == wBSEventViewModel.M_ID).Select(x => x.ChildCaseID).DefaultIfEmpty(0).Max(x => x) + 1;
            int questionGrade = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionGrade).First();
            int serviceHours = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionServiceHours).First();
            String groupSW = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventViewModel.CustomerRef).Select(x => x.GroupSW).First();

            if (wBSEventViewModel.ExpectArriveDTStr == null)
                wBSEventViewModel.ExpectArriveDTStr = "19000101 00:01";
            if (wBSEventViewModel.ExpectFinishDTStr == null)
                wBSEventViewModel.ExpectFinishDTStr = "19000101 00:01";
            wBSEventViewModel.ExpectArriveDT = DateTime.ParseExact(wBSEventViewModel.ExpectArriveDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            wBSEventViewModel.ExpectFinishDT = DateTime.ParseExact(wBSEventViewModel.ExpectFinishDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            ret[2] = GetCustomerArea(wBSEventViewModel.CustomerRef);


            try
            {
                bool isMChg = false;
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
                //20150811新增-Hsiuyang
                if (wBSEventViewModel.ChangeAddr != null)
                    if (wBSEventViewModel.ChangeAddr.Trim().Length > 0)
                    {
                        wBSEventM.CustomerAddr = wBSEventViewModel.ChangeAddr;
                        isMChg = true;
                    }
                //wBSEventM.SpareMach = "R";      //預設無借出備機
                //wBSEventM.UserMach = "R";       //預設無取回客戶機器
                if (Int32.Parse(wBSEventM.CaseMStatus) < 4 && wBSEventM.CaseMStatus != "0")
                {
                    isMChg = true;
                    wBSEventM.CaseMStatus = "4";    //4為已分配(另開子單)
                }
                if (wBSEventM.CaseMStatus == "6")   //6為全部子單以解決需退回5
                {   
                    isMChg = true;
                    wBSEventM.CaseMStatus = "5";    //5為部分子單已解決
                }
                if (isMChg)
                {
                    wBSEventM.ModifyDT = DateTime.Now;
                    wBSEventM.ModifyUserID = wBSEventViewModel.CreateUserID;
                }

                WBSEventC wBSEventC = new WBSEventC();
                ret[1] = num.ToString();
                wBSEventC.Num = num;
                wBSEventC.MomCaseID = wBSEventViewModel.M_ID;
                wBSEventC.ChildCaseID = childCaseID;
                wBSEventViewModel.WBSCaseNumberC = (wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString();
                wBSEventC.EventClass = wBSEventViewModel.EventClass;
                wBSEventC.ProductClass = Int32.Parse(wBSEventViewModel.ProductClass);
                wBSEventC.ItemClass = Int32.Parse(wBSEventViewModel.ItemClass);
                wBSEventC.QuestionClass = Int32.Parse(wBSEventViewModel.QuestionClass);
                wBSEventC.QuestionGrade = questionGrade;
                wBSEventC.QuestionServiceHours = serviceHours;
                wBSEventC.QuestionDescription = wBSEventViewModel.QuestionDescription;
                wBSEventC.QuestionCreateUserID = wBSEventViewModel.QuestionCreateUserID;
                wBSEventC.QuestionCreateDateTime = DateTime.Now;
                wBSEventC.ExpectArriveDateTime = wBSEventViewModel.ExpectArriveDT;
                wBSEventC.ExpectFinishDateTime = wBSEventViewModel.ExpectFinishDT;
                wBSEventC.ExpectArriveSW = wBSEventViewModel.ExpectArriveSW;
                wBSEventC.CreateDateTime = DateTime.Now;
                wBSEventC.CreateUserID = wBSEventViewModel.CreateUserID;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.CreateUserID;
                //20150811新增-Hsiuyang
                wBSEventC.SugProvideSpareMach = wBSEventViewModel.SugProvideSpareMach;
                wBSEventC.SugRetrieveSpareMach = wBSEventViewModel.SugRetrieveSpareMach;
                wBSEventC.SugRetrieveUserMach = wBSEventViewModel.SugRetrieveUserMach;
                wBSEventC.SugReturnUserMach = wBSEventViewModel.SugReturnUserMach;
                wBSEventC.SugMachMemo = (wBSEventViewModel.SugMachMemo == null) ? "" : wBSEventViewModel.SugMachMemo;   //建議備機說明

                wBSEventC.EventStatus = 11; //11為問題已開立
                //20150813新增-Hsiuyang
                if (wBSEventViewModel.Closed == "T") //線上處理結案影響
                {
                    //wBSEventM.CaseMStatus = "9";    //9為問題已結案
                    //wBSEventM.CloseDT = DateTime.Now;
                    wBSEventC.EventStatus = 50;     //50為任務已解決(維修附件上傳)
                    wBSEventC.QuestionFinishSW = "Y";
                    wBSEventC.QuestionFinishDT = DateTime.Now;
                    wBSEventC.QuestionFinishSysDT = DateTime.Now;
                    wBSEventC.ServiceReport = wBSEventViewModel.AssignDescription;  //當結案時解決方式即為服務報告
                }
                wBSEventC.AssignDescription = wBSEventViewModel.AssignDescription;  //解決方式(派單)描述


                //20150812新增-Hsiuyang-SugProduct建議部分
                if (wBSEventViewModel.MaterialJson != null)
                {
                    JArray SugProduct = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaterialJson);
                    for (int i = 0; i < SugProduct.Count; i++)
                    {
                        SugProduct sugProduct = new SugProduct();
                        sugProduct.CID = wBSEventC.Num;
                        sugProduct.Class = Int32.Parse(SugProduct[i]["Class"].ToString());
                        //sugProduct.Class = Int32.Parse(SugProduct[i][0].ToString());
                        //if (SugProduct[i][1].ToString() == "")
                        if (SugProduct[i]["ProductNum"].ToString() == "")
                            sugProduct.ProductName = SugProduct[i]["ProductName"].ToString();
                        //sugProduct.ProductName = SugProduct[i][2].ToString();
                        else
                            sugProduct.ProductNum = Int32.Parse(SugProduct[i]["ProductNum"].ToString());
                        //sugProduct.ProductNum = Int32.Parse(SugProduct[i][1].ToString());

                        db.SugProduct.Add(sugProduct);
                    }
                }
                //20150813新增-Hsiuyang-解決方式知識庫附件
                if (wBSEventViewModel.KnowledgeJson != null)
                {
                    JArray KnowledgeData = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.KnowledgeJson);
                    for (int i = 0; i < KnowledgeData.Count; i++)
                    {
                        Files knowledgefile = new Files();
                        knowledgefile.CID = wBSEventC.Num;
                        knowledgefile.Class = 3;
                        knowledgefile.FileAddr = "";
                        knowledgefile.FileName = "";
                        //knowledgefile.KnowledgeID = Int32.Parse(KnowledgeData[i][0].ToString());
                        knowledgefile.KnowledgeID = Int32.Parse(KnowledgeData[i]["KnowledgeID"].ToString());
                        db.Files.Add(knowledgefile);
                    }
                }
                //20150814新增-Hsiuyang-執行預先保養單
                if (wBSEventViewModel.MaintainCaseJson != null)
                {
                    JArray maintainCases = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaintainCaseJson);
                    for (int i = 0; i < maintainCases.Count; i++)
                    {
                        EventRelation maintainCase = new EventRelation();
                        maintainCase.CID = wBSEventC.Num;
                        maintainCase.RelationCID = Int32.Parse(maintainCases[i]["cID"].ToString());

                        db.EventRelation.Add(maintainCase);
                    }
                }
                //20151113新增-Hsiuyang-Hyperlink建議參考網頁(CLASS=9)
                if (wBSEventViewModel.HyperlinkJson != null)
                {
                    JArray Hyperlink = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.HyperlinkJson);
                    for (int i = 0; i < Hyperlink.Count; i++)
                    {
                        Files hyperlink = new Files();
                        hyperlink.CID = wBSEventC.Num;
                        hyperlink.Class = 9;
                        hyperlink.FileAddr = Hyperlink[i]["Href"].ToString();
                        hyperlink.FileName = Hyperlink[i]["Name"].ToString();

                        db.Files.Add(hyperlink);
                    }
                }
                //20151221-自動派單 20160906改轉派工時選擇人派工
                if (wBSEventViewModel.ResponsibleID != "" && wBSEventViewModel.ResponsibleID != null)
                {
                    //String subAreaID = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventM.CustomerRef).Select(x => x.RegionID).First();
                    //String AreaID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.AreaID).First();
                    //int rID = 0;

                    //if (db.SystemSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AutoAssign == true).Count() > 0) //事件個別指定
                    //{
                    //    if (db.SystemSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AutoAssignUserType == 2).Count() > 0)
                    //        rID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.ResponsibleID).First();
                    //    else
                    //    {
                    //        if (db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                    //        else if (db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                            
                    //    }
                    //}
                    //else //系統預設
                    //{
                    //    if (db.SystemSetting.Where(x => x.isSysDefault == true && x.AutoAssignUserType == 2).Count() > 0)
                    //        rID = db.SubArea.AsEnumerable().Where(x => x.SubAreaID == subAreaID).Select(x => x.ResponsibleID).First();
                    //    else
                    //    {
                    //        if (db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.EventClass == wBSEventViewModel.EventClass && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                    //        else if (db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Count() > 0)
                    //            rID = db.DefaultAssignSetting.Where(x => x.isSysDefault == true && x.AreaID == AreaID).Select(x => x.ResponsibleClassID).First();
                             
                    //    }

                    //}

                    //wBSEventC.ResponsibleID = rID;

                    wBSEventC.ResponsibleID = int.Parse(wBSEventViewModel.ResponsibleID);

                    wBSEventC.AssignCreateDT = DateTime.Now;
                    wBSEventC.AssignCreateUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignDT = DateTime.Now;
                    wBSEventC.AssignUserID = wBSEventViewModel.CreateUserID;
                    wBSEventC.AssignModifyDT = DateTime.Now;
                    wBSEventC.AssignModifyUserID = wBSEventViewModel.CreateUserID;

                    wBSEventC.RespondSW = "Y";
                    wBSEventC.RespondDT = DateTime.Now;
                    wBSEventC.RespondReason = "";
                    //wBSEventC.ScheduleStartDT = wBSEventViewModel.ExpectArriveDT;
                    //wBSEventC.ScheduleEndDT = wBSEventViewModel.ExpectFinishDT;
                    //wBSEventC.ScheduleServiceHours = wBSEventC.QuestionServiceHours;
                    
                    wBSEventC.EventStatus = 30; //30任務已接受未排程

                    //String ExpectArriveSW, EventStatusStr;
                    //if (wBSEventC.ExpectArriveSW == "0")
                    //    ExpectArriveSW = "自行約定";
                    //else if (wBSEventC.ExpectArriveSW == "1")
                    //    ExpectArriveSW = "合約規定";
                    //else if (wBSEventC.ExpectArriveSW == "2")
                    //    ExpectArriveSW = "建議期望";
                    //else if (wBSEventC.ExpectArriveSW == "4")
                    //    ExpectArriveSW = "自派新單";
                    //else
                    //    ExpectArriveSW = "客戶指定";

                    //String ExpectArriveDTStr = wBSEventC.ExpectArriveDateTime.Value.ToString("yyyy/MM/dd HH:mm");
                    //if (wBSEventC.ExpectArriveSW == "0")
                    //    ExpectArriveDTStr = "自行約定";
                                        
                    //EventStatusStr = "已接受未排程";


                    //String UserID = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.UserID).First();
                    //String UserName = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.UserData2.UserName).First();
                    //ret[3] = db.ResponsibleClass.Where(x => x.ID == rID).Select(x => x.Name).First() + "-" + UserName;

                    //String url = "http://" + wBSEventViewModel.Url + "/Mobile/MobileCaseDetail?type=2&&mid=" + wBSEventC.MomCaseID + "&&cid=" + wBSEventC.Num;
                    //String title = "";      //[燈號]-[推播事件說明]
                    //String content = "";    //[被推播人員姓名]您好:案件-[客戶簡稱]-[到達約定選擇]:[應到達時間],[事件說明],請您盡速處理。
                    //title = "綠燈-執行人已接受未排程";
                    //content = UserName + "您好:案件-" + wBSEventM.Customer1.ShortName + "-" + ExpectArriveSW + ":" + ExpectArriveDTStr + "," + EventStatusStr + ",請您盡速處理。";

                    //messageRepository.AddMsgbyUser(UserID, title, content, url);
                }

                WBSEventC tmp = db.WBSEventC.Find(wBSEventViewModel.C_ID);
                if (tmp.EventStatus == 49)
                {
                    tmp.EventStatus = 50;
                }

                //db.WBSEventM.Add(wBSEventM);
                db.WBSEventC.Add(wBSEventC);
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }
            return ret;
        }
        //完成報價
        public String[] FinishQuotation(WBSEventViewModel wBSEventViewModel,Boolean isClosed)//isClosed =true 結案 =flase轉派工
        {
            String[] ret = new String[3];
            ret[0] = "false";   //回饋訊息
            ret[1] = "";        //案號
            ret[2] = "";        //mid
            Boolean canClosed = true;       //判斷是否母單可以結案
            Boolean SpareMach = false;      //判斷目前備機是否提供 (true:提供中,flase:未提供)
            Boolean UserMach = false;       //判斷目前客戶機器是否取回 (true:取回中,flase:未取回)
            WBSEventC wBSEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);
            WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
            String caseNum = "", eventNumM;
            ret[2] = wBSEventC.MomCaseID.ToString();
            String SpareMachCaseNum = "";
            String UserMachCaseNum = "";

            caseNum = wBSEventM.CaseClass + wBSEventM.CaseDate + "-";
            if (wBSEventM.CaseCode < 10)
                caseNum += "0000" + wBSEventM.CaseCode.ToString();
            else if (wBSEventM.CaseCode < 100 && wBSEventM.CaseCode >= 10)
                caseNum += "00" + wBSEventM.CaseCode.ToString();
            else if (wBSEventM.CaseCode < 10000 && wBSEventM.CaseCode >= 1000)
                caseNum += "0" + wBSEventM.CaseCode.ToString();
            else
                caseNum += wBSEventM.CaseCode.ToString();
            eventNumM = caseNum;
            caseNum += "-" + ((wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString());

            try
            {
                wBSEventC.ServiceReport = wBSEventViewModel.ServiceReport;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.ModifyUserID;

                if (wBSEventC.ScheduleStartDT == null)
                    wBSEventC.ScheduleStartDT = DateTime.Now;

                if (wBSEventC.ScheduleEndDT == null)
                {
                    wBSEventC.ServiceLeaveDT = DateTime.Now;
                    wBSEventC.ServiceLeaveSysDT = DateTime.Now;
                    wBSEventC.ServiceArriveDT = DateTime.Now;
                    wBSEventC.ServiceArriveSysDT = DateTime.Now;
                    wBSEventC.ScheduleEndDT = DateTime.Now;
                    //wBSEventC.ScheduleStartDT = DateTime.Now;
                }
                wBSEventC.ServiceModifyDT = DateTime.Now;
                wBSEventC.ServiceModifyUserID = wBSEventViewModel.ModifyUserID;

                if (wBSEventC.ServiceCreateUserID == null)
                {
                    wBSEventC.ServiceCreateDT = DateTime.Now;
                    wBSEventC.ServiceCreateUserID = wBSEventViewModel.ModifyUserID;
                }

                wBSEventC.ScheduleServiceHours = wBSEventViewModel.WorkHours;
                wBSEventC.ServiceTakeHours = wBSEventViewModel.WorkHours;
                //wBSEventC.EventStatus = wBSEventViewModel.EventStatus; //43報價未回覆 50任務已解決

                if (isClosed)
                {
                    //按照case的最後修改時間小到大排序,保證最後一次借出或歸還順序是否正確(本單與被刪除子單不算在內)
                    var qryC = db.WBSEventC.Where(x => x.MomCaseID == wBSEventC.MomCaseID && x.Num != wBSEventC.Num && x.EventStatus != 0).OrderBy(x => x.ModifyDateTime);
                    foreach (WBSEventC C in qryC)
                    {
                        if (C.EventStatus < 50)
                            canClosed = false;          //某子單未解決不可結案
                        if (C.RetrieveSpareMach == "T") //先判斷此case是否取回備機,若有,表示之前的全取回
                            SpareMach = false;
                        if (C.ReturnUserMach == "T")    //先判斷此case是否歸還客戶機器,若有,表示之前的全歸還
                            UserMach = false;
                        if (C.ProvideSpareMach == "T") //再判斷此case是否借出備機
                        {
                            SpareMachCaseNum = eventNumM + "-" + ((C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString());
                            SpareMach = true;
                        }
                        if (C.RetrieveUserMach == "T")  //再判斷此case是否取回客戶機器
                        {
                            UserMachCaseNum = eventNumM + "-" + ((C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString());
                            UserMach = true;
                        }
                    }

                    if (wBSEventC.RetrieveSpareMach == "T") //先判斷本case是否取回備機,若有,表示之前的全取回
                        SpareMach = false;
                    if (wBSEventC.ReturnUserMach == "T")    //先判斷本case是否歸還客戶機器,若有,表示之前的全歸還
                        UserMach = false;
                    if (wBSEventC.ProvideSpareMach == "T")  //再判斷本次是否借出備機
                        SpareMach = true;
                    if (wBSEventC.RetrieveUserMach == "T")  //再判斷本次是否取回客戶機器
                        UserMach = true;

                    if (SpareMach == true)
                    {
                        wBSEventM.SpareMach = "L";
                        canClosed = false;
                    }
                    else
                    {
                        wBSEventM.SpareMach = "R";
                    }
                    if (UserMach == true)
                    {
                        wBSEventM.UserMach = "L";
                        canClosed = false;
                    }
                    else
                    {
                        wBSEventM.UserMach = "R";
                    }

                    if (canClosed)
                    {
                        wBSEventC.EventStatus = 50;
                        wBSEventM.CaseMStatus = "9";
                        wBSEventM.CloseDT = DateTime.Now;
                        wBSEventM.ModifyDT = DateTime.Now;
                        wBSEventM.ModifyUserID = wBSEventViewModel.ModifyUserID;
                        db.SaveChanges();
                        //ret[0] = "案件" + caseNum + "已解決,所有子單均解決,完成結案。";
                        ret[0] = wBSEventM.Customer1.ShortName + "-" + wBSEventC.ProductClass1.Note + "-所有子單均解決,完成結案,單號:" + caseNum + "。";
                    }
                    else
                    {
                        if (wBSEventC.EventStatus < 42)
                            wBSEventC.EventStatus = 42;
                        
                        //wBSEventM.CaseMStatus = "6";
                        wBSEventM.ModifyDT = DateTime.Now;
                        wBSEventM.ModifyUserID = wBSEventViewModel.ModifyUserID;
                        db.SaveChanges();
                        //ret[0] = "案件" + caseNum + "已解決,有";

                        ret[0] = wBSEventM.Customer1.ShortName + "-" + wBSEventC.ProductClass1.Note + "-無法結案,處理資訊暫存成功,單號:" + caseNum + "。";

                        //if (SpareMach == true)
                        //    ret[0] += "未取回備機,";
                        //if (UserMach == true)
                        //    ret[0] += "未歸還客戶機器,";
                        //ret[0] += "子單未解決,無法結案。";

                        if (SpareMach == true)
                            ret[0] += "注意事項:單號:" + SpareMachCaseNum + ",已勾選「提供備機」但後續子任務未勾選「拿回備機」。";
                        if (UserMach == true)
                            ret[0] += "注意事項:單號:" + UserMachCaseNum + ",已勾選「拿回客戶機器」但後續子任務未勾選「歸還客戶機器」。";
                    }
                }
                else
                {
                    if (wBSEventC.RetrieveSpareMach == "T") //先判斷本case是否取回備機,若有,表示之前的全取回
                        wBSEventM.SpareMach = "R"; ;
                    if (wBSEventC.ReturnUserMach == "T")    //先判斷本case是否歸還客戶機器,若有,表示之前的全歸還
                        wBSEventM.UserMach = "R"; ;
                    if (wBSEventC.ProvideSpareMach == "T")  //再判斷本次是否借出備機
                        wBSEventM.SpareMach = "L";
                    if (wBSEventC.RetrieveUserMach == "T")  //再判斷本次是否取回客戶機器
                        wBSEventM.UserMach = "L";
                    wBSEventC.EventStatus = 49;
                    //wBSEventM.CaseMStatus = "6";
                    db.SaveChanges();
                    ret[0] = wBSEventM.Customer1.ShortName + "-" + wBSEventC.ProductClass1.Note + "-已解決未派工,單號:" + caseNum + "。";
                    //ret[0] = "案件" + caseNum + "已解決。";
                }
                ret[1] = caseNum;
            }
            catch
            {
                ret[0] = "false";
            }

            return ret;
        }
        //刪除叫修單
        public String[] Delete(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[2];
            ret[0] = "false";
            ret[1] = wBSEventViewModel.C_ID.ToString();
            
            try
            {   
                WBSEventC wBSEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);

                wBSEventC.DeleteMarkDateTime = DateTime.Now;
                wBSEventC.DeleteMarkUserID = wBSEventViewModel.DeleteMarkUserID;
                //wBSEventC.DeleteMarkSW = "Y";
                wBSEventC.DeleteReason = wBSEventViewModel.DeleteReason;
                wBSEventC.EventStatus = 0;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.DeleteMarkUserID;
                db.SaveChanges();

                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
                int NotEndNum = db.WBSEventC.Where(x => x.MomCaseID == wBSEventViewModel.M_ID && x.EventStatus != 0 && x.EventStatus < 50).Count();
                if (NotEndNum == 0 && wBSEventC.ChildCaseID != 1)
                {
                    wBSEventM.CaseMStatus = "9";
                    wBSEventM.CloseDT = DateTime.Now;
                    wBSEventM.ModifyDT = DateTime.Now;
                    wBSEventM.ModifyUserID = wBSEventViewModel.DeleteMarkUserID;
                }
                else if (wBSEventC.ChildCaseID == 1)
                {
                    wBSEventM.CaseMStatus = "0";
                    wBSEventM.ModifyDT = DateTime.Now;
                    wBSEventM.ModifyUserID = wBSEventViewModel.DeleteMarkUserID;
                }
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }

            return ret;
        }
        //我的工作(type: 1-未解決案件 2-異常案件 3-與我相關的案件 4-最近異動的案件 5-實際執行人已解決未結案案件 6-所屬區域大類案件)
        public IQueryable<WBSEventViewModel> MyJobSearch(String type, String dateClass, DateTime startDate, DateTime endDate, String uid, String isClosed)
        {
            string roleid = db.UserData.Find(uid).RoleID;
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();
            List<String> areaIDList = new List<String>();
            List<AlertDetailSettingViewModel> alertMList = new List<AlertDetailSettingViewModel>();
            if (type.Equals("2")) {
                var Aqry = db.AlertDetailSetting;
                foreach (AlertDetailSetting o in Aqry) {
                    AlertDetailSettingViewModel a = new AlertDetailSettingViewModel();
                    a.EventClass = o.EventClass;
                    a.AlertEvent = o.AlertEvent;
                    a.FirstTime = o.FirstTime;
                    alertMList.Add(a);
                }
            }
            if(type.Equals("6")){
                var qry3 = db.SubArea.Where(x=>x.ResponsibleClass.UserID == uid);
                foreach (SubArea o in qry3) {                    
                    areaIDList.Add(o.AreaID);
                }
            }


            var qry = db.WBSEventM.Where(x => x.CaseID != 0);

            foreach (WBSEventM m in qry) {
                //var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID && x.EventStatus != 0 && x.EventStatus < 30);
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID);

                //qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus < 50);
                if (type.Equals("1"))   //未解決
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0" && x.EventStatus >= 11 && x.EventStatus < 50);
                    if (roleid != "99" && roleid != "10")
                        qry2 = qry2.Where(x => x.ResponsibleClass.UserID == uid);
                }
                else if (type.Equals("2"))  //異常
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0" && x.EventStatus >= 11 && x.EventStatus <= 50);
                    if (roleid != "99" && roleid != "10")
                        qry2 = qry2.Where(x => x.ResponsibleClass.UserID == uid);
                }
                else if (type.Equals("3"))  //與我相關
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0" && x.EventStatus >= 11 && x.EventStatus <= 50);
                    if (roleid != "99" && roleid != "10")
                        qry2 = qry2.Where(x => x.CreateUserID == uid || x.AssignUserID == uid || x.ServiceCreateUserID == uid || x.ResponsibleClass.UserID == uid || x.WBSEventM.Customer1.SubArea.ResponsibleClass.UserID == uid);
                }
                else if (type.Equals("4"))  //最近異動
                {
                    //qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0");
                    if (roleid != "99" && roleid != "10")
                        qry2 = qry2.Where(x => x.ModifyUserID == uid);                    
                }
                else if (type.Equals("5")) //實際執行人已解決未結案
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0" && x.EventStatus >= 46 && x.EventStatus <= 50);
                    if (roleid != "99" && roleid != "10")
                        qry2 = qry2.Where(x => x.ServiceCreateUserID == uid || x.ServiceModifyUserID == uid);
                }
                else if (type.Equals("6"))  //所屬區域
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus != "9" && x.WBSEventM.CaseMStatus != "0");
                    if(isClosed == "true") //已解決未結案
                        qry2 = qry2.Where(x => x.EventStatus >= 46 && x.EventStatus <= 50);
                    else
                        qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus < 50);
                    //String AreaID = GetCustomerArea()
                    //if (roleid != "99" && roleid != "10")
                       
                }

                


                String Addr = "", SName = "", FName = "";
                Addr = m.Customer1.Addr;
                SName = m.Customer1.ShortName;
                FName = m.Customer1.FullName;

                if (dateClass != null && dateClass != "") {
                    switch (dateClass) {
                        case "1":   //開單日期
                            qry2 = qry2.Where(x => x.CreateDateTime.Value.CompareTo(startDate) >= 0 && x.CreateDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "2":   //派工日期
                            qry2 = qry2.Where(x => x.AssignDT.Value.CompareTo(startDate) >= 0 && x.AssignDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "3":   //接受日期
                            qry2 = qry2.Where(x => x.RespondDT.Value.CompareTo(startDate) >= 0 && x.RespondDT.Value.CompareTo(endDate) <= 0 && x.RespondSW == "Y");
                            break;
                        case "4":   //到達日期
                            qry2 = qry2.Where(x => x.ServiceArriveDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "5":   //解決日期
                            qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                            //qry2 = qry2.Where(x => x.ServiceLeaveDT.Value.CompareTo(startDate) >= 0 && x.ServiceLeaveDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "6":   //結案日期
                            qry2 = qry2.Where(x => x.WBSEventM.CloseDT.Value.CompareTo(startDate) >= 0 && x.WBSEventM.CloseDT.Value.CompareTo(endDate) <= 0);
                            //qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "7":   //異動日期
                            qry2 = qry2.Where(x => x.ModifyDateTime.Value.CompareTo(startDate) >= 0 && x.ModifyDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "8":   //系統到達日期
                            qry2 = qry2.Where(x => x.ServiceArriveSysDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveSysDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "9":   //系統解決日期
                            qry2 = qry2.Where(x => x.QuestionFinishSysDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishSysDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                            break;
                    }                    
                }

                foreach (WBSEventC c in qry2) {
                    //先判斷如果為區域大類且不是主管 此筆還要不要做
                    Boolean notSameArea = true;
                    if (type.Equals("6") && roleid != "99" && roleid != "10"){
                        foreach(string o in areaIDList){
                            if(c.WBSEventM.Customer1.SubArea.AreaID == o)
                                notSameArea = false;
                        }
                        if(notSameArea)
                            continue ;
                    }

                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >= 10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                    v.EventStatus = c.EventStatus;

                    v.EventStatusStr = (v.EventStatus == 0) ? "0" + v.EventStatus.ToString() : v.EventStatus.ToString();
                    v.EventStatusStr += "." + GetEventStatusStr(v.EventStatus);

                    v.CustomerSName = m.Customer1.ShortName;                    
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone = m.CustomerUserPhone1;
                    if (m.CustomerUserPhone2 != null && m.CustomerUserPhone2 != "")
                        v.CustomerUserPhone += " /" + m.CustomerUserPhone2;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    
                    v.ProductNote = c.ProductClass1.Note;
                    
                    v.ItemNote = c.ItemClass1.Note;
                    
                    v.QuestionNote = c.QuestionClass1.Note;
                    
                    
                    v.QuestionDescription = c.QuestionDescription;

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";
                    v.HasAssignActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 2).Count() > 0)
                        v.HasAssignActtachment = "@";

                    v.HasKnowledge = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 3).Count() > 0)
                        v.HasKnowledge = "@";

                    v.HasHyperlink = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 9).Count() > 0)
                        v.HasHyperlink = "@";

                    v.ExpectArriveDTStr = (c.ExpectArriveDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                    v.ExpectFinishDTStr = (c.ExpectFinishDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                    if (c.ExpectArriveSW == "1")
                        v.ExpectArriveSWStr = "合約規定";
                    else if (c.ExpectArriveSW == "2")
                        v.ExpectArriveSWStr = "建議期望";
                    else if (c.ExpectArriveSW == "3")
                        v.ExpectArriveSWStr = "客戶指定";
                    else if (c.ExpectArriveSW == "4")
                        v.ExpectArriveSWStr = "自派新單";
                    else
                    {
                        v.ExpectArriveSWStr = "自行約定";
                        v.ExpectArriveDTStr = "請自行與客戶約定";
                        v.ExpectFinishDTStr = "請自行與客戶約定";
                    }
                    
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    //v.DeleteMarkSW = c.DeleteMarkSW;
                    //v.DeleteReason = c.DeleteReason;
                    //v.DeleteMarkUserID = c.DeleteMarkUserID;
                    //v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    
                    
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = c.UserData.UserName;
                    v.ModifyDT = c.ModifyDateTime;                    
                    v.ModifyUserName = c.UserData2.UserName;
                    if (c.AssignDT != null)
                        v.AssignDTStr = c.AssignDT.Value.ToString("MM/dd HH:mm");
                    if (c.AssignUserID != null)
                        v.AssignUserName = c.UserData4.UserName;//db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                    if (c.ResponsibleID != null)
                        v.ResponsibleUserName = c.ResponsibleClass.Name + "-" + c.ResponsibleClass.UserData2.UserName;
                    

                    if (c.EventStatus >= 41)
                    {
                        if (c.ServiceModifyUserID != null)
                            v.ServiceUserName = c.UserData7.UserName;//db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceModifyUserID).Select(x => x.UserName).First();
                        else if (c.ServiceCreateUserID != null)
                            v.ServiceUserName = c.UserData8.UserName;//db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceCreateUserID).Select(x => x.UserName).First();
                        else
                            v.ServiceUserName = c.UserData.UserName;//db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    }

                    if (c.ServiceArriveSysDT != null)
                        v.ServiceArriveDT = c.ServiceArriveDT;                    

                    if (c.ScheduleStartDT != null)
                        v.ScheduleStartDT = c.ScheduleStartDT;

                    if (c.ServiceLeaveSysDT != null)
                        v.ServiceLeaveDT = c.ServiceLeaveDT;

                    //v.CloseDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                    //if (c.ServiceLeaveDT != null)
                    //    v.SolveDTStr = c.ServiceLeaveDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.WBSEventM.CloseDT != null)
                    {
                        v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("MM/dd HH:mm");
                        v.EventStatusStr = "99.已結案";
                    }
                    v.MaintainNum = "";
                    int maintainNum = db.EventRelation.Where(x => x.CID == c.Num).Count();
                    if (maintainNum != 0)
                        v.MaintainNum = maintainNum.ToString();

                    v.RespondReason = c.RespondReason;
                    if (m.Customer1.SubArea.ResponsibleID2 != null)
                    {
                        v.DefaultUserName2 = m.Customer1.SubArea.ResponsibleClass1.Name + "-" + m.Customer1.SubArea.ResponsibleClass1.UserData2.UserName;
                        //v.ResponsibleArea2 = m.Customer1.SubArea.SubAreaID;
                    }



                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    //v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                    //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                    //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();
                    //v.AreaID = m.Customer1.SubArea.AreaID;
                    //v.AreaStr = m.Customer1.SubArea.Area.Name;

                    if (type.Equals("2")) 
                        v.AbnormalReason = isAbnormal(c, alertMList);
                    if (type.Equals("3"))
                    {
                        v.RelatedCauses = " ";
                        if(c.CreateUserID == uid)
                            v.RelatedCauses += " 開單";
                        if(c.AssignUserID == uid )
                            v.RelatedCauses += " 派工";
                        if(c.ServiceCreateUserID == uid )
                            v.RelatedCauses += " 實際執行人";
                        if(c.EventStatus >= 30)
                            if(c.ResponsibleClass.UserID == uid )
                                v.RelatedCauses += " 執行人";
                        if(m.Customer1.SubArea.ResponsibleClass.UserID == uid)
                            v.RelatedCauses += " 預設責任區人員";

                        
                    }
                    //AbnormalReason //異常狀態
                    if (type != "2")
                        ret.Add(v);
                    else {
                        if (v.AbnormalReason != "")
                            ret.Add(v);
                    }
                }
            }
            return ret.AsQueryable();
        }
        //C02C03 排程 
        public String[] ChangeScheduleDT(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[3];
            ret[0] = "false";   //回饋訊息
            ret[1] = "";        //案號
            ret[2] = "";        //mid

            if (wBSEventViewModel.ScheduleStartDTStr == null)
                wBSEventViewModel.ScheduleStartDTStr = "19000101 00:01";
            wBSEventViewModel.ScheduleStartDT = DateTime.ParseExact(wBSEventViewModel.ScheduleStartDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            try
            {
                WBSEventC wBSEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);

                if (wBSEventC.EventStatus == 30)
                {                    
                    wBSEventC.EventStatus = 31;
                }
                wBSEventC.ScheduleStartDT = wBSEventViewModel.ScheduleStartDT;

                if (wBSEventC.ScheduleServiceHours == null)
                {
                    wBSEventC.ScheduleServiceHours = 0;
                    wBSEventC.ScheduleEndDT = wBSEventC.ScheduleStartDT;
                }
                
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.ModifyUserID;

                String caseNum = wBSEventM.CaseClass + wBSEventM.CaseDate + "-";
                if (wBSEventM.CaseCode < 10)
                    caseNum += "0000" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 100 && wBSEventM.CaseCode >= 10)
                    caseNum += "00" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 10000 && wBSEventM.CaseCode >= 1000)
                    caseNum += "0" + wBSEventM.CaseCode.ToString();
                else
                    caseNum += wBSEventM.CaseCode.ToString();
                caseNum += "-" + ((wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString());

                db.SaveChanges();
                ret[1] = caseNum;
                ret[0] = "true";
            }
            catch
            {
                ret[0] = "false";
            }
            return ret;
        }
        //客戶叫修主畫面-叫修案件讀取
        //20150818-刪除子單不讀-Hsiuyang
        public IQueryable<WBSEventViewModel> Read()
        {
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();
            
            var qry = db.WBSEventM.Where(x => x.CaseClass == "C");
            foreach (WBSEventM m in qry)
            {
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID && x.EventStatus != 0 && x.EventStatus < 50);
                var qry3 = db.Customer.Where(x => x.CustomerRef == m.CustomerRef);
                //var qry4 = db.ProductClass.Where(x => x.)
                String Addr = "", SName = "", FName = "";
                foreach (Customer o in qry3)
                {
                    Addr = o.Addr;
                    SName = o.ShortName;
                    FName = o.FullName;
                }

                foreach (WBSEventC c in qry2)
                {
                                        
                    String ProductNote = "", ItemNote = "" ,QuestionNote = "";
                    var qry4 = db.ProductClass.Where(x => x.ProductClassID == c.ProductClass);
                    foreach (ProductClass o in qry4)
                    {                        
                        ProductNote = o.Note;                        
                    }

                    var qry5 = db.ItemClass.Where(x => x.ItemClassID == c.ItemClass);
                    foreach (ItemClass o in qry5)
                    {
                        ItemNote = o.Note;
                    }

                    var qry6 = db.QuestionClass.Where(x => x.QuestionClassID == c.QuestionClass);
                    foreach (QuestionClass o in qry6)
                    {
                        QuestionNote = o.Note;
                    }


                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >=10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >=100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >=1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0"+c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = Addr;
                    v.CustomerSName = SName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = ProductNote;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = ItemNote;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = QuestionNote;
                    v.QuestionNoteAll = ProductNote + "-" + ItemNote + "-" + QuestionNote;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.EventStatus = c.EventStatus;
                    if (v.EventStatus == 11)
                        v.EventStatusStr = "11.已開單未派工";
                    else if (v.EventStatus == 20)
                        v.EventStatusStr = "20.已拒絕待重派";
                    else if (v.EventStatus == 21)
                        v.EventStatusStr = "21.已派工未接受";                    
                    else if (v.EventStatus == 30)
                        v.EventStatusStr = "30.已接受未排程";
                    else if (v.EventStatus == 31)
                        v.EventStatusStr = "31.已接受已排程";
                    else if (v.EventStatus == 41)
                        v.EventStatusStr = "41.已到達未離開";
                    else if (v.EventStatus == 42)
                        v.EventStatusStr = "42.已離開待附件";
                    else if (v.EventStatus == 46)
                        v.EventStatusStr = "46.已解決未審核";
                    //else if (v.EventStatus == 50)
                    //    v.EventStatusStr = "50.已解決已審核";



                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    v.ModifyUserID = c.ModifyUserID;

                    //已開立時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);
                    //v.ServiceDT = Convert.ToDateTime(diff1.ToString());
                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");
                    
                    TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                    v.OverTime = "";
                    v.OverTimeDisplay = "none";
                    if (diff1.CompareTo(duration) > 0)
                    {
                        v.OverTime = "逾時";
                        v.OverTimeColor = "Red";
                        v.OverTimeDisplay = "";
                    }


                    //v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                    //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                    //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();


                    ret.Add(v);
                }                
            }
            return ret.AsQueryable();
        }
        //客戶叫修主畫面-案件詳情讀取
        public WBSEventViewModel ReadOneCase(int mID, int cID)
        {
            WBSEventViewModel v = new WBSEventViewModel();
            WBSEventM M = db.WBSEventM.Find(mID);
            WBSEventC C = db.WBSEventC.Find(cID);

            v.C_ID = C.Num;
            v.CreateDT = C.CreateDateTime;
            v.CreateUserID = C.CreateUserID;
            v.CustomerAddr = M.Customer1.Addr; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.Addr).First();            
            v.CustomerID = M.Customer1.CustomerID; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.CustomerID).First();
            v.CustomerRef = M.CustomerRef;
            v.CustomerSName = M.Customer1.ShortName; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.ShortName).First();
            v.CustomerUserName = M.CustomerUserName;
            v.CustomerUserPhone1 = M.CustomerUserPhone1;
            v.CustomerUserPhone2 = M.CustomerUserPhone2;
            v.EventClass = C.EventClass;
            v.ExpectArriveDT = C.ExpectArriveDateTime;
            v.ExpectArriveSW = C.ExpectArriveSW;
            v.ExpectFinishDT = C.ExpectFinishDateTime;
            //20150811新增-Hsiuyang
            v.ChangeAddr = M.CustomerAddr;
            v.SpareMach = M.SpareMach;
            v.UserMach = M.UserMach;
            v.CaseMStatus = M.CaseMStatus;

            //v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.Name + "-" + M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.ResponsibleArea = M.Customer1.SubArea.SubAreaID;

            v.ExpectArriveDTStr = (C.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            v.ExpectFinishDTStr = (C.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            v.ExpectArriveSW = C.ExpectArriveSW;
            if (C.ExpectArriveSW == "1")            
                v.ExpectArriveSWStr = "合約規定";            
            else if (C.ExpectArriveSW == "2")
                v.ExpectArriveSWStr = "建議期望";
            else if (C.ExpectArriveSW == "3")
                v.ExpectArriveSWStr = "客戶指定";
            else
            {
                v.ExpectArriveSWStr = "自行約定";
                v.ExpectArriveDTStr = "請自行與客戶約定";
                v.ExpectFinishDTStr = "請自行與客戶約定";
            }            

            v.ItemClass = C.ItemClass.ToString();

            v.ProductNote = C.ProductClass1.Note; //db.ProductClass.AsEnumerable().Where(x => x.ProductClassID == C.ProductClass).Select(x => x.Note).First();
            v.ItemNote = C.ItemClass1.Note; //db.ItemClass.AsEnumerable().Where(x => x.ItemClassID == C.ItemClass).Select(x => x.Note).First();
            v.QuestionNote = C.QuestionClass1.Note; //db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == C.QuestionClass).Select(x => x.Note).First();

            v.M_ID = M.CaseID;
            v.ProductClass = C.ProductClass.ToString();
            v.QuestionClass = C.QuestionClass.ToString();
            v.QuestionDescription = C.QuestionDescription;
            v.WBSCaseNumberC = (C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString();
            v.WBSCaseNumberM = M.CaseClass + M.CaseDate + "-";
            if (M.CaseCode < 10)
                v.WBSCaseNumberM += "0000" + M.CaseCode.ToString();
            else if (M.CaseCode < 100 && M.CaseCode >= 10)
                v.WBSCaseNumberM += "000" + M.CaseCode.ToString();
            else if (M.CaseCode < 1000 && M.CaseCode >= 100)
                v.WBSCaseNumberM += "00" + M.CaseCode.ToString();
            else if (M.CaseCode < 10000 && M.CaseCode >= 1000)
                v.WBSCaseNumberM += "0" + M.CaseCode.ToString();
            else
                v.WBSCaseNumberM += M.CaseCode.ToString();
            v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;

            //20150811新增-Hsiuyang
            v.SugProvideSpareMach = C.SugProvideSpareMach;
            v.SugRetrieveSpareMach = C.SugRetrieveSpareMach;
            v.SugRetrieveUserMach = C.SugRetrieveUserMach;
            v.SugReturnUserMach = C.SugReturnUserMach;
            v.EventStatus = C.EventStatus;
            v.AssignDescription = C.AssignDescription;
            //20150814新增-Hsiuyang
            if (C.EventStatus >= 50)
                v.Closed = "T";
            else
                v.Closed = "F";
            //建議零件
            var qryS = db.SugProduct.Where(x => x.CID == cID && (x.Class == 1 || x.Class == 3));
            JArray SugProduct = new JArray();
            foreach (SugProduct s in qryS)
            {
                JObject item = new JObject();
                item["Class"] = s.Class.ToString();
                if (s.ProductNum == null)
                {
                    item["ProductNum"] = "";
                    item["ProductName"] = s.ProductName;
                }
                else
                {
                    item["ProductNum"] = s.ProductNum.ToString();
                    item["ProductName"] = s.ProductData.Name; //db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                    //item["ProductName"] = db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                }
                SugProduct.Add(item);
            }
            if (SugProduct.Count > 0)
                v.MaterialJson = SugProduct.ToString();
            //解決方式知識庫附件
            var qryK = db.Files.Where(x => x.CID == cID && x.Class == 3);
            JArray KnowledgeData = new JArray();
            foreach (Files k in qryK)
            {
                JObject item = new JObject();
                item["KnowledgeID"] = k.KnowledgeID.ToString();
                item["Name"] = k.KnowledgeBase.FileName; //db.KnowledgeBase.AsEnumerable().Where(x => x.KnowledgeID == k.KnowledgeID).Select(x => x.FileName).First();

                KnowledgeData.Add(item);
            }
            if (KnowledgeData.Count > 0)
                v.KnowledgeJson = KnowledgeData.ToString();
            //執行預先保養單
            var qryE = db.EventRelation.Where(x => x.CID == cID);
            JArray MaintainCase = new JArray();
            foreach (EventRelation e in qryE)
            {
                JObject item = new JObject();
                item["mID"] = db.WBSEventC.AsEnumerable().Where(x => x.Num == e.RelationCID).Select(x => x.MomCaseID).First();                
                item["cID"] = e.RelationCID;

                MaintainCase.Add(item);
            }
            if (MaintainCase.Count > 0)
                v.MaintainCaseJson = MaintainCase.ToString();

            if (C.EventStatus == 0)
            {
                v.DeleteMarkDT = C.DeleteMarkDateTime;
                v.DeleteMarkDTStr = (C.DeleteMarkDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                v.DeleteMarkUserID = C.DeleteMarkUserID;
                v.DeleteMarkUserName = db.UserData.AsEnumerable().Where(x => x.UserID == C.DeleteMarkUserID).Select(x => x.UserName).First();
                v.DeleteReason = C.DeleteReason;
            }
            //20150824新增-Hsiuyang-已排程所需(預計到達時間,回覆說明)
            if (C.EventStatus == 31) {
                v.ScheduleStartDT = C.ScheduleStartDT;
                v.ScheduleStartDTStr = (C.ScheduleStartDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                v.RespondReason = C.RespondReason;
                if(C.RespondSW == "Y")
                    v.RespondSWStr = "任務已接受";
                else if (C.RespondSW == "N")
                    v.RespondSWStr = "任務已拒絕";
                else
                    v.RespondSWStr = "尚未回覆";
            }
            if (C.EventStatus >= 41)
            {
                v.ServiceArriveDT = C.ServiceArriveDT;
                v.ServiceArriveDTStr = (C.ServiceArriveDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            }
            if (C.EventStatus >= 42)
            {
                v.ServiceLeaveDT = C.ServiceLeaveDT;
                v.ServiceLeaveDTStr = (C.ServiceLeaveDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            }
            //20150922新增-Hsiuyang
            if (C.EventStatus >= 46)
            {
                v.ServiceReport = C.ServiceReport;
                
                v.ProvideSpareMach = C.ProvideSpareMach;
                v.RetrieveSpareMach = C.RetrieveSpareMach;
                v.RetrieveUserMach = C.RetrieveUserMach;
                v.ReturnUserMach = C.ReturnUserMach;
                if (C.QuestionFinishDT != null)
                        v.SolveDTStr = C.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                if (C.WBSEventM.CloseDT != null)                    
                    v.CloseDTStr = C.WBSEventM.CloseDT.Value.ToString("yyyy/MM/dd HH:mm");
            }


            return v;
        }
        //案件檢視
        public IQueryable<WBSEventViewModel> EventSearch(string eventStatus, string eventClass, string userClass, string user, string areaID, string childCaseID, string CGroupSW, string CGroupID, string CSName, string dateClass, DateTime startDate, DateTime endDate)
        {
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();
            endDate = endDate.AddDays(1);

            var qry = db.WBSEventM.Where(x=>x.CaseID!=0);

            if (eventClass != null && eventClass != "")
            {
                string temp = eventClass.First().ToString();
                qry = qry.Where(x => x.CaseClass == temp);
            }

            if (areaID != null && areaID != "" && areaID != "12")   //12為不分區
            {
                qry = qry.Where(x => x.Customer1.SubArea.AreaID == areaID);
            }

            if (CGroupSW != null && CGroupSW != "")
            {
                qry = qry.Where(x => x.Customer1.GroupSW == CGroupSW);
            }

            if (CGroupID != null && CGroupID != "")
            {
                qry = qry.Where(x => x.Customer1.GroupID == CGroupID);
            }

            if (CSName != null && CSName != "")
            {
                int t = Int32.Parse(CSName);
                qry = qry.Where(x => x.CustomerRef == t);
            }

            //var qry = db.WBSEventM.Where(x => x.CaseClass == "C");
            foreach (WBSEventM m in qry)
            {



                //var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID && x.EventStatus != 0 && x.EventStatus < 30);
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID);
                var qry3 = db.Customer.Where(x => x.CustomerRef == m.CustomerRef);
                //var qry4 = db.ProductClass.Where(x => x.)
                String Addr = "", SName = "", FName = "";
                foreach (Customer o in qry3)
                {
                    Addr = o.Addr;
                    SName = o.ShortName;
                    FName = o.FullName;
                }

                //if (eventClass != null && eventClass != "" )
                if (eventClass != null && eventClass.Length > 1)
                {
                    qry2 = qry2.Where(x => x.EventClass == eventClass);
                }

                if (eventStatus != null && eventStatus != "" && eventStatus != "99")
                {
                    int teventStatus = Int32.Parse(eventStatus);
                    qry2 = qry2.Where(x => x.EventStatus == teventStatus);
                }
                else if (eventStatus == "99")
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus == "9");
                }

                if (userClass != null && userClass != "")
                {
                    if (user != null && user != "")
                    {
                        if (userClass == "1")       //開單人員
                            qry2 = qry2.Where(x => x.CreateUserID == user);
                        else if (userClass == "2")  //派工人員
                            qry2 = qry2.Where(x => x.AssignUserID == user);
                        else if (userClass == "3")  //責任區人員
                        {
                            int tempU = Int32.Parse(user);
                            qry2 = qry2.Where(x => x.WBSEventM.Customer1.SubArea.ResponsibleClass.ID == tempU); 
                        }
                        else if (userClass == "4")  //任務負責人
                        {
                            int tempU = Int32.Parse(user);
                            qry2 = qry2.Where(x => x.ResponsibleID == tempU);
                        }
                        else if (userClass == "5")  //執行人
                            qry2 = qry2.Where(x => x.ServiceCreateUserID == user);

                    }
                }
                
                if (dateClass != null && dateClass != "")
                {
                    

                    if (dateClass == "1")       //開單日期                        
                        qry2 = qry2.Where(x => x.CreateDateTime.Value.CompareTo(startDate) >= 0 && x.CreateDateTime.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "2")  //派工日期
                        qry2 = qry2.Where(x => x.AssignDT.Value.CompareTo(startDate) >= 0 && x.AssignDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "3")  //接受日期
                        qry2 = qry2.Where(x => x.RespondDT.Value.CompareTo(startDate) >= 0 && x.RespondDT.Value.CompareTo(endDate) <= 0 && x.RespondSW=="Y");
                    else if (dateClass == "4")  //到達日期
                        qry2 = qry2.Where(x => x.ServiceArriveDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "5")  //解決日期
                        qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                        //qry2 = qry2.Where(x => x.ServiceLeaveDT.Value.CompareTo(startDate) >= 0 && x.ServiceLeaveDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "6")  //結案日期
                        qry2 = qry2.Where(x => x.WBSEventM.CloseDT.Value.CompareTo(startDate) >= 0 && x.WBSEventM.CloseDT.Value.CompareTo(endDate) <= 0);
                        //qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "7")  //異動日期
                        qry2 = qry2.Where(x => x.ModifyDateTime.Value.CompareTo(startDate) >= 0 && x.ModifyDateTime.Value.CompareTo(endDate) <= 0);
                }

                if (childCaseID != null && childCaseID != "")
                {
                    if (childCaseID == "M")
                        qry2 = qry2.Where(x => x.ChildCaseID == 1);
                    else
                        qry2 = qry2.Where(x => x.ChildCaseID != 1);
                }
                foreach (WBSEventC c in qry2)
                {

                    String ProductNote = "", ItemNote = "", QuestionNote = "";
                    var qry4 = db.ProductClass.Where(x => x.ProductClassID == c.ProductClass);
                    foreach (ProductClass o in qry4)
                    {
                        ProductNote = o.Note;
                    }

                    var qry5 = db.ItemClass.Where(x => x.ItemClassID == c.ItemClass);
                    foreach (ItemClass o in qry5)
                    {
                        ItemNote = o.Note;
                    }

                    var qry6 = db.QuestionClass.Where(x => x.QuestionClassID == c.QuestionClass);
                    foreach (QuestionClass o in qry6)
                    {
                        QuestionNote = o.Note;
                    }


                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >= 10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                    v.EventStatus = c.EventStatus;
                    
                    if(v.EventStatus == 0)
                        v.EventStatusStr = "00.已刪除";
                    else if(v.EventStatus == 11)
                        v.EventStatusStr = "11.已開單未派工";
                    else if(v.EventStatus == 20)
                        v.EventStatusStr = "20.已拒絕待重派";
                    else if(v.EventStatus == 21)
                        v.EventStatusStr = "21.已派工未接受";
                    else if(v.EventStatus == 30)
                        v.EventStatusStr = "30.已接受未排程";
                    else if(v.EventStatus == 31)
                        v.EventStatusStr = "31.已接受已排程";
                    else if(v.EventStatus == 41)
                        v.EventStatusStr = "41.已到達未離開";
                    else if(v.EventStatus == 42)
                        v.EventStatusStr = "42.已離開待附件";
                    else if(v.EventStatus == 46)
                        v.EventStatusStr = "46.已解決未審核";
                    else if(v.EventStatus == 50)
                        v.EventStatusStr = "50.已解決已審核";



                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = Addr;
                    v.CustomerSName = SName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = ProductNote;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = ItemNote;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = QuestionNote;
                    v.QuestionNoteAll = ProductNote + "-" + ItemNote + "-" + QuestionNote;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("yyyy/MM/dd HH:mm");
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    if (c.ModifyDateTime != null)
                        v.ChgDTStr = c.ModifyDateTime.Value.ToString("yyyy/MM/dd HH:mm");
                    v.ModifyUserID = c.ModifyUserID;
                    if (c.AssignDT != null)
                        v.AssignDTStr = c.AssignDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.AssignUserID != null)
                        v.AssignUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                    if(c.ResponsibleID != null)
                        v.ResponsibleUserName = c.ResponsibleClass.UserData2.UserName;
                    if (c.RespondSW == "Y")
                        v.ConfirmDTStr = c.RespondDT.Value.ToString("yyyy/MM/dd HH:mm");
                    else
                        v.ConfirmDTStr = "";
                    if (c.ServiceArriveDT != null)
                        v.ArriveDTStr = c.ServiceArriveDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.QuestionFinishDT != null)
                        v.SolveDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                        //v.CloseDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                    //if (c.ServiceLeaveDT != null)
                    //    v.SolveDTStr = c.ServiceLeaveDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.WBSEventM.CloseDT != null)
                    {
                        v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("yyyy/MM/dd HH:mm");
                        v.EventStatusStr = "99.已結案";
                    }

                    v.CGroupSName = c.WBSEventM.Customer1.CustomerGroup.CGroupID + " : " + c.WBSEventM.Customer1.CustomerGroup.CGroupShortName;

                    //已開立時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);
                    //v.ServiceDT = Convert.ToDateTime(diff1.ToString());
                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                    TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                    v.OverTime = "";
                    if (diff1.CompareTo(duration) > 0)
                        v.OverTime = "逾時";


                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                    //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                    //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();

                    ret.Add(v);
                }
            }
            return ret.AsQueryable();
        }
        //我的工作
        public IQueryable<WBSEventViewModel> MyJobSearch(string type, string dateClass, DateTime startDate, DateTime endDate, string uid)
        {
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();

            var qry = db.WBSEventM.Where(x => x.CaseID != 0);

            foreach (WBSEventM m in qry)
            {

                //var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID && x.EventStatus != 0 && x.EventStatus < 30);
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID);

                if (type.Equals("1"))
                    qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus < 50);
                else if (type.Equals("2"))
                    qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus < 50);
                else if (type.Equals("3"))
                {
                    qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus <= 50);
                    qry2 = qry2.Where(x => x.CreateUserID == uid || x.AssignUserID == uid || x.ServiceCreateUserID == uid || x.ResponsibleClass.UserID == uid);
                }

                String Addr = "", SName = "", FName = "";

                Addr = m.Customer1.Addr;
                SName = m.Customer1.ShortName;
                FName = m.Customer1.FullName;

                if (dateClass != null && dateClass != "")
                {
                    if (dateClass == "1")       //開單日期                        
                        qry2 = qry2.Where(x => x.CreateDateTime.Value.CompareTo(startDate) >= 0 && x.CreateDateTime.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "2")  //派工日期
                        qry2 = qry2.Where(x => x.AssignDT.Value.CompareTo(startDate) >= 0 && x.AssignDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "3")  //接受日期
                        qry2 = qry2.Where(x => x.RespondDT.Value.CompareTo(startDate) >= 0 && x.RespondDT.Value.CompareTo(endDate) <= 0 && x.RespondSW == "Y");
                    else if (dateClass == "4")  //到達日期
                        qry2 = qry2.Where(x => x.ServiceArriveDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "5")  //解決日期
                        qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                    //qry2 = qry2.Where(x => x.ServiceLeaveDT.Value.CompareTo(startDate) >= 0 && x.ServiceLeaveDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "6")  //結案日期
                        qry2 = qry2.Where(x => x.WBSEventM.CloseDT.Value.CompareTo(startDate) >= 0 && x.WBSEventM.CloseDT.Value.CompareTo(endDate) <= 0);
                    //qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0);
                    else if (dateClass == "7")  //異動日期
                        qry2 = qry2.Where(x => x.ModifyDateTime.Value.CompareTo(startDate) >= 0 && x.ModifyDateTime.Value.CompareTo(endDate) <= 0);
                }

                foreach (WBSEventC c in qry2)
                {
                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >= 10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                    v.EventStatus = c.EventStatus;

                    if (v.EventStatus == 0)
                        v.EventStatusStr = "00.已刪除";
                    else if (v.EventStatus == 11)
                        v.EventStatusStr = "11.已開單未派工";
                    else if (v.EventStatus == 20)
                        v.EventStatusStr = "20.已拒絕待重派";
                    else if (v.EventStatus == 21)
                        v.EventStatusStr = "21.已派工未接受";
                    else if (v.EventStatus == 30)
                        v.EventStatusStr = "30.已接受未排程";
                    else if (v.EventStatus == 31)
                        v.EventStatusStr = "31.已接受已排程";
                    else if (v.EventStatus == 41)
                        v.EventStatusStr = "41.已到達未離開";
                    else if (v.EventStatus == 42)
                        v.EventStatusStr = "42.已離開待附件";
                    else if (v.EventStatus == 46)
                        v.EventStatusStr = "46.已解決未審核";
                    else if (v.EventStatus == 50)
                        v.EventStatusStr = "50.已解決已審核";

                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = Addr;
                    v.CustomerSName = SName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = c.ProductClass1.Note;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = c.ItemClass1.Note;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = c.QuestionClass1.Note;
                    v.QuestionNoteAll = c.ProductClass1.Note + "-" + c.ItemClass1.Note + "-" + c.QuestionClass1.Note;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("yyyy/MM/dd HH:mm");
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    if (c.ModifyDateTime != null)
                        v.ChgDTStr = c.ModifyDateTime.Value.ToString("yyyy/MM/dd HH:mm");
                    v.ModifyUserID = c.ModifyUserID;
                    if (c.AssignDT != null)
                        v.AssignDTStr = c.AssignDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.AssignUserID != null)
                        v.AssignUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                    if (c.ResponsibleID != null)
                        v.ResponsibleUserName = c.ResponsibleClass.UserData2.UserName;
                    if (c.RespondSW == "Y")
                        v.ConfirmDTStr = c.RespondDT.Value.ToString("yyyy/MM/dd HH:mm");
                    else
                        v.ConfirmDTStr = "";
                    if (c.ServiceArriveDT != null)
                        v.ArriveDTStr = c.ServiceArriveDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.QuestionFinishDT != null)
                        v.SolveDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.WBSEventM.CloseDT != null)
                    {
                        v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("yyyy/MM/dd HH:mm");
                        v.EventStatusStr = "99.已結案";
                    }
                    v.CGroupSName = c.WBSEventM.Customer1.CustomerGroup.CGroupID + " : " + c.WBSEventM.Customer1.CustomerGroup.CGroupShortName;

                    //已開單時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);

                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                    TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                    v.OverTime = "";
                    if (diff1.CompareTo(duration) > 0)
                        v.OverTime = "逾時";

                    //v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;

                    Boolean isAbnormal = false;
                    if (c.EventStatus == 41 && c.ScheduleEndDT.Value.CompareTo(DateTime.Now) < 0)
                    {
                        v.AbnormalReason = "逾時未離開";
                        isAbnormal = true;
                    }
                    else if (c.EventStatus == 31 && c.ScheduleStartDT.Value.CompareTo(DateTime.Now) < 0)
                    {
                        v.AbnormalReason = "逾時未到達";
                        isAbnormal = true;
                    }
                    //AbnormalReason //異常狀態
                    if (type != "2")
                        ret.Add(v);
                    else
                    {
                        if (isAbnormal)
                            ret.Add(v);
                    }
                }
            }

            return ret.AsQueryable();
        }
        //建立後續叫修單
        public string[] FollowUpCreate(WBSEventViewModel wBSEventViewModel)
        {
            string[] ret = new string[3];

            ret[0] = "false";
            ret[1] = "";
            ret[2] = "";    //area
            int  num = 0, childCaseID = 0;                        
            
            //string groupSW = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventViewModel.CustomerRef).Select(x => x.GroupSW).First();

            if (wBSEventViewModel.ExpectArriveDTStr == null)
                wBSEventViewModel.ExpectArriveDTStr = "19000101 00:01";
            if (wBSEventViewModel.ExpectFinishDTStr == null)
                wBSEventViewModel.ExpectFinishDTStr = "19000101 00:01";
            wBSEventViewModel.ExpectArriveDT = DateTime.ParseExact(wBSEventViewModel.ExpectArriveDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            wBSEventViewModel.ExpectFinishDT = DateTime.ParseExact(wBSEventViewModel.ExpectFinishDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);

            try
            {
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
                WBSEventC oldEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);
                wBSEventM.CaseMStatus = "5";    //5為部分子單已解決
                num = db.WBSEventC.AsEnumerable().Select(x => x.Num).DefaultIfEmpty(0).Max(x => x) + 1;
                childCaseID = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == wBSEventM.CaseID).Select(x => x.ChildCaseID).DefaultIfEmpty(0).Max(x => x) + 1;
                ret[2] = GetCustomerArea(wBSEventM.CustomerRef);

                WBSEventC wBSEventC = new WBSEventC();
                ret[1] = num.ToString();
                wBSEventC.Num = num;
                wBSEventC.MomCaseID = oldEventC.MomCaseID;
                wBSEventC.ChildCaseID = childCaseID;
                wBSEventViewModel.WBSCaseNumberC = (wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString();
                wBSEventC.EventClass = wBSEventViewModel.EventClass;
                wBSEventC.ProductClass = oldEventC.ProductClass;
                wBSEventC.ItemClass = oldEventC.ItemClass;
                wBSEventC.QuestionClass = oldEventC.QuestionClass;
                wBSEventC.QuestionGrade = oldEventC.QuestionGrade;
                wBSEventC.QuestionServiceHours = oldEventC.QuestionServiceHours;
                wBSEventC.QuestionDescription = wBSEventViewModel.QuestionDescription;
                wBSEventC.QuestionCreateUserID = wBSEventViewModel.QuestionCreateUserID;
                wBSEventC.QuestionCreateDateTime = DateTime.Now;
                wBSEventC.ExpectArriveDateTime = wBSEventViewModel.ExpectArriveDT;
                wBSEventC.ExpectFinishDateTime = wBSEventViewModel.ExpectFinishDT;
                wBSEventC.ExpectArriveSW = wBSEventViewModel.ExpectArriveSW;
                //wBSEventC.DeleteMarkSW = wBSEventViewModel.DeleteMarkSW;
                //wBSEventC.DeleteReason = wBSEventViewModel.DeleteReason;
                //wBSEventC.DeleteMarkUserID = wBSEventViewModel.DeleteMarkUserID;
                //wBSEventC.DeleteMarkDateTime = wBSEventViewModel.DeleteMarkDT;
                wBSEventC.CreateDateTime = DateTime.Now;
                wBSEventC.CreateUserID = wBSEventViewModel.CreateUserID;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.CreateUserID;
                
                wBSEventC.SugProvideSpareMach = "F";
                wBSEventC.SugRetrieveSpareMach = "F";
                wBSEventC.SugRetrieveUserMach = "F";
                wBSEventC.SugReturnUserMach = "F";
                wBSEventC.EventStatus = 11; //11為問題已開立
                
                //db.WBSEventM.Add(wBSEventM);
                db.WBSEventC.Add(wBSEventC);
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }
            return ret;

        }
        //建立新叫修單
        public string[] Create(WBSEventViewModel wBSEventViewModel)
        {
            string[] ret = new string[3];
            ret[0] = "false";
            ret[1] = "";
            ret[2] = "";    //area
            int casecode = 0, caseID = 0, num = 0, childCaseID = 0;
            casecode = db.WBSEventM.AsEnumerable().Where(x => x.CaseClass == "C" && x.CaseDate == DateTime.Now.ToString("yyyyMMdd")).Select(x => x.CaseCode).DefaultIfEmpty(0).Max(x => x) + 1;
            caseID = db.WBSEventM.AsEnumerable().Select(x => x.CaseID).DefaultIfEmpty(0).Max(x => x) + 1;
            num = db.WBSEventC.AsEnumerable().Select(x => x.Num).DefaultIfEmpty(0).Max(x => x) + 1;
            childCaseID = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == caseID).Select(x => x.ChildCaseID).DefaultIfEmpty(0).Max(x => x) + 1;
            int questionGrade = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionGrade).First();
            int serviceHours = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionServiceHours).First();
            string groupSW = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventViewModel.CustomerRef).Select(x => x.GroupSW).First();

            if (wBSEventViewModel.ExpectArriveDTStr == null)
                wBSEventViewModel.ExpectArriveDTStr = "19000101 00:01";
            if (wBSEventViewModel.ExpectFinishDTStr == null)
                wBSEventViewModel.ExpectFinishDTStr = "19000101 00:01";
            wBSEventViewModel.ExpectArriveDT = DateTime.ParseExact(wBSEventViewModel.ExpectArriveDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            wBSEventViewModel.ExpectFinishDT = DateTime.ParseExact(wBSEventViewModel.ExpectFinishDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            ret[2] = GetCustomerArea(wBSEventViewModel.CustomerRef);


            try
            {
                WBSEventM wBSEventM = new WBSEventM();
                wBSEventM.CaseID = caseID;
                //wBSEventM.CaseClass = wBSEventViewModel.WBSCaseNumberM.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[0];
                //wBSEventM.CaseClass = wBSEventViewModel.WBSCaseNumberM.Substring(0, 1);
                wBSEventM.CaseClass = "C";
                //wBSEventM.CaseDate = wBSEventViewModel.WBSCaseNumberM.Substring(1, 8);
                wBSEventM.CaseDate = DateTime.Now.ToString("yyyyMMdd");
                wBSEventM.CaseCode = casecode;
                wBSEventViewModel.WBSCaseNumberM = wBSEventM.CaseClass + wBSEventM.CaseDate + "-";
                if (wBSEventM.CaseCode < 10)
                    wBSEventViewModel.WBSCaseNumberM += "0000" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 100 && wBSEventM.CaseCode >= 10)
                    wBSEventViewModel.WBSCaseNumberM += "000" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 1000 && wBSEventM.CaseCode >= 100)
                    wBSEventViewModel.WBSCaseNumberM += "00" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 10000 && wBSEventM.CaseCode >= 1000)
                    wBSEventViewModel.WBSCaseNumberM += "0" + wBSEventM.CaseCode.ToString();
                else
                    wBSEventViewModel.WBSCaseNumberM += wBSEventM.CaseCode.ToString();
                wBSEventM.CustomerRef = wBSEventViewModel.CustomerRef;
                wBSEventM.CustomerUserID = wBSEventViewModel.CustomerUserID;
                wBSEventM.CustomerUserName = wBSEventViewModel.CustomerUserName;
                wBSEventM.CustomerUserPhone1 = wBSEventViewModel.CustomerUserPhone1;
                wBSEventM.CustomerUserPhone2 = wBSEventViewModel.CustomerUserPhone2;
                //20150811新增-Hsiuyang
                if (wBSEventViewModel.ChangeAddr != null)
                    if (wBSEventViewModel.ChangeAddr.Trim().Length > 0)
                        wBSEventM.CustomerAddr = wBSEventViewModel.ChangeAddr;
                wBSEventM.SpareMach = "R";      //預設無借出備機
                wBSEventM.UserMach = "R";       //預設無取回客戶機器
                wBSEventM.CaseMStatus = "1";    //1為開立新問題

                WBSEventC wBSEventC = new WBSEventC();
                ret[1] = num.ToString();
                wBSEventC.Num = num;
                wBSEventC.MomCaseID = caseID;
                wBSEventC.ChildCaseID = childCaseID;
                wBSEventViewModel.WBSCaseNumberC = (wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString();
                wBSEventC.EventClass = "C01";
                wBSEventC.ProductClass = Int32.Parse(wBSEventViewModel.ProductClass);
                wBSEventC.ItemClass = Int32.Parse(wBSEventViewModel.ItemClass);
                wBSEventC.QuestionClass = Int32.Parse(wBSEventViewModel.QuestionClass);
                wBSEventC.QuestionGrade = questionGrade;
                wBSEventC.QuestionServiceHours = serviceHours;
                wBSEventC.QuestionDescription = wBSEventViewModel.QuestionDescription;                
                wBSEventC.QuestionCreateUserID = wBSEventViewModel.QuestionCreateUserID;
                wBSEventC.QuestionCreateDateTime = DateTime.Now;
                wBSEventC.ExpectArriveDateTime = wBSEventViewModel.ExpectArriveDT;
                wBSEventC.ExpectFinishDateTime = wBSEventViewModel.ExpectFinishDT;
                wBSEventC.ExpectArriveSW = wBSEventViewModel.ExpectArriveSW;
                wBSEventC.DeleteMarkSW = wBSEventViewModel.DeleteMarkSW;
                wBSEventC.DeleteReason = wBSEventViewModel.DeleteReason;
                wBSEventC.DeleteMarkUserID = wBSEventViewModel.DeleteMarkUserID;
                wBSEventC.DeleteMarkDateTime = wBSEventViewModel.DeleteMarkDT;
                wBSEventC.CreateDateTime = DateTime.Now;
                wBSEventC.CreateUserID = wBSEventViewModel.CreateUserID;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.CreateUserID;
                //wBSEventC.ModifyDateTime = wBSEventViewModel.ModifyDT;
                //wBSEventC.ModifyUserID = wBSEventViewModel.ModifyUserID;
                //20150811新增-Hsiuyang
                wBSEventC.SugProvideSpareMach = wBSEventViewModel.SugProvideSpareMach;
                wBSEventC.SugRetrieveSpareMach = wBSEventViewModel.SugRetrieveSpareMach;
                wBSEventC.SugRetrieveUserMach = wBSEventViewModel.SugRetrieveUserMach;
                wBSEventC.SugReturnUserMach = wBSEventViewModel.SugReturnUserMach;
                wBSEventC.EventStatus = 11; //11為問題已開立
                //20150813新增-Hsiuyang
                if (wBSEventViewModel.Closed == "T") //線上處理結案影響
                {
                    wBSEventM.CaseMStatus = "9";    //9為問題已結案
                    wBSEventM.CloseDT = DateTime.Now;
                    wBSEventC.EventStatus = 50;     //50為任務已解決(維修附件上傳)
                    wBSEventC.QuestionFinishSW = "Y";
                    wBSEventC.QuestionFinishDT = DateTime.Now;
                    wBSEventC.ServiceReport = wBSEventViewModel.AssignDescription;  //當結案時解決方式即為服務報告
                }
                wBSEventC.AssignDescription = wBSEventViewModel.AssignDescription;  //解決方式(派單)描述
                

                //20150812新增-Hsiuyang-SugProduct建議部分
                JArray SugProduct = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaterialJson);
                for (int i = 0; i < SugProduct.Count; i++)
                {
                    SugProduct sugProduct = new SugProduct();
                    sugProduct.CID = wBSEventC.Num;
                    sugProduct.Class = Int32.Parse(SugProduct[i]["Class"].ToString());
                    //sugProduct.Class = Int32.Parse(SugProduct[i][0].ToString());
                    //if (SugProduct[i][1].ToString() == "")
                    if (SugProduct[i]["ProductNum"].ToString() == "")
                        sugProduct.ProductName = SugProduct[i]["ProductName"].ToString();
                    //sugProduct.ProductName = SugProduct[i][2].ToString();
                    else
                        sugProduct.ProductNum = Int32.Parse(SugProduct[i]["ProductNum"].ToString());
                    //sugProduct.ProductNum = Int32.Parse(SugProduct[i][1].ToString());

                    db.SugProduct.Add(sugProduct);
                }
                //20150813新增-Hsiuyang-解決方式知識庫附件
                JArray KnowledgeData = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.KnowledgeJson);
                for (int i = 0; i < KnowledgeData.Count; i++)
                {
                    Files knowledgefile = new Files();
                    knowledgefile.CID = wBSEventC.Num;
                    knowledgefile.Class = 3;
                    knowledgefile.FileAddr = "";
                    knowledgefile.FileName = "";
                    //knowledgefile.KnowledgeID = Int32.Parse(KnowledgeData[i][0].ToString());
                    knowledgefile.KnowledgeID = Int32.Parse(KnowledgeData[i]["KnowledgeID"].ToString());
                    db.Files.Add(knowledgefile);
                }
                //20150814新增-Hsiuyang-執行預先保養單
                JArray maintainCases = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaintainCaseJson);
                for (int i = 0; i < maintainCases.Count; i++)
                {
                    EventRelation maintainCase = new EventRelation();
                    maintainCase.CID = wBSEventC.Num;
                    maintainCase.RelationCID = Int32.Parse(maintainCases[i]["cID"].ToString());

                    db.EventRelation.Add(maintainCase);
                }



                db.WBSEventM.Add(wBSEventM);
                db.WBSEventC.Add(wBSEventC);
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }
            return ret;
        }
        public ActionResult EventC02Detail(WBSEventViewModel wbsModel)
        {
            ViewBag.type = wbsModel.type;   //0:儲存處理說明 1:完成報價 2:客戶回覆轉派工 3:客戶回覆(結案)

           if (ModelState.IsValid)
            {

                // 先取得該使用者的 FormsIdentity
                FormsIdentity id = (FormsIdentity)User.Identity;
                // 再取出使用者的 FormsAuthenticationTicket
                FormsAuthenticationTicket ticket = id.Ticket;

                wbsModel.ModifyUserID = ticket.Name;

                string[] ret;
                string msg, cu;
                if (wbsModel.type == 0) //儲存處理說明(只修改服務報告、修改日期、修改時間)
                {
                    ret = wBSEventRepository.ChangeServiceReport(wbsModel);
                    if (ret[0] == "true")
                    {
                        cu = wBSEventRepository.GetCShortNameAndProductName(wbsModel.C_ID);
                        msg = cu + "-處理說明更新成功,單號:" + ret[1];
                        //msg = "任務" + ret[1] + "處理說明更新成功";
                        return RedirectToAction("EventC02Main", "WBSEvent", new { data = msg });
                    }
                }
                else if (wbsModel.type == 4) //排程
                {
                    ret = wBSEventRepository.ChangeScheduleDT(wbsModel);
                    if (ret[0] == "true")
                    {
                        cu = wBSEventRepository.GetCShortNameAndProductName(wbsModel.C_ID);
                        msg = cu + "-排程成功,單號:" + ret[1];                        
                        return RedirectToAction("EventC02Main", "WBSEvent", new { data = msg });
                    }
                }
                else if (wbsModel.type == 5) //已交付廠商待回送
                {

                    ret = wBSEventRepository.ChangeC02to43(wbsModel);
                    if (ret[0] == "true")
                    {
                        cu = wBSEventRepository.GetCShortNameAndProductName(wbsModel.C_ID);
                        msg = cu + "-已交付廠商待回送,單號:" + ret[1];
                        return RedirectToAction("EventC02Main", "WBSEvent", new { data = msg });
                    }
                }
                else if (wbsModel.type == 2 || wbsModel.type == 3)    //2:檢測/完修(轉派工) 3:完修(結案)
                {
                    wbsModel.EventStatus = 50;
                    if (wbsModel.type == 3)
                        ret = wBSEventRepository.FinishQuotation(wbsModel, true);
                    else
                        ret = wBSEventRepository.FinishQuotation(wbsModel, false);
                    if (ret[0] != "false")
                    {
                        msg = ret[0];
                        if (wbsModel.type == 3)
                            return RedirectToAction("EventC02Main", "WBSEvent", new { data = msg });
                        else///WBSEvent/NewCase?type=5&&mid=4131&&cid=9167
                            return RedirectToAction("NewCase", "WBSEvent", new { data = msg, type = 5, mid = wbsModel.M_ID, cid = wbsModel.C_ID });
                    }
                }

            }
            //return RedirectToAction("RegSuccess", "ActivityReg", new { data = msg });
            return View();
        }
        //案件檢視
        public IQueryable<WBSEventViewModel> EventSearch(String NotClose, String eventStatus, String eventClass, String userClass, String user, String areaID, String childCaseID, String CGroupSW, String CGroupID, String CSName, String dateClass, DateTime startDate, DateTime endDate, String Etype)
        {
            List<AlertDetailSettingViewModel> alertMList = new List<AlertDetailSettingViewModel>();            
            var Aqry = db.AlertDetailSetting;
            foreach (AlertDetailSetting o in Aqry)
            {
                AlertDetailSettingViewModel a = new AlertDetailSettingViewModel();
                a.EventClass = o.EventClass;
                a.AlertEvent = o.AlertEvent;
                a.FirstTime = o.FirstTime;
                alertMList.Add(a);
            }            

            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();
            endDate = endDate.AddDays(1);

            var qry = db.WBSEventM.Where(x=>x.CaseID!=0);

            //if (eventClass != null && eventClass != "")
            //{
            //    String temp = eventClass.First().ToString();
            //    qry = qry.Where(x => x.CaseClass == temp);
            //}

            if (areaID != null && areaID != "" && areaID != "12")   //12為不分區
            {
                qry = qry.Where(x => x.Customer1.SubArea.AreaID == areaID);
            }

            if (CGroupSW != null && CGroupSW != "")
            {
                qry = qry.Where(x => x.Customer1.GroupSW == CGroupSW);
            }

            if (CGroupID != null && CGroupID != "")
            {
                qry = qry.Where(x => x.Customer1.GroupID == CGroupID);
            }

            if (CSName != null && CSName != "")
            {
                int t = Int32.Parse(CSName);
                qry = qry.Where(x => x.CustomerRef == t);
            }

            //var qry = db.WBSEventM.Where(x => x.CaseClass == "C");
            foreach (WBSEventM m in qry)
            {
                
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID);
                
                if (eventClass != null && eventClass.Length > 1)
                {
                    qry2 = qry2.Where(x => x.EventClass == eventClass);
                }

                if (NotClose == "true")
                    qry2 = qry2.Where(x => x.EventStatus >= 11 && x.EventStatus < 50);

                if (Etype == "C02" || Etype == "C03")
                    qry2 = qry2.Where(x => x.EventStatus >= 30 && x.EventStatus < 50);

                if (eventStatus != null && eventStatus != "" && eventStatus != "99")
                {
                    int teventStatus = Int32.Parse(eventStatus);
                    //20160520改
                    qry2 = qry2.Where(x => x.EventStatus == teventStatus && x.WBSEventM.CaseMStatus != "9");
                }
                else if (eventStatus == "99")
                {
                    qry2 = qry2.Where(x => x.WBSEventM.CaseMStatus == "9");
                }

                if (userClass != null && userClass != "")
                {
                    if (user != null && user != "")
                    {
                        if (userClass == "1")       //開單人員
                            qry2 = qry2.Where(x => x.CreateUserID == user);
                        else if (userClass == "2")  //派工人員
                            qry2 = qry2.Where(x => x.AssignUserID == user);
                        else if (userClass == "3")  //責任區人員
                        {
                            int tempU = Int32.Parse(user);
                            qry2 = qry2.Where(x => x.WBSEventM.Customer1.SubArea.ResponsibleClass.ID == tempU); 
                        }
                        else if (userClass == "4")  //執行人
                        {
                            int tempU = Int32.Parse(user);
                            qry2 = qry2.Where(x => x.ResponsibleID == tempU);
                        }
                        else if (userClass == "5")  //實際執行人
                            qry2 = qry2.Where(x => x.ServiceCreateUserID == user);
                        else if (userClass == "6") //執行人或實際執行人
                        {
                            int tempU = Int32.Parse(user);
                            string uid = db.ResponsibleClass.Find(tempU).UserID;
                            qry2 = qry2.Where(x => (x.ServiceCreateUserID == uid && x.EventStatus >= 41) || (x.ResponsibleID == tempU && x.EventStatus <41));
                        }
                    }
                }
                
                if (dateClass != null && dateClass != "")
                {
                    switch(dateClass){
                        case "1":   //開單日期
                            qry2 = qry2.Where(x => x.CreateDateTime.Value.CompareTo(startDate) >= 0 && x.CreateDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "2":   //派工日期
                            qry2 = qry2.Where(x => x.AssignDT.Value.CompareTo(startDate) >= 0 && x.AssignDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "3":   //接受日期
                            qry2 = qry2.Where(x => x.RespondDT.Value.CompareTo(startDate) >= 0 && x.RespondDT.Value.CompareTo(endDate) <= 0 && x.RespondSW == "Y");
                            break;
                        case "4":   //到達日期
                            qry2 = qry2.Where(x => x.ServiceArriveDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "5":   //解決日期
                            //qry2 = qry2.Where(x => x.ServiceLeaveDT.Value.CompareTo(startDate) >= 0 && x.ServiceLeaveDT.Value.CompareTo(endDate) <= 0);
                            qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                            break;
                        case "6":   //結案日期
                            qry2 = qry2.Where(x => x.WBSEventM.CloseDT.Value.CompareTo(startDate) >= 0 && x.WBSEventM.CloseDT.Value.CompareTo(endDate) <= 0);
                            //qry2 = qry2.Where(x => x.QuestionFinishDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "7":   //異動日期
                            qry2 = qry2.Where(x => x.ModifyDateTime.Value.CompareTo(startDate) >= 0 && x.ModifyDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "8":   //應到達日期(期望)
                            qry2 = qry2.Where(x => x.ExpectArriveDateTime.Value.CompareTo(startDate) >= 0 && x.ExpectArriveDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "9":   //應完修日期(期望)
                            qry2 = qry2.Where(x => x.ExpectFinishDateTime.Value.CompareTo(startDate) >= 0 && x.ExpectFinishDateTime.Value.CompareTo(endDate) <= 0);
                            break;
                        case "10":   //預計到達日期
                            qry2 = qry2.Where(x => x.ScheduleStartDT.Value.CompareTo(startDate) >= 0 && x.ScheduleStartDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "11":   //系統到達日期
                            qry2 = qry2.Where(x => x.ServiceArriveSysDT.Value.CompareTo(startDate) >= 0 && x.ServiceArriveSysDT.Value.CompareTo(endDate) <= 0);
                            break;
                        case "12":   //系統解決日期
                            qry2 = qry2.Where(x => x.QuestionFinishSysDT.Value.CompareTo(startDate) >= 0 && x.QuestionFinishSysDT.Value.CompareTo(endDate) <= 0 && x.WBSEventM.CloseDT == null);
                            break;
                    }
                }

                if (childCaseID != null && childCaseID != "")
                {
                    if (childCaseID == "M")
                        qry2 = qry2.Where(x => x.ChildCaseID == 1);
                    else
                        qry2 = qry2.Where(x => x.ChildCaseID != 1);
                }
                foreach (WBSEventC c in qry2)
                {
                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >= 10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                    v.EventStatus = c.EventStatus;

                    v.EventStatusStr = (v.EventStatus == 0) ? "0" + v.EventStatus.ToString() : v.EventStatus.ToString();
                    v.EventStatusStr += "." + GetEventStatusStr(v.EventStatus);

                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = m.Customer1.Addr;
                    if (m.CustomerAddr != "" && m.CustomerAddr != null)
                        v.CustomerAddr = m.CustomerAddr;
                    v.CustomerSName = m.Customer1.ShortName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone = m.CustomerUserPhone1;
                    if (m.CustomerUserPhone2 != null && m.CustomerUserPhone2 != "")
                        v.CustomerUserPhone += " /" + m.CustomerUserPhone2;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = c.ProductClass1.Note;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = c.ItemClass1.Note;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = c.QuestionClass1.Note;
                    v.QuestionNoteAll = c.ProductClass1.Note + "-" + c.ItemClass1.Note + "-" + c.QuestionClass1.Note;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";
                    v.HasAssignActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 2).Count() > 0)
                        v.HasAssignActtachment = "@";

                    v.HasKnowledge = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 3).Count() > 0)
                        v.HasKnowledge = "@";

                    v.HasHyperlink = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 9).Count() > 0)
                        v.HasHyperlink = "@";

                    v.ExpectArriveDTStr = (c.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.ExpectFinishDTStr = (c.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    if (c.ExpectArriveSW == "1")
                        v.ExpectArriveSWStr = "合約規定";
                    else if (c.ExpectArriveSW == "2")
                        v.ExpectArriveSWStr = "建議期望";
                    else if (c.ExpectArriveSW == "3")
                        v.ExpectArriveSWStr = "客戶指定";
                    else if (c.ExpectArriveSW == "4")
                        v.ExpectArriveSWStr = "自派新單";
                    else
                    {
                        v.ExpectArriveSWStr = "自行約定";
                        v.ExpectArriveDTStr = "請自行與客戶約定";
                        v.ExpectFinishDTStr = "請自行與客戶約定";
                    } 

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                    v.CreateYYYYStr = c.CreateDateTime.Value.Year.ToString();
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    if (c.ModifyDateTime != null)
                        v.ChgDTStr = c.ModifyDateTime.Value.ToString("MM/dd HH:mm");
                    v.ModifyUserID = c.ModifyUserID;
                    if (c.AssignDT != null)
                        v.AssignDTStr = c.AssignDT.Value.ToString("MM/dd HH:mm");
                    if (c.AssignUserID != null)
                        v.AssignUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                    if(c.ResponsibleID != null)
                        v.ResponsibleUserName = c.ResponsibleClass.Name + "-" + c.ResponsibleClass.UserData2.UserName;
                    if (c.RespondSW == "Y")
                        v.ConfirmDTStr = c.RespondDT.Value.ToString("MM/dd HH:mm");
                    else
                        v.ConfirmDTStr = "";

                    if (c.EventStatus >= 41)
                    {
                        if (c.ServiceModifyUserID != null)
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceModifyUserID).Select(x => x.UserName).First();
                        else if (c.ServiceCreateUserID != null)
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceCreateUserID).Select(x => x.UserName).First();
                        else
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    }

                    if (c.ServiceArriveSysDT != null)
                    {                        
                        v.ArriveDTStr = c.ServiceArriveDT.Value.ToString("MM/dd HH:mm");
                        v.ServiceArriveDT = c.ServiceArriveDT;
                        v.ArriveSysDTStr = c.ServiceArriveSysDT.Value.ToString("MM/dd HH:mm");
                    }
                    if (c.QuestionFinishSysDT != null)
                    {
                        v.SolveDTStr = c.QuestionFinishDT.Value.ToString("MM/dd HH:mm");
                        v.SolveSysDTStr = c.QuestionFinishSysDT.Value.ToString("MM/dd HH:mm");
                        v.QuestionFinishDT = c.QuestionFinishDT;
                    }

                    if (c.ExpectArriveDateTime != null)
                        v.ExArriveDTStr = c.ExpectArriveDateTime.Value.ToString("MM/dd HH:mm");
                    if (c.ExpectFinishDateTime != null)
                        v.ExFinishDTStr = c.ExpectFinishDateTime.Value.ToString("MM/dd HH:mm");
                    if (c.ScheduleStartDT != null)
                    {
                        v.SArriveDTStr = c.ScheduleStartDT.Value.ToString("MM/dd HH:mm");
                        v.ScheduleStartDT = c.ScheduleStartDT;
                    }

                    v.ServiceLeaveDT = c.ServiceLeaveDT;

                        //v.CloseDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                    //if (c.ServiceLeaveDT != null)
                    //    v.SolveDTStr = c.ServiceLeaveDT.Value.ToString("yyyy/MM/dd HH:mm");
                    if (c.WBSEventM.CloseDT != null)
                    {
                        v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("MM/dd HH:mm");
                        v.EventStatusStr = "99.已結案";
                    }
                    v.MaintainNum = "";
                    int maintainNum = db.EventRelation.Where(x => x.CID == c.Num).Count();
                    if (maintainNum != 0)
                        v.MaintainNum = maintainNum.ToString();

                    v.RespondReason = c.RespondReason;
                    if (m.Customer1.SubArea.ResponsibleID2 != null)
                    {
                        v.DefaultUserName2 = m.Customer1.SubArea.ResponsibleClass1.Name + "-" + m.Customer1.SubArea.ResponsibleClass1.UserData2.UserName;
                        //v.ResponsibleArea2 = m.Customer1.SubArea.SubAreaID;
                    }


                    v.CGroupSName = c.WBSEventM.Customer1.CustomerGroup.CGroupID + " : " + c.WBSEventM.Customer1.CustomerGroup.CGroupShortName;

                    //已開立時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);
                    //v.ServiceDT = Convert.ToDateTime(diff1.ToString());
                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                    TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                    v.OverTime = "";
                    if (diff1.CompareTo(duration) > 0)
                        v.OverTime = "逾時";


                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                    //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                    //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();
                    v.AreaID = m.Customer1.SubArea.AreaID;
                    v.AreaStr = m.Customer1.SubArea.Area.Name;

                    v.AbnormalReason = isAbnormal(c, alertMList);

                    if (Etype == "C02" || Etype == "C03")
                    {
                        int addday = db.SystemSetting.Where(x => x.isSysDefault == true).Select(x => x.Alert43Day).First();

                        if (db.SystemSetting.Where(x => x.EventClass == Etype).Count() > 0)
                            addday = db.SystemSetting.Where(x => x.EventClass == eventClass).Select(x => x.Alert43Day).First();

                        //if (c.ServiceLeaveDT != null)
                        if (c.EventStatus == 43)    //20161012 改只有43看的到提醒截止時間
                        {
                            v.FinishDTStr = c.ServiceLeaveDT.Value.ToString("MM/dd HH:mm");

                            if (c.ServiceLeaveSysDT != null)
                                v.FinishSysDTStr = c.ServiceLeaveSysDT.Value.ToString("MM/dd HH:mm");
                            if (c.ServiceLeaveDT.Value.AddDays(addday).CompareTo(DateTime.Now) < 0)
                            {
                                DateTime temp = c.ServiceLeaveDT.Value.AddDays(addday);
                                while (temp.CompareTo(DateTime.Now) < 0)
                                {
                                    temp = temp.AddDays(addday);
                                }
                                v.NextAlertDTStr = temp.ToString("MM/dd HH:mm");
                            }
                            else
                            {
                                v.NextAlertDTStr = c.ServiceLeaveDT.Value.AddDays(addday).ToString("MM/dd HH:mm");
                            }
                        }
                        //else
                        //{
                        //    if (c.CreateDateTime.Value.AddDays(3).CompareTo(DateTime.Now) < 0)
                        //    {
                        //        DateTime temp = c.CreateDateTime.Value.AddDays(3);
                        //        while(temp.CompareTo(DateTime.Now) < 0){
                        //            temp = temp.AddDays(3);
                        //        }
                        //            v.NextAlertDTStr = temp.ToString("MM/dd HH:mm");
                        //    }
                        //    else
                        //    {
                        //        v.NextAlertDTStr = c.CreateDateTime.Value.AddDays(3).ToString("MM/dd HH:mm");
                        //    }
                        //}
                    }

                    ret.Add(v);
                }
            }

            return ret.AsQueryable();
        }
        //客戶叫修服務-案件詳情讀取-手機轉派工專用(部分資料清空)
        public WBSEventViewModel ReadOneCase2(int mID)
        {
            WBSEventViewModel v = new WBSEventViewModel();
            WBSEventM M = db.WBSEventM.Find(mID);
            int temp = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == mID && x.ChildCaseID == 1).Select(x => x.Num).Max(x => x);
            WBSEventC C = db.WBSEventC.Find(temp);

            v.C_ID = C.Num;
            v.CustomerAddr = M.Customer1.Addr; 
            v.CustomerID = M.Customer1.CustomerID; 
            v.CustomerRef = M.CustomerRef;
            v.CustomerSName = M.Customer1.ShortName; 
            v.CustomerUserName = M.CustomerUserName;
            v.CustomerUserPhone1 = M.CustomerUserPhone1;
            v.CustomerUserPhone2 = M.CustomerUserPhone2;
            //20150811新增-Hsiuyang
            v.ChangeAddr = M.CustomerAddr;
            v.SpareMach = M.SpareMach;
            v.UserMach = M.UserMach;
            v.CaseMStatus = M.CaseMStatus;

            //v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.Name + "-" + M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.ResponsibleArea = M.Customer1.SubArea.SubAreaID;


            v.ItemClass = C.ItemClass.ToString();
            v.ProductNote = C.ProductClass1.Note; //db.ProductClass.AsEnumerable().Where(x => x.ProductClassID == C.ProductClass).Select(x => x.Note).First();
            v.ItemNote = C.ItemClass1.Note; //db.ItemClass.AsEnumerable().Where(x => x.ItemClassID == C.ItemClass).Select(x => x.Note).First();
            v.QuestionNote = C.QuestionClass1.Note; //db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == C.QuestionClass).Select(x => x.Note).First();

            v.M_ID = M.CaseID;
            v.ProductClass = C.ProductClass.ToString();
            v.QuestionClass = C.QuestionClass.ToString();            
            v.WBSCaseNumberC = (C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString();
            v.WBSCaseNumberM = M.CaseClass + M.CaseDate + "-";
            if (M.CaseCode < 10)
                v.WBSCaseNumberM += "0000" + M.CaseCode.ToString();
            else if (M.CaseCode < 100 && M.CaseCode >= 10)
                v.WBSCaseNumberM += "000" + M.CaseCode.ToString();
            else if (M.CaseCode < 1000 && M.CaseCode >= 100)
                v.WBSCaseNumberM += "00" + M.CaseCode.ToString();
            else if (M.CaseCode < 10000 && M.CaseCode >= 1000)
                v.WBSCaseNumberM += "0" + M.CaseCode.ToString();
            else
                v.WBSCaseNumberM += M.CaseCode.ToString();
            v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;

            return v;
        }
        //案件檢視ByCase
        public IQueryable<WBSEventViewModel> EventSearchByCase(String CaseNum, String MNum, String CNum)
        {
            List<AlertDetailSettingViewModel> alertMList = new List<AlertDetailSettingViewModel>();
            var Aqry = db.AlertDetailSetting;
            foreach (AlertDetailSetting o in Aqry)
            {
                AlertDetailSettingViewModel a = new AlertDetailSettingViewModel();
                a.EventClass = o.EventClass;
                a.AlertEvent = o.AlertEvent;
                a.FirstTime = o.FirstTime;
                alertMList.Add(a);
            }

            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();

            string caseClass = MNum.Substring(0, 1);
            string caseDate = MNum.Substring(1, 8);
            string caseCodeStr = MNum.Substring(9, 5);
            int caseCode = int.Parse(caseCodeStr);

            var qry = db.WBSEventM.Where(x => x.CaseClass == caseClass && x.CaseDate == caseDate && x.CaseCode == caseCode);
            foreach (WBSEventM m in qry)
            {                
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID);
                if (CNum != "")
                {
                    int tmp = int.Parse(CNum);
                    qry2 = qry2.Where(x => x.ChildCaseID == tmp);
                }
                foreach (WBSEventC c in qry2)
                {
                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >= 10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                    v.EventStatus = c.EventStatus;

                    v.EventStatusStr = (v.EventStatus == 0) ? "0" + v.EventStatus.ToString() : v.EventStatus.ToString();
                    v.EventStatusStr += "." + GetEventStatusStr(v.EventStatus);

                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = m.Customer1.Addr;
                    if (m.CustomerAddr != "" && m.CustomerAddr != null)
                        v.CustomerAddr = m.CustomerAddr;
                    v.CustomerSName = m.Customer1.ShortName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone = m.CustomerUserPhone1;
                    if (m.CustomerUserPhone2 != null && m.CustomerUserPhone2 != "")
                        v.CustomerUserPhone += " /" + m.CustomerUserPhone2;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = c.ProductClass1.Note;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = c.ItemClass1.Note;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = c.QuestionClass1.Note;
                    v.QuestionNoteAll = c.ProductClass1.Note + "-" + c.ItemClass1.Note + "-" + c.QuestionClass1.Note;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";
                    v.HasAssignActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 2).Count() > 0)
                        v.HasAssignActtachment = "@";

                    v.HasKnowledge = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 3).Count() > 0)
                        v.HasKnowledge = "@";

                    v.HasHyperlink = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 9).Count() > 0)
                        v.HasHyperlink = "@";

                    v.ExpectArriveDTStr = (c.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.ExpectFinishDTStr = (c.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    if (c.ExpectArriveSW == "1")
                        v.ExpectArriveSWStr = "合約規定";
                    else if (c.ExpectArriveSW == "2")
                        v.ExpectArriveSWStr = "建議期望";
                    else if (c.ExpectArriveSW == "3")
                        v.ExpectArriveSWStr = "客戶指定";
                    else if (c.ExpectArriveSW == "4")
                        v.ExpectArriveSWStr = "自派新單";
                    else
                    {
                        v.ExpectArriveSWStr = "自行約定";
                        v.ExpectArriveDTStr = "請自行與客戶約定";
                        v.ExpectFinishDTStr = "請自行與客戶約定";
                    }

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;
                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                    v.CreateYYYYStr = c.CreateDateTime.Value.Year.ToString();
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    if (c.ModifyDateTime != null)
                        v.ChgDTStr = c.ModifyDateTime.Value.ToString("MM/dd HH:mm");
                    v.ModifyUserID = c.ModifyUserID;
                    if (c.AssignDT != null)
                        v.AssignDTStr = c.AssignDT.Value.ToString("MM/dd HH:mm");
                    if (c.AssignUserID != null)
                        v.AssignUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                    if (c.ResponsibleID != null)
                        v.ResponsibleUserName = c.ResponsibleClass.Name + "-" + c.ResponsibleClass.UserData2.UserName;
                    if (c.RespondSW == "Y")
                        v.ConfirmDTStr = c.RespondDT.Value.ToString("MM/dd HH:mm");
                    else
                        v.ConfirmDTStr = "";

                    if (c.EventStatus >= 41)
                    {
                        if (c.ServiceModifyUserID != null)
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceModifyUserID).Select(x => x.UserName).First();
                        else if (c.ServiceCreateUserID != null)
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.ServiceCreateUserID).Select(x => x.UserName).First();
                        else
                            v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    }

                    if (c.ServiceArriveSysDT != null)
                    {
                        v.ArriveDTStr = c.ServiceArriveDT.Value.ToString("MM/dd HH:mm");
                        v.ServiceArriveDT = c.ServiceArriveDT;
                        v.ArriveSysDTStr = c.ServiceArriveSysDT.Value.ToString("MM/dd HH:mm");
                    }
                    if (c.QuestionFinishSysDT != null)
                    {
                        v.SolveDTStr = c.QuestionFinishDT.Value.ToString("MM/dd HH:mm");
                        v.SolveSysDTStr = c.QuestionFinishSysDT.Value.ToString("MM/dd HH:mm");
                        v.QuestionFinishDT = c.QuestionFinishDT;
                    }

                    if (c.ExpectArriveDateTime != null)
                        v.ExArriveDTStr = c.ExpectArriveDateTime.Value.ToString("MM/dd HH:mm");
                    if (c.ExpectFinishDateTime != null)
                        v.ExFinishDTStr = c.ExpectFinishDateTime.Value.ToString("MM/dd HH:mm");
                    if (c.ScheduleStartDT != null)
                    {
                        v.SArriveDTStr = c.ScheduleStartDT.Value.ToString("MM/dd HH:mm");
                        v.ScheduleStartDT = c.ScheduleStartDT;
                    }
                    v.ServiceLeaveDT = c.ServiceLeaveDT;
                    if (c.WBSEventM.CloseDT != null)
                    {
                        v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("MM/dd HH:mm");
                        v.EventStatusStr = "99.已結案";
                    }
                    v.MaintainNum = "";
                    int maintainNum = db.EventRelation.Where(x => x.CID == c.Num).Count();
                    if (maintainNum != 0)
                        v.MaintainNum = maintainNum.ToString();

                    v.RespondReason = c.RespondReason;
                    if (m.Customer1.SubArea.ResponsibleID2 != null)
                    {
                        v.DefaultUserName2 = m.Customer1.SubArea.ResponsibleClass1.Name + "-" + m.Customer1.SubArea.ResponsibleClass1.UserData2.UserName;                        
                    }
                    v.CGroupSName = c.WBSEventM.Customer1.CustomerGroup.CGroupID + " : " + c.WBSEventM.Customer1.CustomerGroup.CGroupShortName;

                    //已開立時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);                    
                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                    TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                    v.OverTime = "";
                    if (diff1.CompareTo(duration) > 0)
                        v.OverTime = "逾時";

                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;                    
                    v.AreaID = m.Customer1.SubArea.AreaID;
                    v.AreaStr = m.Customer1.SubArea.Area.Name;

                    v.AbnormalReason = isAbnormal(c, alertMList);

                    ret.Add(v);
                }
            }

            return ret.AsQueryable();
        }
        public ActionResult FollowUpEvent2(WBSEventViewModel wbsModel, IEnumerable<HttpPostedFileBase> files)
        {
            if (wbsModel.QuestionDescription == null) {
                ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                return RedirectToAction("FollowUpEvent2", "Mobile", new { mid = wbsModel.M_ID, cid = wbsModel.C_ID });
            }
            else {
                if (wbsModel.QuestionDescription.Trim() == "") {
                    ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                    return RedirectToAction("FollowUpEvent2", "Mobile", new { mid = wbsModel.M_ID, cid = wbsModel.C_ID });
                }
            }

            // 先取得該使用者的 FormsIdentity
            FormsIdentity id = (FormsIdentity)User.Identity;
            // 再取出使用者的 FormsAuthenticationTicket
            FormsAuthenticationTicket ticket = id.Ticket;
            string[] ret;

            wbsModel.CreateUserID = ticket.Name;
            wbsModel.QuestionCreateUserID = ticket.Name;

            ret = wBSEventRepository.FollowUpCreate(wbsModel);

            if (ret[0] != "false") {
                String msg = "叫修單新增成功,案件編號:" + ret[0];
                string url = "http://" + Request.Url.Authority + "/WBSEvent/WBSAssignMain?area=" + ret[2];
                //messageRepository.AddMsgbyRole("01", "新增後續叫修單", "新叫修單" + ret[0] + ",請盡速修改並指派執行人!", url);
                messageRepository.AddMsgbyTypeAndCid("0", ret[1], url);
                if (files != null) {
                    Save(files, ret[0], ret[1], 1);
                }
                return RedirectToAction("MobileMain2", "Mobile", new { data = msg });
            }
            else {
                return RedirectToAction("MobileMain2", "Mobile", new { data = "新增失敗" });
            }
            //return RedirectToAction("FollowUpEvent", "Mobile", new { mid = wbsModel.M_ID, cid = wbsModel.C_ID });
        }
        //更新叫修單
        public String[] Update(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[3];
            ret[0] = "false";
            ret[1] = wBSEventViewModel.C_ID.ToString();
            ret[2] = "";    //area

            int questionGrade = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionGrade).First();
            int serviceHours = db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == Int32.Parse(wBSEventViewModel.QuestionClass)).Select(x => x.QuestionServiceHours).First();
            String groupSW = db.Customer.AsEnumerable().Where(x => x.CustomerRef == wBSEventViewModel.CustomerRef).Select(x => x.GroupSW).First();

            if (wBSEventViewModel.ExpectArriveDTStr == null)
                wBSEventViewModel.ExpectArriveDTStr = "19000101 00:01";
            if (wBSEventViewModel.ExpectFinishDTStr == null)
                wBSEventViewModel.ExpectFinishDTStr = "19000101 00:01";
            wBSEventViewModel.ExpectArriveDT = DateTime.ParseExact(wBSEventViewModel.ExpectArriveDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            wBSEventViewModel.ExpectFinishDT = DateTime.ParseExact(wBSEventViewModel.ExpectFinishDTStr, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
            ret[2] = GetCustomerArea(wBSEventViewModel.CustomerRef);


            try
            {
                //WBSEventM wBSEventM = new WBSEventM();
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);
                
                //wBSEventM.CaseID = caseID;
                //wBSEventM.CaseClass = wBSEventViewModel.WBSCaseNumberM.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[0];
                //wBSEventM.CaseClass = wBSEventViewModel.WBSCaseNumberM.Substring(0, 1);
                //wBSEventM.CaseClass = "C";
                //wBSEventM.CaseDate = wBSEventViewModel.WBSCaseNumberM.Substring(1, 8);
                //wBSEventM.CaseDate = DateTime.Now.ToString("yyyyMMdd");
                //wBSEventM.CaseCode = casecode;
                //wBSEventViewModel.WBSCaseNumberM = wBSEventM.CaseClass + wBSEventM.CaseDate;
                //if (wBSEventM.CaseCode < 10)
                //    wBSEventViewModel.WBSCaseNumberM += "0000" + wBSEventM.CaseCode.ToString();
                //else if (wBSEventM.CaseCode < 100 && wBSEventM.CaseCode >= 10)
                //    wBSEventViewModel.WBSCaseNumberM += "000" + wBSEventM.CaseCode.ToString();
                //else if (wBSEventM.CaseCode < 1000 && wBSEventM.CaseCode >= 100)
                //    wBSEventViewModel.WBSCaseNumberM += "00" + wBSEventM.CaseCode.ToString();
                //else if (wBSEventM.CaseCode < 10000 && wBSEventM.CaseCode >= 1000)
                //    wBSEventViewModel.WBSCaseNumberM += "0" + wBSEventM.CaseCode.ToString();
                //else
                //    wBSEventViewModel.WBSCaseNumberM += wBSEventM.CaseCode.ToString();
                //wBSEventM.RB_CasseDate = wBSEventViewModel.RB_CasseDate;
                //try
                //{
                //    wBSEventM.RB_CasseNumber = Int32.Parse(wBSEventViewModel.RB_CasseNumber);
                //}
                //catch
                //{
                //    wBSEventM.RB_CasseNumber = 0;
                //}
                wBSEventM.ProductID = wBSEventViewModel.ProductID;
                wBSEventM.CustomerRef = wBSEventViewModel.CustomerRef;
                wBSEventM.CustomerUserID = wBSEventViewModel.CustomerUserID;
                wBSEventM.CustomerUserName = wBSEventViewModel.CustomerUserName;
                wBSEventM.CustomerUserPhone1 = wBSEventViewModel.CustomerUserPhone1;
                wBSEventM.CustomerUserPhone2 = wBSEventViewModel.CustomerUserPhone2;
                wBSEventM.CustomerCaseNum = wBSEventViewModel.CustomerCaseNum;
                //20150811新增-Hsiuyang
                if (wBSEventViewModel.ChangeAddr != null)
                    if (wBSEventViewModel.ChangeAddr.Trim().Length > 0)
                        wBSEventM.CustomerAddr = wBSEventViewModel.ChangeAddr;
                wBSEventM.ModifyDT = DateTime.Now;
                wBSEventM.ModifyUserID = wBSEventViewModel.ModifyUserID;


                WBSEventC wBSEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);
                //wBSEventC.Num = num;
                //wBSEventC.MomCaseID = caseID;
                //wBSEventC.ChildCaseID = childCaseID;
                //wBSEventViewModel.WBSCaseNumberC = (wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString();
                //wBSEventC.EventClass = "C01";
                wBSEventC.ProductClass = Int32.Parse(wBSEventViewModel.ProductClass);
                wBSEventC.ItemClass = Int32.Parse(wBSEventViewModel.ItemClass);
                wBSEventC.QuestionClass = Int32.Parse(wBSEventViewModel.QuestionClass);
                wBSEventC.QuestionGrade = questionGrade;
                wBSEventC.QuestionServiceHours = serviceHours;
                wBSEventC.QuestionDescription = wBSEventViewModel.QuestionDescription;                
                //wBSEventC.QuestionCreateUserID = wBSEventViewModel.QuestionCreateUserID;
                //wBSEventC.QuestionCreateDateTime = DateTime.Now;
                wBSEventC.ExpectArriveDateTime = wBSEventViewModel.ExpectArriveDT;
                wBSEventC.ExpectFinishDateTime = wBSEventViewModel.ExpectFinishDT;
                wBSEventC.ExpectArriveSW = wBSEventViewModel.ExpectArriveSW;
                //wBSEventC.DeleteMarkSW = wBSEventViewModel.DeleteMarkSW;
                //wBSEventC.DeleteReason = wBSEventViewModel.DeleteReason;
                //wBSEventC.DeleteMarkUserID = wBSEventViewModel.DeleteMarkUserID;
                //wBSEventC.DeleteMarkDateTime = wBSEventViewModel.DeleteMarkDT;
                //wBSEventC.CreateDateTime = DateTime.Now;
                //wBSEventC.CreateUserID = wBSEventViewModel.CreateUserID;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.ModifyUserID;
                //20150811新增-Hsiuyang
                wBSEventC.SugProvideSpareMach = wBSEventViewModel.SugProvideSpareMach;
                wBSEventC.SugRetrieveSpareMach = wBSEventViewModel.SugRetrieveSpareMach;
                wBSEventC.SugRetrieveUserMach = wBSEventViewModel.SugRetrieveUserMach;
                wBSEventC.SugReturnUserMach = wBSEventViewModel.SugReturnUserMach;
                wBSEventC.SugMachMemo = wBSEventViewModel.SugMachMemo;   //建議備機說明
                //20150817新增-Hsiuyang
                if (wBSEventViewModel.Closed == "T") //線上處理結案影響
                {
                    wBSEventM.CaseMStatus = "9";    //9為問題已結案
                    wBSEventM.CloseDT = DateTime.Now;
                    wBSEventC.EventStatus = 50;     //50為任務已解決(維修附件上傳)
                    wBSEventC.QuestionFinishSW = "Y";
                    wBSEventC.QuestionFinishDT = DateTime.Now;
                    wBSEventC.QuestionFinishSysDT = DateTime.Now;
                    wBSEventC.ServiceReport = wBSEventViewModel.AssignDescription;  //當結案時解決方式即為服務報告
                }
                else
                {
                    //wBSEventM.CaseMStatus = "1";    //1為開立新問題
                    //wBSEventC.EventStatus = 11; //11為問題已開立
                    wBSEventC.QuestionFinishSW = null;
                    wBSEventC.QuestionFinishDT = null;
                    wBSEventC.QuestionFinishSysDT = null;
                    wBSEventC.ServiceReport = null;  //當結案時解決方式即為服務報告
                }
                wBSEventC.AssignDescription = wBSEventViewModel.AssignDescription;  //解決方式(派單)描述

                //刪除原子單建議零件
                var qryD = db.SugProduct.Where(x => x.CID == wBSEventC.Num && (x.Class == 1 || x.Class == 3));
                foreach (SugProduct d in qryD)
                {
                    db.SugProduct.Remove(d);
                }
                //刪除原子單解決方式知識庫附件
                var qryDK = db.Files.Where(x => x.CID == wBSEventC.Num && x.Class == 3);
                foreach (Files d in qryDK)
                {
                    db.Files.Remove(d);
                }
                //刪除原子單執行預先保養單
                var qryM = db.EventRelation.Where(x => x.CID == wBSEventC.Num);
                foreach (EventRelation d in qryM)
                {
                    db.EventRelation.Remove(d);
                }
                //刪除原子單建議參考網頁
                var qryDH = db.Files.Where(x => x.CID == wBSEventC.Num && x.Class == 9);
                foreach (Files d in qryDH)
                {
                    db.Files.Remove(d);
                }
                
                //20150817新增-Hsiuyang-SugProduct建議部分
                JArray SugProduct = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaterialJson);
                for (int i = 0; i < SugProduct.Count; i++)
                {
                    SugProduct sugProduct = new SugProduct();
                    sugProduct.CID = wBSEventC.Num;
                    sugProduct.Class = Int32.Parse(SugProduct[i]["Class"].ToString());                    
                    if (SugProduct[i]["ProductNum"].ToString() == "")
                        sugProduct.ProductName = SugProduct[i]["ProductName"].ToString();                    
                    else
                        sugProduct.ProductNum = Int32.Parse(SugProduct[i]["ProductNum"].ToString());
                    

                    db.SugProduct.Add(sugProduct);
                }
                //20150817新增-Hsiuyang-解決方式知識庫附件
                JArray KnowledgeData = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.KnowledgeJson);
                for (int i = 0; i < KnowledgeData.Count; i++)
                {
                    Files knowledgefile = new Files();
                    knowledgefile.CID = wBSEventC.Num;
                    knowledgefile.Class = 3;
                    knowledgefile.FileAddr = "";
                    knowledgefile.FileName = "";                    
                    knowledgefile.KnowledgeID = Int32.Parse(KnowledgeData[i]["KnowledgeID"].ToString());
                    db.Files.Add(knowledgefile);
                }
                //20150817新增-Hsiuyang-執行預先保養單
                JArray maintainCases = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.MaintainCaseJson);
                for (int i = 0; i < maintainCases.Count; i++)
                {
                    EventRelation maintainCase = new EventRelation();
                    maintainCase.CID = wBSEventC.Num;
                    maintainCase.RelationCID = Int32.Parse(maintainCases[i]["cID"].ToString());

                    db.EventRelation.Add(maintainCase);
                }

                //20151113新增-Hsiuyang-Hyperlink建議參考網頁(CLASS=9)
                JArray Hyperlink = JsonConvert.DeserializeObject<JArray>(wBSEventViewModel.HyperlinkJson);
                for (int i = 0; i < Hyperlink.Count; i++)
                {
                    Files hyperlink = new Files();
                    hyperlink.CID = wBSEventC.Num;
                    hyperlink.Class = 9;
                    hyperlink.FileAddr = Hyperlink[i]["Href"].ToString();
                    hyperlink.FileName = Hyperlink[i]["Name"].ToString();

                    db.Files.Add(hyperlink);
                }

                //db.WBSEventM.Add(wBSEventM);
                //db.WBSEventC.Add(wBSEventC);
                db.SaveChanges();
                //ret = "true";
                ret[0] = wBSEventViewModel.WBSCaseNumberM + "-" + wBSEventViewModel.WBSCaseNumberC;
            }
            catch
            {
            }

            return ret;
        }
        public ActionResult FollowUpEvent(WBSEventViewModel wbsModel, IEnumerable<HttpPostedFileBase> files)
        {
            string type = "0";
            if (wbsModel.ExpectArriveSW == "4")
                type = "1";

            if (wbsModel.QuestionDescription == null) {
                ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                return RedirectToAction("FollowUpEvent", "Mobile", new { mid = wbsModel.M_ID,cid = wbsModel.C_ID,type = type});
            }
            else {
                if (wbsModel.QuestionDescription.Trim() == "") {
                    ModelState.AddModelError("QuestionDescription", "問題描述輸入錯誤");
                    return RedirectToAction("FollowUpEvent", "Mobile", new { mid = wbsModel.M_ID, cid = wbsModel.C_ID, type = type });
                }
            }

            // 先取得該使用者的 FormsIdentity
            FormsIdentity id = (FormsIdentity)User.Identity;
            // 再取出使用者的 FormsAuthenticationTicket
            FormsAuthenticationTicket ticket = id.Ticket;
            string[] ret;

            string AreaID = areaRespositiory.GetCustomerAreaID(wbsModel.CustomerRef);
            //Boolean isAutoAssign = systemSettingRepository.IsAutoAssign(wbsModel.EventClass, AreaID);

            wbsModel.CreateUserID = ticket.Name;
            wbsModel.QuestionCreateUserID = ticket.Name;
            //wbsModel.isAutoAssign = isAutoAssign.ToString();
            //不再自動派工

            wbsModel.isAutoAssign = "false";
            wbsModel.Url = Request.Url.Authority;

            ret = wBSEventRepository.FollowUpCreate(wbsModel);

            if (ret[0] != "false") {
                string cu = wBSEventRepository.GetCShortNameAndProductName(int.Parse(ret[1]));
                String msg = cu + "-新增成功,單號:" + ret[0];

                if (wbsModel.ResponsibleID != null && wbsModel.ResponsibleID != "")
                    msg = cu + "-新增並派工成功,單號:" + ret[0];
                //String msg = "叫修單新增成功,案件編號:" + ret[0];
                string url = "http://" + Request.Url.Authority + "/WBSEvent/WBSAssignMain?area=" + ret[2];
                //messageRepository.AddMsgbyRole("01", "新增後續叫修單", "新叫修單" + ret[0] + ",請盡速修改並指派執行人!", url);                
                //if (isAutoAssign || type == "1")
                //    msg += ",系統已預設派工:" + ret[3] + "。";

                messageRepository.AddMsgbyTypeAndCid("0", ret[1], url);


                if (files != null) {
                    Save(files, ret[0], ret[1], 1);
                }
                return RedirectToAction("MobileMain", "Mobile", new { data = msg });
            }
            else{
                return RedirectToAction("MobileMain", "Mobile", new { data = "新增失敗" });
            }
            //return RedirectToAction("FollowUpEvent", "Mobile", new { mid = wbsModel.M_ID, cid = wbsModel.C_ID });
        }
        //C02C03 儲存處理說明
        public String[] ChangeServiceReport(WBSEventViewModel wBSEventViewModel)
        {
            String[] ret = new String[3];
            ret[0] = "false";   //回饋訊息
            ret[1] = "";        //案號
            ret[2] = "";        //mid

            try
            {
                WBSEventC wBSEventC = db.WBSEventC.Find(wBSEventViewModel.C_ID);
                WBSEventM wBSEventM = db.WBSEventM.Find(wBSEventViewModel.M_ID);

                if (wBSEventC.EventStatus < 42)
                {
                    wBSEventC.ServiceArriveDT = DateTime.Now;
                    wBSEventC.ServiceArriveSysDT = DateTime.Now;
                    wBSEventC.ServiceCreateDT = DateTime.Now;
                    wBSEventC.ServiceCreateUserID = wBSEventViewModel.ModifyUserID;                    
                    wBSEventC.EventStatus = 42;
                }
                if (wBSEventC.ServiceCreateUserID == null)
                {
                    wBSEventC.ServiceCreateDT = DateTime.Now;
                    wBSEventC.ServiceCreateUserID = wBSEventViewModel.ModifyUserID;
                }
                wBSEventC.ServiceLeaveDT = DateTime.Now;
                wBSEventC.ServiceLeaveSysDT = DateTime.Now;
                wBSEventC.ServiceModifyDT = DateTime.Now;
                wBSEventC.ServiceModifyUserID = wBSEventViewModel.ModifyUserID;

                wBSEventC.ServiceReport = wBSEventViewModel.ServiceReport;
                wBSEventC.ModifyDateTime = DateTime.Now;
                wBSEventC.ModifyUserID = wBSEventViewModel.ModifyUserID;

                String caseNum = wBSEventM.CaseClass + wBSEventM.CaseDate + "-";
                if (wBSEventM.CaseCode < 10)
                    caseNum += "0000" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 100 && wBSEventM.CaseCode >= 10)
                    caseNum += "00" + wBSEventM.CaseCode.ToString();
                else if (wBSEventM.CaseCode < 10000 && wBSEventM.CaseCode >= 1000)
                    caseNum += "0" + wBSEventM.CaseCode.ToString();
                else
                    caseNum += wBSEventM.CaseCode.ToString();
                caseNum += "-" + ((wBSEventC.ChildCaseID < 10) ? ("0" + wBSEventC.ChildCaseID.ToString()) : wBSEventC.ChildCaseID.ToString());

                db.SaveChanges();
                ret[1] = caseNum;
                ret[0] = "true"; 
            }
            catch
            {
                ret[0] = "false";
            }
            return ret;
        }
        //客戶叫修主畫面-案件詳情讀取
        public WBSEventViewModel ReadOneCase(int mID, int cID)
        {
            List<AlertDetailSettingViewModel> alertMList = new List<AlertDetailSettingViewModel>();
            var Aqry = db.AlertDetailSetting;
            foreach (AlertDetailSetting o in Aqry)
            {
                AlertDetailSettingViewModel a = new AlertDetailSettingViewModel();
                a.EventClass = o.EventClass;
                a.AlertEvent = o.AlertEvent;
                a.FirstTime = o.FirstTime;
                alertMList.Add(a);
            }

            WBSEventViewModel v = new WBSEventViewModel();
            WBSEventM M = db.WBSEventM.Find(mID);
            WBSEventC C = db.WBSEventC.Find(cID);

            v.C_ID = C.Num;
            v.CreateDT = C.CreateDateTime;
            v.CreateUserID = C.CreateUserID;
            v.CustomerAddr = M.Customer1.Addr; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.Addr).First();
            v.CustomerNote = M.Customer1.Notes; 
            v.CustomerID = M.Customer1.CustomerID; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.CustomerID).First();
            v.CustomerRef = M.CustomerRef;
            v.CustomerSName = M.Customer1.ShortName; //db.Customer.AsEnumerable().Where(x => x.CustomerRef == M.CustomerRef).Select(x => x.ShortName).First();
            v.CustomerUserName = M.CustomerUserName;
            v.CustomerUserPhone1 = M.CustomerUserPhone1;
            v.CustomerUserPhone2 = M.CustomerUserPhone2;
            v.CustomerUserPhone = M.CustomerUserPhone1;
            if (M.CustomerUserPhone2 != null && M.CustomerUserPhone2 != "")
                v.CustomerUserPhone += " /" + M.CustomerUserPhone2;
            v.CustomerCaseNum = M.CustomerCaseNum;

            if (M.ProductID != null)
            {
                v.ProductID = M.ProductID;
                v.ProductIDNote = db.ProductData.Where(x => x.ProductID == M.ProductID).Select(x => x.Note2).First();
            }
            else
            {
                v.ProductID = "";
                v.ProductIDNote = "";
            }
            v.EventClass = C.EventClass;
            v.EventClassStr = C.EventClass + "-" + db.EventClass.Where(x => x.Class == C.EventClass).Select(x => x.Name).First(); ;
            v.ExpectArriveDT = C.ExpectArriveDateTime;
            v.ExpectArriveDD = C.ExpectArriveDateTime.Value.Date;
            v.ExpectArriveHH = C.ExpectArriveDateTime.Value.ToString("HH");
            v.ExpectArriveMM = C.ExpectArriveDateTime.Value.ToString("mm");
            v.ExpectArriveSW = C.ExpectArriveSW;
            v.ExpectFinishDT = C.ExpectFinishDateTime;
            v.ExpectFinishDD = C.ExpectFinishDateTime.Value.Date;
            v.ExpectFinishHH = C.ExpectFinishDateTime.Value.ToString("HH");
            v.ExpectFinishMM = C.ExpectFinishDateTime.Value.ToString("mm");
            //20150811新增-Hsiuyang
            v.ChangeAddr = M.CustomerAddr;
            v.SpareMach = M.SpareMach;
            v.UserMach = M.UserMach;
            v.CaseMStatus = M.CaseMStatus;

            //v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.Name + "-" + M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.ResponsibleArea = M.Customer1.SubArea.SubAreaID;

            v.ExpectArriveDTStr = (C.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            v.ExpectFinishDTStr = (C.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
            v.ExpectArriveSW = C.ExpectArriveSW;
            if (C.ExpectArriveSW == "1")            
                v.ExpectArriveSWStr = "合約規定";            
            else if (C.ExpectArriveSW == "2")
                v.ExpectArriveSWStr = "建議期望";
            else if (C.ExpectArriveSW == "3")
                v.ExpectArriveSWStr = "客戶指定";
            else if (C.ExpectArriveSW == "4")
                v.ExpectArriveSWStr = "自派新單";                
            else
            {
                v.ExpectArriveSWStr = "自行約定";
                v.ExpectArriveDTStr = "請自行與客戶約定";
                v.ExpectFinishDTStr = "請自行與客戶約定";
            }                

            v.ItemClass = C.ItemClass.ToString();

            v.ProductNote = C.ProductClass1.Note; //db.ProductClass.AsEnumerable().Where(x => x.ProductClassID == C.ProductClass).Select(x => x.Note).First();
            v.ItemNote = C.ItemClass1.Note; //db.ItemClass.AsEnumerable().Where(x => x.ItemClassID == C.ItemClass).Select(x => x.Note).First();
            v.QuestionNote = C.QuestionClass1.Note; //db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == C.QuestionClass).Select(x => x.Note).First();

            v.M_ID = M.CaseID;
            v.ProductClass = C.ProductClass.ToString();
            v.QuestionClass = C.QuestionClass.ToString();
            v.QuestionDescription = C.QuestionDescription;
            v.WBSCaseNumberC = (C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString();
            v.WBSCaseNumberM = M.CaseClass + M.CaseDate + "-";
            if (M.CaseCode < 10)
                v.WBSCaseNumberM += "0000" + M.CaseCode.ToString();
            else if (M.CaseCode < 100 && M.CaseCode >= 10)
                v.WBSCaseNumberM += "000" + M.CaseCode.ToString();
            else if (M.CaseCode < 1000 && M.CaseCode >= 100)
                v.WBSCaseNumberM += "00" + M.CaseCode.ToString();
            else if (M.CaseCode < 10000 && M.CaseCode >= 1000)
                v.WBSCaseNumberM += "0" + M.CaseCode.ToString();
            else
                v.WBSCaseNumberM += M.CaseCode.ToString();
            v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;

            //20150811新增-Hsiuyang
            v.SugProvideSpareMach = C.SugProvideSpareMach;
            v.SugRetrieveSpareMach = C.SugRetrieveSpareMach;
            v.SugRetrieveUserMach = C.SugRetrieveUserMach;
            v.SugReturnUserMach = C.SugReturnUserMach;
            v.SugMachMemo = C.SugMachMemo;
            v.EventStatus = C.EventStatus;
            v.AssignDescription = C.AssignDescription;
            v.ServiceReport = C.ServiceReport;
            if (C.ServiceTakeHours != null)
                v.WorkHours = C.ServiceTakeHours.Value;
            else
                v.WorkHours = 0;
            //20150814新增-Hsiuyang
            if (C.EventStatus >= 50)
                v.Closed = "T";
            else
                v.Closed = "F";
            //建議零件
            var qryS = db.SugProduct.Where(x => x.CID == cID && (x.Class == 1 || x.Class == 3));
            JArray SugProduct = new JArray();
            foreach (SugProduct s in qryS) {
                JObject item = new JObject();
                item["Class"] = s.Class.ToString();
                if (s.ProductNum == null) {
                    item["ProductNum"] = "";
                    item["ProductName"] = s.ProductName;
                }
                else {
                    item["ProductNum"] = s.ProductNum.ToString();
                    item["ProductName"] = s.ProductData.Name; //db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                    //item["ProductName"] = db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                }
                SugProduct.Add(item);
            }
            if (SugProduct.Count > 0)
                v.MaterialJson = SugProduct.ToString();

            //實際零件
            var qryS2 = db.SugProduct.Where(x => x.CID == cID && (x.Class == 2 || x.Class == 4));
            JArray SugProduct2 = new JArray();
            foreach (SugProduct s in qryS2)
            {
                JObject item = new JObject();
                item["Class"] = s.Class.ToString();
                if (s.ProductNum == null)
                {
                    item["ProductNum"] = "";
                    item["ProductName"] = s.ProductName;
                }
                else
                {
                    item["ProductNum"] = s.ProductNum.ToString();
                    item["ProductName"] = s.ProductData.Name; //db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                    //item["ProductName"] = db.ProductData.AsEnumerable().Where(x => x.ProductNum == s.ProductNum).Select(x => x.Name).First();
                }
                SugProduct2.Add(item);
            }
            if (SugProduct2.Count > 0)
                v.MaterialJson2 = SugProduct2.ToString();

            
            //解決方式知識庫附件
            var qryK = db.Files.Where(x => x.CID == cID && x.Class == 3);
            JArray KnowledgeData = new JArray();
            foreach (Files k in qryK) {
                JObject item = new JObject();
                item["KnowledgeID"] = k.KnowledgeID.ToString();
                item["Name"] = k.KnowledgeBase.FileName; //db.KnowledgeBase.AsEnumerable().Where(x => x.KnowledgeID == k.KnowledgeID).Select(x => x.FileName).First();

                KnowledgeData.Add(item);
            }
            if (KnowledgeData.Count > 0)
                v.KnowledgeJson = KnowledgeData.ToString();
            //執行預先保養單
            var qryE = db.EventRelation.Where(x => x.CID == cID);
            JArray MaintainCase = new JArray();
            foreach (EventRelation e in qryE) {
                JObject item = new JObject();
                item["mID"] = db.WBSEventC.AsEnumerable().Where(x => x.Num == e.RelationCID).Select(x => x.MomCaseID).First();                
                item["cID"] = e.RelationCID;
                MaintainCase.Add(item);
            }
            if (MaintainCase.Count > 0)
                v.MaintainCaseJson = MaintainCase.ToString();

            //20151113新增-Hsiuyang-Hyperlink建議參考網頁(CLASS=9)
            var qryH = db.Files.Where(x => x.CID == cID && x.Class == 9);
            JArray HyperlinkData = new JArray();
            foreach (Files k in qryH) {
                JObject item = new JObject();
                item["Href"] = k.FileAddr;
                item["Name"] = k.FileName;
                HyperlinkData.Add(item);
            }
            if (HyperlinkData.Count > 0)
                v.HyperlinkJson = HyperlinkData.ToString();
            if (C.EventStatus == 0) {
                v.DeleteMarkDT = C.DeleteMarkDateTime;
                v.DeleteMarkDTStr = (C.DeleteMarkDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                v.DeleteMarkUserID = C.DeleteMarkUserID;
                v.DeleteMarkUserName = db.UserData.AsEnumerable().Where(x => x.UserID == C.DeleteMarkUserID).Select(x => x.UserName).First();
                v.DeleteReason = C.DeleteReason;
            }
            //20150824新增-Hsiuyang-已排程所需(預計到達時間,回覆說明)
            v.ResponsibleUserName = "";
            if (C.ScheduleServiceHours != null)
                v.WorkHours = C.ScheduleServiceHours.Value;
            if (C.EventStatus >= 21)
            {
                if (C.ResponsibleClass != null)
                    v.ResponsibleUserName = C.ResponsibleClass.UserData2.UserName;
                else //線上結案
                    v.ResponsibleUserName = "";
            }
            if (C.EventStatus >= 31) {
                //v.ResponsibleUserName = C.ResponsibleClass.UserData2.UserName;
                v.ScheduleStartDT = C.ScheduleStartDT;
                v.ScheduleStartDTStr = (C.ScheduleStartDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                v.RespondReason = C.RespondReason;
                if(C.RespondSW == "Y")
                    v.RespondSWStr = "任務已接受";
                else if (C.RespondSW == "N")
                    v.RespondSWStr = "任務已拒絕";
                else
                    v.RespondSWStr = "尚未回覆";
            }
            if (C.EventStatus >= 41) {
                if(C.ServiceModifyUserID != null)
                    v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == C.ServiceModifyUserID).Select(x => x.UserName).First();
                else if(C.ServiceCreateUserID!=null)
                    v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == C.ServiceCreateUserID).Select(x => x.UserName).First();
                else
                    v.ServiceUserName = db.UserData.AsEnumerable().Where(x => x.UserID == C.CreateUserID).Select(x => x.UserName).First();

                v.RespondSW = C.RespondSW;
                if (C.ServiceArriveDT == null)//非線上結案
                {
                    v.ServiceArriveDT = C.ServiceArriveDT;
                    v.ServiceArriveDTStr = "已線上結案或強制結案";
                    v.ServiceArriveSysDT = C.ServiceArriveSysDT;
                    v.ServiceArriveSysDTStr = "已線上結案或強制結案";
                    v.EditArriveDT = C.ServiceArriveDT;
                }
                else {
                    v.ServiceArriveDT = C.ServiceArriveDT;
                    v.ServiceArriveDTStr = (C.ServiceArriveDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.ServiceArriveSysDT = C.ServiceArriveSysDT;
                    v.ServiceArriveSysDTStr = (C.ServiceArriveSysDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.EditArriveDT = C.ServiceArriveDT;
                    v.EditArriveDD = C.ServiceArriveDT.Value.Date;
                    v.EditArriveHH = C.ServiceArriveDT.Value.ToString("HH");
                    v.EditArriveMM = C.ServiceArriveDT.Value.ToString("mm");
                }
            }
            if (C.EventStatus >= 42) {                
                if (C.ServiceLeaveDT == null)//非線上結案
                {
                    v.ServiceLeaveDT = C.ServiceLeaveDT;
                    v.ServiceLeaveDTStr = "已線上結案或強制結案";
                    v.ServiceLeaveSysDT = C.ServiceLeaveSysDT;
                    v.ServiceLeaveSysDTStr = "已線上結案或強制結案";
                    v.EditLeaveDT = C.ServiceLeaveDT;
                }
                else {
                    v.ServiceLeaveDT = C.ServiceLeaveDT;
                    v.ServiceLeaveDTStr = (C.ServiceLeaveDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.ServiceLeaveSysDT = C.ServiceLeaveSysDT;
                    v.ServiceLeaveSysDTStr = (C.ServiceLeaveSysDT ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.EditLeaveDT = C.ServiceLeaveDT;
                    v.EditLeaveDD = C.ServiceLeaveDT.Value.Date;
                    v.EditLeaveHH = C.ServiceLeaveDT.Value.ToString("HH");
                    v.EditLeaveMM = C.ServiceLeaveDT.Value.ToString("mm");
                }
                v.ProvideSpareMach = C.ProvideSpareMach;
                v.RetrieveSpareMach = C.RetrieveSpareMach;
                v.RetrieveUserMach = C.RetrieveUserMach;
                v.ReturnUserMach = C.ReturnUserMach;
                v.MachMemo = C.MachMemo;                
            }
            //20150922新增-Hsiuyang
            if (C.EventStatus >= 46) {
                if (C.QuestionFinishDT != null) {
                    v.SolveDTStr = C.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                    v.SolveSysDTStr = C.QuestionFinishSysDT.Value.ToString("yyyy/MM/dd HH:mm");
                }
                if (C.WBSEventM.CloseDT != null)                    
                    v.CloseDTStr = C.WBSEventM.CloseDT.Value.ToString("yyyy/MM/dd HH:mm");
            }
            v.haveContract = "false";
            Boolean havaContract = false;
            if(db.CustomerContract.Where(x=>x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Count() > 0)
                havaContract = true;
            if(havaContract) {
                v.haveContract = "true";
                v.CCProduct = C.ProductClass;
                String temp = db.CustomerContract.Where(x=>x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x=>x.ContractStatus).First();
                //合約狀況代碼
                switch(temp){//01.洽談中 (可能用計算方式:合約到期日 +N天) A1.總行合約中 B1.分行合約中 C1.叫修 L1.租賃中 W1.保固中 ZZ.未分類 XX.停用
                    case "01": v.ContractStatusStr = "洽談中"; break;
                    case "A1": v.ContractStatusStr = "總行合約中"; break;
                    case "B1": v.ContractStatusStr = "分行合約中"; break;
                    case "C1": v.ContractStatusStr = "叫修"; break;
                    case "L1": v.ContractStatusStr = "租賃中"; break;
                    case "W1": v.ContractStatusStr = "保固中"; break;
                    case "ZZ": v.ContractStatusStr = "未分類"; break;
                    case "XX": v.ContractStatusStr = "停用"; break;
                    default: v.ContractStatusStr = ""; break;
                }
                //v.ContractStatusStr = db.CustomerContract.Where(x=>x.CustomerRef == M.CustomerRef && x.ProductClassID == C.ProductClass).Select(x=>x.ContractStatus).First();
                //v.MaintainNum = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductClassID == C.ProductClass).Select(x => x.MaintainNum).First();
                v.MaintainNum = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.MaintainNum).First();
                v.MaintainMonthMemo = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.MaintainMonthMemo).First();
            }

            if (v.Closed == "T" && v.RespondSW != "Y") {//已結案且沒有回覆者判定為線上結案
                v.ExpectArriveDTStr = "已線上結案";
                v.ExpectFinishDTStr = "已線上結案";
            }

            v.AbnormalReason = isAbnormal(C, alertMList);
            v.EventStatusStr = GetEventStatusStr(C.EventStatus);
            

            return v;
        }
        public IQueryable<WBSEventViewModel> ReadEventStatisticsByType(String type, String uid)//type 0:未解決,1:已解決,2:已結案,3:總數(3不做) //20160810改狀態11 20 21 30 31 41 42 43
        {
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();

            //20161012-判斷11或20只能由派遣管理人看到-Hsiuyang
            if ((type == "11" || type == "20") && uid != "Assign")
                return ret.AsQueryable();

            var qry = db.WBSEventC.Where(x => x.EventClass != "M01");

            if (type != null && type != "")//type 0:未解決,1:已解決,2:已結案,3:總數(3不做),4:未指派
            {
                if (type == "11")
                    qry = qry.Where(x => x.EventStatus == 11);
                else if (type == "20")
                    qry = qry.Where(x => x.EventStatus == 20);
                else if (type == "21")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 21);
                else if (type == "30")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 30);
                else if (type == "31")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 31);
                else if (type == "41")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 41);
                else if (type == "42")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 42);
                else if (type == "43")
                    qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus == 43);

                //if (uid == "Assign") {
                //    if (type == "4")
                //        qry = qry.Where(x => x.EventStatus <= 20);
                //    else
                //        qry = qry.Where(x => x.EventStatus < -99);
                //}
                //else {
                //    if (type == "0")
                //        qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus < 50);
                //    else if (type == "1")
                //        qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus >= 50);
                //    else if (type == "2")
                //        qry = qry.Where(x => x.ResponsibleClass.UserID == uid && x.EventStatus >= 50 && x.WBSEventM.CaseMStatus == "9" && x.ChildCaseID == 1);
                //    else if (type == "4")
                //        qry = qry.Where(x => x.Num < -1);
                //    //else if (type == "3")
                //    //qry = qry.Where(x => x.EventStatus >= 30 && x.EventStatus < 50);
                //}
                
            }
            foreach (WBSEventC c in qry) {
                WBSEventM m = db.WBSEventM.Find(c.MomCaseID);
                WBSEventViewModel v = new WBSEventViewModel();
                v.M_ID = m.CaseID;
                v.C_ID = c.Num;
                //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                if (m.CaseCode < 10)
                    v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                else if (m.CaseCode < 100 && m.CaseCode >= 10)
                    v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                else if (m.CaseCode < 1000 && m.CaseCode >= 100)
                    v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                else if (m.CaseCode < 10000 && m.CaseCode >= 1000)
                    v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                else
                    v.WBSCaseNumberM += m.CaseCode.ToString();
                v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0" + c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                v.EventClass = c.EventClass;
                v.EventClassStr = v.EventClass + " : " + db.EventClass.AsEnumerable().Where(x => x.Class == c.EventClass).Select(x => x.Name).First();
                v.EventStatus = c.EventStatus;

                v.EventStatusStr = (v.EventStatus == 0) ? "0" + v.EventStatus.ToString() : v.EventStatus.ToString();
                v.EventStatusStr += "." + GetEventStatusStr(v.EventStatus);

                v.CustomerRef = m.CustomerRef;
                v.CustomerAddr = m.Customer1.Addr;
                if(m.CustomerAddr != "" && m.CustomerAddr != null)
                    v.CustomerAddr = m.CustomerAddr;
                v.CustomerSName = m.Customer1.ShortName;
                v.CustomerUserID = m.CustomerUserID;
                v.CustomerUserName = m.CustomerUserName;
                v.CustomerUserPhone1 = m.CustomerUserPhone1;
                v.CustomerUserPhone = m.CustomerUserPhone1;
                if (m.CustomerUserPhone2 != null && m.CustomerUserPhone2 != "")
                    v.CustomerUserPhone += " /" + m.CustomerUserPhone2;
                v.CustomerUserPhone2 = m.CustomerUserPhone2;
                v.ProductClass = c.ProductClass.ToString();
                v.ProductNote = c.ProductClass1.Note;
                v.ItemClass = c.ItemClass.ToString();
                v.ItemNote = c.ItemClass1.Note;
                v.QuestionClass = c.QuestionClass.ToString();
                v.QuestionNote = c.QuestionClass1.Note;
                v.QuestionNoteAll = c.ProductClass1.Note + "-" + c.ItemClass1.Note + "-" + c.QuestionClass1.Note;
                v.QuestionGrade = c.QuestionGrade.ToString();
                v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                v.QuestionDescription = c.QuestionDescription;

                v.HasActtachment = "";
                if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                    v.HasActtachment = "@";
                v.HasAssignActtachment = "";
                if (db.Files.Where(x => x.CID == c.Num && x.Class == 2).Count() > 0)
                    v.HasAssignActtachment = "@";

                v.HasKnowledge = "";
                if (db.Files.Where(x => x.CID == c.Num && x.Class == 3).Count() > 0)
                    v.HasKnowledge = "@";

                v.HasHyperlink = "";
                if (db.Files.Where(x => x.CID == c.Num && x.Class == 9).Count() > 0)
                    v.HasHyperlink = "@";

                v.ExpectArriveDTStr = (c.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                v.ExpectFinishDTStr = (c.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                if (c.ExpectArriveSW == "1")
                    v.ExpectArriveSWStr = "合約規定";
                else if (c.ExpectArriveSW == "2")
                    v.ExpectArriveSWStr = "建議期望";
                else if (c.ExpectArriveSW == "3")
                    v.ExpectArriveSWStr = "客戶指定";
                else if (c.ExpectArriveSW == "4")
                    v.ExpectArriveSWStr = "自派新單";
                else
                {
                    v.ExpectArriveSWStr = "自行約定";
                    v.ExpectArriveDTStr = "請自行與客戶約定";
                    v.ExpectFinishDTStr = "請自行與客戶約定";
                }

                v.QuestionCreateUserID = c.QuestionCreateUserID;
                v.QuestionCreateDT = c.QuestionCreateDateTime;
                v.ExpectArriveDT = c.ExpectArriveDateTime;
                v.ExpectFinishDT = c.ExpectFinishDateTime;
                v.ExpectArriveSW = c.ExpectArriveSW;
                v.DeleteMarkSW = c.DeleteMarkSW;
                v.DeleteReason = c.DeleteReason;
                v.DeleteMarkUserID = c.DeleteMarkUserID;
                v.DeleteMarkDT = c.DeleteMarkDateTime;
                v.CreateDT = c.CreateDateTime;
                v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                v.CreateYYYYStr = c.CreateDateTime.Value.Year.ToString();
                v.CreateUserID = c.CreateUserID;
                v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                v.ModifyDT = c.ModifyDateTime;
                if (c.ModifyDateTime != null)
                    v.ChgDTStr = c.ModifyDateTime.Value.ToString("MM/dd HH:mm");
                v.ModifyUserID = c.ModifyUserID;
                if (c.AssignDT != null)
                    v.AssignDTStr = c.AssignDT.Value.ToString("MM/dd HH:mm");
                if (c.AssignUserID != null)
                    v.AssignUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.AssignUserID).Select(x => x.UserName).First();
                if (c.ResponsibleID != null)
                    v.ResponsibleUserName = c.ResponsibleClass.Name + "-" + c.ResponsibleClass.UserData2.UserName;
                if (c.RespondSW == "Y")
                    v.ConfirmDTStr = c.RespondDT.Value.ToString("MM/dd HH:mm");
                else
                    v.ConfirmDTStr = "";
                if (c.ServiceArriveSysDT != null)
                {
                    v.ArriveDTStr = c.ServiceArriveDT.Value.ToString("MM/dd HH:mm");
                    v.ServiceArriveDT = c.ServiceArriveDT;
                    v.ArriveSysDTStr = c.ServiceArriveSysDT.Value.ToString("MM/dd HH:mm");
                }
                if (c.QuestionFinishSysDT != null)
                {
                    v.SolveDTStr = c.QuestionFinishDT.Value.ToString("MM/dd HH:mm");
                    v.SolveSysDTStr = c.QuestionFinishSysDT.Value.ToString("MM/dd HH:mm");
                    v.QuestionFinishDT = c.QuestionFinishDT;
                }

                if (c.ExpectArriveDateTime != null)
                    v.ExArriveDTStr = c.ExpectArriveDateTime.Value.ToString("MM/dd HH:mm");
                if (c.ExpectFinishDateTime != null)
                    v.ExFinishDTStr = c.ExpectFinishDateTime.Value.ToString("MM/dd HH:mm");
                if (c.ScheduleStartDT != null)
                {
                    v.SArriveDTStr = c.ScheduleStartDT.Value.ToString("MM/dd HH:mm");
                    v.ScheduleStartDT = c.ScheduleStartDT;
                }

                v.ServiceLeaveDT = c.ServiceLeaveDT;

                //v.CloseDTStr = c.QuestionFinishDT.Value.ToString("yyyy/MM/dd HH:mm");
                //if (c.ServiceLeaveDT != null)
                //    v.SolveDTStr = c.ServiceLeaveDT.Value.ToString("yyyy/MM/dd HH:mm");
                if (c.WBSEventM.CloseDT != null)
                {
                    v.CloseDTStr = c.WBSEventM.CloseDT.Value.ToString("MM/dd HH:mm");
                    v.EventStatusStr = "99.已結案";
                }
                v.MaintainNum = "";
                int maintainNum = db.EventRelation.Where(x => x.CID == c.Num).Count();
                if (maintainNum != 0)
                    v.MaintainNum = maintainNum.ToString();

                v.RespondReason = c.RespondReason;
                if (m.Customer1.SubArea.ResponsibleID2 != null)
                {
                    v.DefaultUserName2 = m.Customer1.SubArea.ResponsibleClass1.Name + "-" + m.Customer1.SubArea.ResponsibleClass1.UserData2.UserName;
                    //v.ResponsibleArea2 = m.Customer1.SubArea.SubAreaID;
                }


                v.CGroupSName = c.WBSEventM.Customer1.CustomerGroup.CGroupID + " : " + c.WBSEventM.Customer1.CustomerGroup.CGroupShortName;

                //已開立時間
                System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);
                //v.ServiceDT = Convert.ToDateTime(diff1.ToString());
                int day = Int32.Parse(diff1.ToString("%d"));
                int hour = Int32.Parse(diff1.ToString("%h"));
                hour += day * 24;
                v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                TimeSpan duration = new TimeSpan(0, 0, settingRepository.GetSetting().FirstOverTimeM, 0);
                v.OverTime = "";
                if (diff1.CompareTo(duration) > 0)
                    v.OverTime = "逾時";


                v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();
                v.AreaID = m.Customer1.SubArea.AreaID;
                v.AreaStr = m.Customer1.SubArea.Area.Name;


                //if (Etype == "C02" || Etype == "C03")
                //{
                //    if (c.ServiceLeaveDT != null)
                //    {
                //        v.FinishDTStr = c.ServiceLeaveDT.Value.ToString("MM/dd HH:mm");
                //        v.FinishSysDTStr = c.ServiceLeaveSysDT.Value.ToString("MM/dd HH:mm");
                //        if (c.ServiceLeaveDT.Value.AddDays(7).CompareTo(DateTime.Now) < 0)
                //        {
                //            DateTime temp = c.ServiceLeaveDT.Value.AddDays(7);
                //            while (temp.CompareTo(DateTime.Now) < 0)
                //            {
                //                temp = temp.AddDays(7);
                //            }
                //            v.NextAlertDTStr = temp.ToString("MM/dd HH:mm");
                //        }
                //        else
                //        {
                //            v.NextAlertDTStr = c.ServiceLeaveDT.Value.AddDays(7).ToString("MM/dd HH:mm");
                //        }
                //    }
                //    else
                //    {
                //        if (c.CreateDateTime.Value.AddDays(3).CompareTo(DateTime.Now) < 0)
                //        {
                //            DateTime temp = c.CreateDateTime.Value.AddDays(3);
                //            while (temp.CompareTo(DateTime.Now) < 0)
                //            {
                //                temp = temp.AddDays(3);
                //            }
                //            v.NextAlertDTStr = temp.ToString("MM/dd HH:mm");
                //        }
                //        else
                //        {
                //            v.NextAlertDTStr = c.CreateDateTime.Value.AddDays(3).ToString("MM/dd HH:mm");
                //        }
                //    }
                //}
                ret.Add(v);
            }
            return ret.AsQueryable();
        }
        //客戶叫修服務-案件詳情讀取-轉派工專用(部分資料清空)
        public WBSEventViewModel ReadOneCase2(int mID, int cID)
        {
            WBSEventViewModel v = new WBSEventViewModel();
            WBSEventM M = db.WBSEventM.Find(mID);
            //int temp = db.WBSEventC.AsEnumerable().Where(x => x.MomCaseID == mID && x.ChildCaseID == 1).Select(x => x.Num).Max(x => x);
            WBSEventC C = db.WBSEventC.Find(cID);

            v.C_ID = C.Num;
            v.CustomerAddr = M.Customer1.Addr; 
            v.CustomerID = M.Customer1.CustomerID; 
            v.CustomerRef = M.CustomerRef;
            v.CustomerSName = M.Customer1.ShortName; 
            v.CustomerUserName = M.CustomerUserName;
            v.CustomerUserPhone1 = M.CustomerUserPhone1;
            v.CustomerUserPhone2 = M.CustomerUserPhone2;
            v.CustomerUserPhone = M.CustomerUserPhone1;
            if (M.CustomerUserPhone2 != null && M.CustomerUserPhone2 != "")
                v.CustomerUserPhone += " /" + M.CustomerUserPhone2;
            v.CustomerCaseNum = M.CustomerCaseNum;
            //20150811新增-Hsiuyang
            v.ChangeAddr = M.CustomerAddr;
            v.SpareMach = M.SpareMach;
            v.UserMach = M.UserMach;
            v.CaseMStatus = M.CaseMStatus;

            //v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.DefaultUserName = M.Customer1.SubArea.ResponsibleClass.Name + "-" + M.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
            v.DefaultResponsibleID = M.Customer1.SubArea.ResponsibleID;
            v.ResponsibleArea = M.Customer1.SubArea.SubAreaID;

            v.ItemClass = C.ItemClass.ToString();
            v.ProductNote = C.ProductClass1.Note; //db.ProductClass.AsEnumerable().Where(x => x.ProductClassID == C.ProductClass).Select(x => x.Note).First();
            v.ItemNote = C.ItemClass1.Note; //db.ItemClass.AsEnumerable().Where(x => x.ItemClassID == C.ItemClass).Select(x => x.Note).First();
            v.QuestionNote = C.QuestionClass1.Note; //db.QuestionClass.AsEnumerable().Where(x => x.QuestionClassID == C.QuestionClass).Select(x => x.Note).First();

            v.QuestionDescription = C.QuestionDescription;
            v.ServiceReport = C.ServiceReport;

            v.M_ID = M.CaseID;
            v.ProductClass = C.ProductClass.ToString();
            v.QuestionClass = C.QuestionClass.ToString();

            int t = db.WBSEventC.Where(x => x.MomCaseID == mID).Select(x => x.ChildCaseID).Max(x => x) + 1;
            string NumberC = (t < 10) ? ("0" + t.ToString()) : t.ToString();

            v.WBSCaseNumberC = (C.ChildCaseID < 10) ? ("0" + C.ChildCaseID.ToString()) : C.ChildCaseID.ToString();
            v.WBSCaseNumberM = M.CaseClass + M.CaseDate + "-";
            if (M.CaseCode < 10)
                v.WBSCaseNumberM += "0000" + M.CaseCode.ToString();
            else if (M.CaseCode < 100 && M.CaseCode >= 10)
                v.WBSCaseNumberM += "000" + M.CaseCode.ToString();
            else if (M.CaseCode < 1000 && M.CaseCode >= 100)
                v.WBSCaseNumberM += "00" + M.CaseCode.ToString();
            else if (M.CaseCode < 10000 && M.CaseCode >= 1000)
                v.WBSCaseNumberM += "0" + M.CaseCode.ToString();
            else
                v.WBSCaseNumberM += M.CaseCode.ToString();
            v.WBSCaseNumberO = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC; 
            v.WBSCaseNumber = v.WBSCaseNumberM + "-" + NumberC;
            v.EventClass = C.EventClass;

            v.haveContract = "false";
            Boolean havaContract = false;
            if (db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Count() > 0)
                havaContract = true;
            if (havaContract) {
                v.haveContract = "true";
                v.CCProduct = C.ProductClass;
                String temp2 = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.ContractStatus).First();
                //合約狀況代碼
                switch (temp2)
                {//01.洽談中 (可能用計算方式:合約到期日 +N天) A1.總行合約中 B1.分行合約中 C1.叫修 L1.租賃中 W1.保固中 ZZ.未分類 XX.停用
                    case "01": v.ContractStatusStr = "洽談中"; break;
                    case "A1": v.ContractStatusStr = "總行合約中"; break;
                    case "B1": v.ContractStatusStr = "分行合約中"; break;
                    case "C1": v.ContractStatusStr = "叫修"; break;
                    case "L1": v.ContractStatusStr = "租賃中"; break;
                    case "W1": v.ContractStatusStr = "保固中"; break;
                    case "ZZ": v.ContractStatusStr = "未分類"; break;
                    case "XX": v.ContractStatusStr = "停用"; break;
                    default: v.ContractStatusStr = ""; break;
                }
                v.ContractStatusStr = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.ContractStatus).First();
                v.MaintainNum = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.MaintainNum).First();
                v.MaintainMonthMemo = db.CustomerContract.Where(x => x.CustomerRef == M.CustomerRef && x.ProductID == M.ProductID).Select(x => x.MaintainMonthMemo).First();
            }

            return v;
        }
        //客戶叫修主畫面-叫修案件讀取 20150818-刪除子單不讀-Hsiuyang        
        public IQueryable<WBSEventViewModel> Read()
        {
            List<WBSEventViewModel> ret = new List<WBSEventViewModel>();

            List<AlertDetailSettingViewModel> alertMList = new List<AlertDetailSettingViewModel>();
            var Aqry = db.AlertDetailSetting;
            foreach (AlertDetailSetting o in Aqry)
            {
                AlertDetailSettingViewModel a = new AlertDetailSettingViewModel();
                a.EventClass = o.EventClass;
                a.AlertEvent = o.AlertEvent;
                a.FirstTime = o.FirstTime;
                alertMList.Add(a);
            }

            var qry = db.WBSEventM.Where(x => x.CaseClass != "M");
            foreach (WBSEventM m in qry)
            {
                var qry2 = db.WBSEventC.Where(x => x.MomCaseID == m.CaseID && x.EventStatus != 0 && x.EventStatus < 30);
                var qry3 = db.Customer.Where(x => x.CustomerRef == m.CustomerRef);
                //var qry4 = db.ProductClass.Where(x => x.)
                String Addr = "", SName = "", FName = "";
                foreach (Customer o in qry3)
                {
                    Addr = o.Addr;
                    SName = o.ShortName;
                    FName = o.FullName;
                }

                foreach (WBSEventC c in qry2)
                {
                                        
                    String ProductNote = "", ItemNote = "" ,QuestionNote = "";
                    var qry4 = db.ProductClass.Where(x => x.ProductClassID == c.ProductClass);
                    foreach (ProductClass o in qry4)
                    {                        
                        ProductNote = o.Note;                        
                    }

                    var qry5 = db.ItemClass.Where(x => x.ItemClassID == c.ItemClass);
                    foreach (ItemClass o in qry5)
                    {
                        ItemNote = o.Note;
                    }

                    var qry6 = db.QuestionClass.Where(x => x.QuestionClassID == c.QuestionClass);
                    foreach (QuestionClass o in qry6)
                    {
                        QuestionNote = o.Note;
                    }


                    WBSEventViewModel v = new WBSEventViewModel();
                    v.M_ID = m.CaseID;
                    v.C_ID = c.Num;
                    //v.WBSCaseNumberM = m.CaseClass + m.CaseDate + m.CaseCode;
                    v.WBSCaseNumberM = m.CaseClass + m.CaseDate + "-";
                    if (m.CaseCode < 10)
                        v.WBSCaseNumberM += "0000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 100 && m.CaseCode >=10)
                        v.WBSCaseNumberM += "000" + m.CaseCode.ToString();
                    else if (m.CaseCode < 1000 && m.CaseCode >=100)
                        v.WBSCaseNumberM += "00" + m.CaseCode.ToString();
                    else if (m.CaseCode < 10000 && m.CaseCode >=1000)
                        v.WBSCaseNumberM += "0" + m.CaseCode.ToString();
                    else
                        v.WBSCaseNumberM += m.CaseCode.ToString();
                    v.WBSCaseNumberC = (c.ChildCaseID < 10) ? ("0"+c.ChildCaseID.ToString()) : c.ChildCaseID.ToString();
                    v.WBSCaseNumber = v.WBSCaseNumberM + "-" + v.WBSCaseNumberC;
                    v.EventClass = c.EventClass;
                    v.EventClassStr = c.EventClass + "-" + db.EventClass.Where(x => x.Class == c.EventClass).Select(x => x.Name).First(); ;
                    v.CustomerRef = m.CustomerRef;
                    v.CustomerAddr = Addr;
                    v.CustomerSName = SName;
                    v.CustomerUserID = m.CustomerUserID;
                    v.CustomerUserName = m.CustomerUserName;
                    v.CustomerUserPhone1 = m.CustomerUserPhone1;
                    v.CustomerUserPhone2 = m.CustomerUserPhone2;
                    v.CustomerUserPhone = m.CustomerUserPhone1;
                    if (m.CustomerUserPhone2 != null && m.CustomerUserPhone2 != "")
                        v.CustomerUserPhone += " /" + m.CustomerUserPhone2;
                    v.CustomerCaseNum = m.CustomerCaseNum;
                    v.ProductClass = c.ProductClass.ToString();
                    v.ProductNote = ProductNote;
                    v.ItemClass = c.ItemClass.ToString();
                    v.ItemNote = ItemNote;
                    v.QuestionClass = c.QuestionClass.ToString();
                    v.QuestionNote = QuestionNote;
                    v.QuestionNoteAll = ProductNote + "-" + ItemNote + "-" + QuestionNote;
                    v.QuestionGrade = c.QuestionGrade.ToString();
                    v.QuestionServiceHours = c.QuestionServiceHours.ToString();
                    v.QuestionDescription = c.QuestionDescription;

                    v.EventStatus = c.EventStatus;
                    v.EventStatusStr = (v.EventStatus == 0) ? "0" + v.EventStatus.ToString() : v.EventStatus.ToString();                    
                    v.EventStatusStr += "." + GetEventStatusStr(v.EventStatus);

                    v.HasActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 1).Count() > 0)
                        v.HasActtachment = "@";

                    v.HasAssignActtachment = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 2).Count() > 0)
                        v.HasAssignActtachment = "@";

                    v.HasKnowledge = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 3).Count() > 0)
                        v.HasKnowledge = "@";

                    v.HasHyperlink = "";
                    if (db.Files.Where(x => x.CID == c.Num && x.Class == 9).Count() > 0)
                        v.HasHyperlink = "@";

                    v.QuestionCreateUserID = c.QuestionCreateUserID;
                    v.QuestionCreateDT = c.QuestionCreateDateTime;
                    v.ExpectArriveDT = c.ExpectArriveDateTime;
                    v.ExpectFinishDT = c.ExpectFinishDateTime;
                    v.ExpectArriveSW = c.ExpectArriveSW;

                    v.ExpectArriveDTStr = (c.ExpectArriveDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    v.ExpectFinishDTStr = (c.ExpectFinishDateTime ?? DateTime.Now).ToString("yyyyMMdd HH:mm");
                    
                    if (c.ExpectArriveSW == "1")
                        v.ExpectArriveSWStr = "合約規定";
                    else if (c.ExpectArriveSW == "2")
                        v.ExpectArriveSWStr = "建議期望";
                    else if (c.ExpectArriveSW == "3")
                        v.ExpectArriveSWStr = "客戶指定";
                    else if (c.ExpectArriveSW == "4")
                        v.ExpectArriveSWStr = "自派新單";
                    else
                    {
                        v.ExpectArriveSWStr = "自行約定";
                        v.ExpectArriveDTStr = "請自行與客戶約定";
                        v.ExpectFinishDTStr = "請自行與客戶約定";
                    }  

                    v.DeleteMarkSW = c.DeleteMarkSW;
                    v.DeleteReason = c.DeleteReason;
                    v.DeleteMarkUserID = c.DeleteMarkUserID;
                    v.DeleteMarkDT = c.DeleteMarkDateTime;
                    v.CreateDT = c.CreateDateTime;
                    v.CreateD = c.CreateDateTime.Value.Date;
                    v.CreateDTStr = (c.CreateDateTime ?? DateTime.Now).ToString("yyyy/MM/dd HH:mm");
                    v.CreateYYYYStr = (c.CreateDateTime ?? DateTime.Now).ToString("yyyy");
                    v.CreateMMDDStr = (c.CreateDateTime ?? DateTime.Now).ToString("MM/dd HH:mm");
                    v.CreateHHmmStr = (c.CreateDateTime ?? DateTime.Now).ToString("HH:mm");
                    v.CreateUserID = c.CreateUserID;
                    v.CreateUserName = db.UserData.AsEnumerable().Where(x => x.UserID == c.CreateUserID).Select(x => x.UserName).First();
                    v.ModifyDT = c.ModifyDateTime;
                    v.ModifyUserID = c.ModifyUserID;

                    v.ResponsibleUserName = "";
                    if (c.EventStatus >= 21)
                    {
                        if (c.ResponsibleID != null)
                        {
                            var RegionID = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == c.ResponsibleID).Select(x2 => x2.UserID).First();
                            v.ResponsibleUserName = c.ResponsibleClass.Name + "-" + db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                        }
                        //if (c.ResponsibleClass != null)
                        //    v.ResponsibleUserName = c.ResponsibleClass.UserData2.UserName;
                        else //線上結案
                            v.ResponsibleUserName = "";
                    }

                    v.MaintainNum = "";
                    int maintainNum = db.EventRelation.Where(x => x.CID == c.Num).Count();
                    if (maintainNum != 0)
                        v.MaintainNum = maintainNum.ToString();

                    //已開立時間
                    System.TimeSpan diff1 = DateTime.Now.Subtract(c.CreateDateTime ?? DateTime.Now);
                    //v.ServiceDT = Convert.ToDateTime(diff1.ToString());
                    int day = Int32.Parse(diff1.ToString("%d"));
                    int hour = Int32.Parse(diff1.ToString("%h"));
                    hour += day * 24;
                    v.CreatedTime = hour.ToString() + ":" + diff1.ToString(@"mm\:ss");

                    int temp = 0;                    
                    if (alertMList.Exists(x => x.EventClass == c.EventClass))
                        temp = alertMList.Find(x => x.EventClass == c.EventClass && x.AlertEvent == 1).FirstTime;
                    else
                        temp = alertMList.Find(x => x.EventClass == null && x.AlertEvent == 1).FirstTime;
                    if (c.CreateDateTime.Value.AddMinutes(temp).CompareTo(DateTime.Now) < 0)
                    {
                        //派單後超過"開單時間"N分未接受
                        if (c.EventStatus == 11)
                        {
                            v.AbnormalReason = "逾時未派工";
                        }                            
                        else if (c.EventStatus == 20)
                        {
                            v.AbnormalReason = "逾時未重派";
                        }
                        else if (c.EventStatus == 21)
                        {
                            v.AbnormalReason = "逾時未接受";
                        }
                    }
                    
             

                    List<AlertDetailSettingViewModel> AlertDetailList = alertSettingRepository.ReadAlertDetail(v.EventClass);
                    //v.OverTime = "";
                    //v.OverTimeDisplay = "none";
                    //TimeSpan duration = new TimeSpan(0, 0, AlertDetailList[0].FirstTime, 0);
                    
                    //if (diff1.CompareTo(duration) > 0)
                    //{
                    //    if (v.EventStatus < 30)
                    //    {
                    //        if (v.EventStatus == 11)
                    //            v.OverTime = "派工逾時";
                    //        else if (v.EventStatus == 21)
                    //            v.OverTime = "確認逾時";
                    //        else if (v.EventStatus == 20)
                    //            v.OverTime = "派工被拒";
                    //        v.OverTimeColor = "Red";
                    //        v.OverTimeDisplay = "";
                    //    }
                    //}
                    //if (v.EventStatus == 20)
                    //{
                    //    v.OverTime = "派工被拒";
                    //    v.OverTimeColor = "Red";
                    //    v.OverTimeDisplay = "";
                    //}

                    //v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.DefaultUserName = m.Customer1.SubArea.ResponsibleClass.Name + "-" + m.Customer1.SubArea.ResponsibleClass.UserData2.UserName;
                    v.ResponsibleArea = m.Customer1.SubArea.SubAreaID;
                    if (m.Customer1.SubArea.ResponsibleID2 != null)
                    {
                        v.DefaultUserName2 = m.Customer1.SubArea.ResponsibleClass1.Name + "-" + m.Customer1.SubArea.ResponsibleClass1.UserData2.UserName;
                        v.ResponsibleArea2 = m.Customer1.SubArea.SubAreaID;
                    }
                    
                    //v.DefaultUserName = db.UserData.AsEnumerable().Where(x => x.UserID == RegionID).Select(x => x.UserName).First();
                    //v.ResponsibleArea = db.ResponsibleClass.AsEnumerable().Where(x2 => x2.ID == RID1).Select(x2 => x2.SubAreaID).First();


                    ret.Add(v);
                }                
            }
            return ret.AsQueryable();
        }
        public ActionResult WBSEventMain_Destroy([DataSourceRequest] DataSourceRequest request, WBSEventViewModel wBSEvent)
        {
            if (wBSEvent != null)
            {
                //productService.Destroy(wBSEvent);
            }

            return Json(new[] { wBSEvent }.ToDataSourceResult(request, ModelState));
        }