using LHDN.CRM.BC.Common;
using LHDN.CRM.BC.Services;
using LHDN.CRM.Models.Models;
using LHDN.CRM.Models.ViewModels;
using LHDN.CRM.WebAPI.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Caching;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;

namespace LHDN.CRM.WebAPI.Controllers.Api
{

    [ApiErrorHandler]
    public class ActivityApiController : BaseApiController
    {
        private BC.Services.ActivityService svc = new BC.Services.ActivityService();
        private UserProfileService userSvc = new UserProfileService();
        private EmailService emailSvc = new EmailService();
        private BC.Services.WorkflowService workflowsvc = new BC.Services.WorkflowService();
        BC.Services.CaseService caseSvc = new BC.Services.CaseService();

        [HttpGet]
        [CacheWebApi]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.ViewActivityProfile)]
        public IHttpActionResult GetActivity(long id )
        {
            ActivityViewModel data = null;
            string strUserID = userSvc.LoginID;
            data = svc.GetById(id,false,userSvc.UserInfo);

            //if (data == null) 
            //throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Activity not found!"));

            DateTime dtNow = DateTime.Now;

            AuditLogTxn(AuditService.AuditEventID.ViewActivityProfile,
                AuditService.ResultType.Success,
                AuditService.ActionType.View,
                strUserID,
                dtNow,
                "View Activity", null, "Activity", id);

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateProfile)]
        //[CRMAuthorize(Constant.Authentication.TaxPayer.ViewTaxPayer)]
        //[Authorize(Roles = "role1")]
        public IHttpActionResult GetNewActivity(OpenNewActViewModel o)
        {
            ActivityViewModel data = null;

            data = svc.GetNewActivity(o, userSvc.UserInfo);

            //if (data != null)
            //{
            //    data.CurrentUserUnitID = userSvc.UnitID;
            //}

            //AuditLogTxn("test", "field");

            return Json(data);
        }


        [HttpGet]
        //[CRMAuthorize(Constant.Authentication.ViewTaxPayer)]
        public IHttpActionResult GetActivityDDLOptions()
        {
            //AuditLogTxn("test", "field");

            return Json(svc.GetActivityDDLOptions(userSvc.RoleTindakanSusulan));
        }

        [HttpGet]
        public IHttpActionResult GetActEmailTemplateDDLOptions( )
        {
            TemplatesViewModel vm = null;
            List<TypeViewModel> lstTemplateTypeA = new List<TypeViewModel>();
            lstTemplateTypeA.Add(new TypeViewModel { Type = Constant.EmailTemplateType.EFailing });

            List<TypeViewModel> lstTemplateTypeB = new List<TypeViewModel>(); 
            lstTemplateTypeB.Add(new TypeViewModel { Type = Constant.EmailTemplateType.General });

            vm = svc.GetActEmailTemplateDDLOptions(userSvc.LoginID, lstTemplateTypeA, lstTemplateTypeB);

            return Json(vm);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        // Commented out for draft, system aut save
        //[CRMAuthorize(Constant.Authentication.Activity.CreateUpdateProfile)]
        public IHttpActionResult SaveActivity(ActivityUpdateViewModel model)
        {
            var data = CreateActivity(model);
            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateProfile)]
        public IHttpActionResult CloseActivityEmail(SendEmailViewModel model)
        {
            long lngActivityID = model.ReftableId;
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;
            DateTime dtNow = DateTime.Now;
            long i = emailSvc.SendEmail(model.EmailFromList, model.EmailToList, model.EmailCCList, model.EmailBCCList, model.TemplateId, model.Content, model.Subject, lngActivityID, strUserID, dtNow, (int)Constant.TableType.Activity , lngActivityID);

            byte[] ChangeStamp = svc.CloseActivityAndLinkedInboundActivities(model.ActStatusUpdateModel, strUserName, strUserID, dtNow);

            // TODO : Transaction Scope
            AuditLogTxn(AuditService.AuditEventID.SendEmail, //TODO Audit EnventID for Delete Activity
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        strUserID,
                        dtNow,
                        string.Format(Constant.AuditAdditionalInfo.ActivitySendEmail, strUserName, strUserID , lngActivityID), null, "Activity", lngActivityID);

            return Json(new { ChangeStamp = ChangeStamp });
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.DeleteActivity)]
        public IHttpActionResult DeleteActivity(EntityUpdateViewModel model)
        {
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;
            DateTime dtNow = DateTime.Now;
            bool blnIsSuccess = svc.DeleteActivity(model, strUserName, strUserID, dtNow);
            if (blnIsSuccess)
            {

                // TODO : Transaction Scope
                AuditLogTxn(AuditService.AuditEventID.DeleteActivity, //TODO Audit EnventID for Delete Activity
                            AuditService.ResultType.Success,
                            AuditService.ActionType.Delete,
                            strUserID,
                            dtNow,
                            "Hapus Aktiviti", null, "Activity", model.ActivityID);

                // Insert Recent Activity
                RecentActivityTxn("Activity", (long)model.ActivityID, string.Format(Constant.RecentActivity.ActivityDeletedMsg, model.ActRefNo), strUserID, strUserName, dtNow, string.Format(Constant.RecentActivity.ActivityURL, model.ActivityID));
            }

            return Json(new { IsSuccess = blnIsSuccess });
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.ViewActivityProfile)]
        public IHttpActionResult GetPagedActivityListByID(ActivityListPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetActivityListByID(paging, out intCount);
            DTResultViewModel<ActivityListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<ActivityListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }


        [HttpPost()]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult UpdateActCatatan(ActCatatanViewModel model)
        {
            string strText = "Update Activity Catatan";
            var actionType = AuditService.ActionType.Update;

            DateTime dtNow = DateTime.Now;
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;

            List<ChangeHistoryUpdateViewModel> lstChangeHist = svc.UpdateActCatatan(model, strUserName, strUserID, dtNow);

            //get lstActCatatan
            var data = svc.GetAllActCatatan(model.ActivityID);

            AuditLogTxn(AuditService.AuditEventID.CreateUpdateActivityCatatan,
                            AuditService.ResultType.Success,
                            actionType,
                            strUserID,
                            dtNow,
                            strText,
                            lstChangeHist.Select(a => new AuditDetailViewModel
                            {
                                FieldName = a.DisplayName,
                                OldValue = a.OldValue,
                                NewValue = a.NewValue
                            }).ToList(), "Act_Catatan", model.CatatanID);

            return Json(data);

        }

        [HttpPost()]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult AddActCatatan(ActCatatanViewModel model)
        {
            string strText = "Insert Activity Catatan";
            var actionType = AuditService.ActionType.Add;

            DateTime dtNow = DateTime.Now;
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;

            long lngActCatatanID = svc.InsertActCatatan(model, strUserName, strUserID, dtNow);

            //get lstActCatatan
            var data = svc.GetAllActCatatan(model.ActivityID);

            AuditLogTxn(AuditService.AuditEventID.CreateUpdateActivityCatatan,
                        AuditService.ResultType.Success,
                        actionType,
                        strUserID,
                        dtNow,
                        strText, null, "ActCatatanID", model.CatatanID);

            return Json(data);
        }

        [HttpPost()]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult DeleteActCatatan(ActCatatanViewModel model)
        {
            string strText = "Hapus Aktiviti Catatan";
            var actionType = AuditService.ActionType.Delete;

            DateTime dtNow = DateTime.Now;
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;

            List<ChangeHistoryUpdateViewModel> lstChangeHist = svc.DeleteActCatatan(model, strUserName, strUserID, dtNow);

            //get lstActCatatan
            var data = svc.GetAllActCatatan(model.ActivityID);


            AuditLogTxn(AuditService.AuditEventID.CreateUpdateActivityCatatan,
                            AuditService.ResultType.Success,
                            actionType,
                            strUserID,
                            dtNow,
                            strText,
                            lstChangeHist.Select(a => new AuditDetailViewModel
                            {
                                FieldName = a.DisplayName,
                                OldValue = a.OldValue,
                                NewValue = a.NewValue
                            }).ToList(), "ActCatatanID", model.CatatanID);

            return Json(data);

        }

        [HttpPost()]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public async Task<IHttpActionResult> UploadAttachment()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                //throw new UnsupportedMediaTypeException( );
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            TempAttachmentViewModel a = new TempAttachmentViewModel();
            DateTime dtNow = DateTime.Now;

            if (HttpContext.Current.Request.Files.Count > 0)
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(streamProvider);
                foreach (HttpContent item in streamProvider.Contents)
                {
                    string strFileName = item.Headers.ContentDisposition.FileName.Replace("\"", String.Empty);
                    byte[] yArrFileContent = item.ReadAsByteArrayAsync().Result;
                    a.FileName = strFileName;
                    a.FileContent = yArrFileContent;
                    a.FileContentType = MimeMapping.GetMimeMapping(strFileName); //Path.GetExtension(strFileName); 
                    a.CreatedDateTime = dtNow;
                }
            }

            var data = svc.InsertTempAttachment(a);

            return Json(data);
        }

        [HttpGet]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult GetAttachment(string type, long id)
        {   //id -- AttachmentID //type -- Attachment Table
            DataTable dtbl = svc.GetAttachment(type, id);
            if (dtbl != null && dtbl.Rows.Count > 0)
            {
                string strFileName = dtbl.Rows[0][0].ToString();
                string strContentType = dtbl.Rows[0][1].ToString();
                byte[] FileContent = (byte[])dtbl.Rows[0][2];

                MemoryStream stream = new MemoryStream(FileContent);

                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                };

                httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = strFileName
                };
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(strContentType);

                ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
                return responseMessageResult;
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.NoContent);
            }
        }

        [HttpGet]
        [CRMAuthorize(Constant.Authentication.Activity.ViewActivityProfile)]
        //[CRMAuthorize(Constant.Authentication.UpdateTaxPayer)]
        public IHttpActionResult GetCFFSummaryAttachment(long id)
        {
            DataTable dtbl = svc.GetCFFSummaryAttachment(id);
            //object result = null;
            ResponseMessageResult responseMessageResult = null;
            if (dtbl != null && dtbl.Rows.Count > 0)
            {
                string strContentType = dtbl.Rows[0]["FileContentType"].ToString();
                byte[] byteFileContent = dtbl.Rows[0]["FileContent"] == DBNull.Value ? null : (byte[])dtbl.Rows[0]["FileContent"];

                if (byteFileContent != null)
                {
                    MemoryStream stream = new MemoryStream(byteFileContent);
                    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StreamContent(stream)
                    };

                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
                    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(string.IsNullOrEmpty(strContentType) ? "application/pdf" : strContentType);

                    responseMessageResult = ResponseMessage(httpResponseMessage);
                    return responseMessageResult;
                }
            }
            return Json(responseMessageResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult DeleteAttachment([FromBody]long TempAttachmentID)
        {
            svc.DeleteTempAttachment(TempAttachmentID);

            return Ok();
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.TransfertoCase)]
        public IHttpActionResult LinkUnlinkActivity(EntityUpdateViewModel model)
        {
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;
            DateTime dtNow = DateTime.Now;
            bool blnIsSuccess = false;
            List<ChangeHistoryUpdateViewModel> lstChgHistory = null;
            byte[] ChangeStamp = null;
            var data = new ActivityViewModel();
            blnIsSuccess = svc.LinkUnlinkActivity(model, strUserName, strUserID, dtNow, out data, out lstChgHistory, out ChangeStamp);

            if (blnIsSuccess)
            {
                //ChangeStamp = svc.GetChangeStampbyID(model.ActivityID.GetValueOrDefault());
                AuditLogTxn(AuditService.AuditEventID.TransfertoCase,  //TODO Audit EnventID for Delete Activity
                       AuditService.ResultType.Success,
                       AuditService.ActionType.Update,
                       strUserID,
                       dtNow,
                       "Pautan Kes dari Aktiviti",
                         new AuditDetailViewModel[1].Select(h => new AuditDetailViewModel()
                         {
                             FieldName = "Kes No.",
                             OldValue = (model.IsLinkCase == true) ? "" : model.CaseRefNo,
                             NewValue = (model.IsLinkCase == true) ? model.CaseRefNo : ""
                         }).ToList(), "Activity", model.ActivityID);

                //if (model.IsLinkCase == true)
                //{
                //    AuditLogTxn(AuditService.AuditEventID.TransfertoCase,
                //       AuditService.ResultType.Success,
                //       AuditService.ActionType.Update,
                //       strUserID,
                //       dtNow,
                //       "Pautan Kes dari Aktiviti: Kemaskini Aktiviti maklumat dari Kes",
                //        lstChgHistory.Select(a => new AuditDetailViewModel
                //        {
                //            FieldName = a.DisplayName,
                //            OldValue = a.OldValue,
                //            NewValue = a.NewValue
                //        }).ToList(), "Activity", model.ActivityID);
                //}

            }
            return Json(new { IsSuccess = blnIsSuccess, ChangeStamp = ChangeStamp, data });
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.ReopenActivity)]
        public IHttpActionResult ReopenActivity(EntityUpdateViewModel model)
        {
            string strUserName = userSvc.DisplayName;
            string strUserID = userSvc.LoginID;
            DateTime dtNow = DateTime.Now;
            int intActStatusID = 0;

            byte[] ChangeStamp = svc.ReopenActivity(model, strUserName, strUserID, dtNow, out intActStatusID);

            // TODO : Transaction Scope
            AuditLogTxn(AuditService.AuditEventID.ReopenActivity, //TODO Audit EnventID for Delete Activity
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        strUserID,
                        dtNow,
                        "Buka Semula Aktiviti", null, "Activity", model.ActivityID);
            
            return Json(new { ChangeStamp = ChangeStamp, ActStatusID= intActStatusID, ActStatus1ID = (int)Constant.StatusLevel1.BelumSelesai, ActStatus2ID = (int)Constant.StatusLevel2.Normal , ActStatus3ID= 0 });
        }

        [HttpGet]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateCatatan)]
        public IHttpActionResult GetAllCatatanInString(long id)
        {
            return Json(svc.GetAllCatatanInString(0, id));
        }

        [HttpPost]
        [ValidateAjaxRequest]
        //[CRMAuthorize(Constant.Authentication.UpdateTaxPayer)]
        public IHttpActionResult GetMyPendingActInDashboard(PendingActivityPagedListViewModel paging)
        {
            string strCreatedBy = userSvc.LoginID;
            int intCount = 0;

            var lst = svc.GetPendingActivityByName(strCreatedBy, paging, out intCount);

            DTResultViewModel<PendingActivityPagedListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<PendingActivityPagedListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpGet]
        //[CRMAuthorize(Constant.Authentication.UpdateTaxPayer)]
        public IHttpActionResult GetNewSessionKey()
        {

            return Json(Guid.NewGuid());
        }

        [HttpGet]
        //[CRMAuthorize(Constant.Authentication.UpdateTaxPayer)]
        public IHttpActionResult GetChangeStampbyID(long id)
        {
            byte[] ChangeStamp = svc.GetChangeStampbyID(id);
            return Json(new { data = ChangeStamp });
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.CreateUpdateProfile)]
        public IHttpActionResult SaveActSession(List<ActSession> lstActSession)
        {
            svc.InsertActSession(lstActSession);
            return Ok();
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult PrintSlipKedatangan(OpenNewActViewModel model)
        {
            string strContent = svc.PrintSlipKedatangan((long)model.ActID, userSvc.DisplayName);

            return Json(strContent);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.ViewActivityProfile)]
        public IHttpActionResult GetOutboundCountByTP(CountOutboundByTPViewModel model)
        {  
            return Json(svc.GetOutboundCountByTP(model));

        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAssignActivityForUnit(PendingActivityPagedListViewModel paging)
        {
            int intCount = 0;
            paging.UnitId = userSvc.UnitID;

            var lst = svc.GetPendingActByManagerPool(paging, userSvc.UserInfo.LoginID, out intCount);

            DTResultViewModel<PendingActivityPagedListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<PendingActivityPagedListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);

        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAssignedInboundCFFDraftActivity(PendingActivityPagedListViewModel paging)
        {
            int intCount = 0;
            string strLoginID = userSvc.LoginID;

            var lst = svc.GetAssignedInboundCFFDraftActivity(strLoginID,paging, out intCount);

            DTResultViewModel<PendingActivityPagedListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<PendingActivityPagedListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);

        }


        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetActWorkFlowAssignToByKategoryId(WorkflowAssignToUnitIDViewModel Kategory)
        {
            WorkflowAssignToUnitIDViewModel data = null;
            data = workflowsvc.GetWorkFlowAssignToByKategoryId(Kategory);

            WorkflowUserViewModel assignedUser = new WorkflowUserViewModel();
            if (data != null)
            {
                if (data.ID == -1)
                {
                    assignedUser.DisplayName = data.DisplayName;
                    assignedUser.ID = data.ID.ToString();
                }
                else
                {
                    assignedUser.DisplayName = data.DisplayName;
                    assignedUser.ID = data.ID.ToString();
                    assignedUser.AssignToType = data.AssignToTypeID;
                    assignedUser.ManagerFunctionRoleID = data.ManagerFunctionRoleID;
                }

            }
            else
            {
                assignedUser.DisplayName = "No default unit";
                assignedUser.ID = "-1";
            }

            return Json(assignedUser);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetActWorkFlowSearchUserOrUnit(WorkflowUserViewModel data)
        {
            var managerLoginId = userSvc.Manager !=null ? userSvc.Manager.ID  : null; //Get Manager LoginId
            data.ManagerId = managerLoginId != null ? managerLoginId : "";

            return Json(workflowsvc.GetWorkFlowAllUserOrUnit(data));
        }       

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.AssignActivityProfile)]
        public IHttpActionResult InsertActWorkflowAction(WorkflowUpdateViewModel workflowModel)
        {
            string strCreatedBy = userSvc.LoginID;
            string strLastUpdatedBy = userSvc.LoginID;
            string strCreatedByName = userSvc.DisplayName;
            string strLastUpdatedByName = userSvc.DisplayName;
            string strCurrentUserEmail = userSvc.Email;
            DateTime dtNow = DateTime.Now;
            WorkflowUserViewModel assignedUser = new WorkflowUserViewModel();
            string strDescription = "";
            string strCaseRefNo = "";
            string strActRefNo = "";
            DataTable dTblResult = new DataTable();
            bool blnAlertIsRead = false;
            string strAssignToEmail = string.Empty;

            workflowModel.Workflow.CreatedBy = strCreatedBy;
            workflowModel.Workflow.LastUpdatedBy = strLastUpdatedBy;
            workflowModel.Workflow.LastUpdatedByName = strLastUpdatedByName;
            workflowModel.Workflow.AssignBy = strCreatedBy;
            workflowModel.Workflow.AssignByName = strCreatedByName;
            workflowModel.Workflow.AssignByEmail = strCurrentUserEmail;
            workflowModel.Workflow.TableType = (int)Constant.TableType.Activity;


            var data = workflowsvc.UpdateWorkflow(workflowModel, out strCaseRefNo,out strActRefNo, out dTblResult, ref assignedUser, dtNow);

            string strMsg = "";
            if (data != null)
            {
                //Audit
                if (workflowModel.Workflow.DecisionID == (int)Constant.WorkFlow.WorkflowDecision.Assign)
                {
                    strMsg = string.Format("{0} {1}", Constant.WorkFlow.WorkflowDecision.Assign.ToString(), " Activity");
                    strDescription = string.Format(Constant.RecentActivity.ActivityAssignmentCreatedMsg, strActRefNo);
                }
                else if (workflowModel.Workflow.DecisionID == (int)Constant.WorkFlow.WorkflowDecision.Recall)
                {
                    strMsg = string.Format("{0} {1}", Constant.WorkFlow.WorkflowDecision.Recall.ToString(), " Activity");
                    strDescription = string.Format(Constant.RecentActivity.ActivityAssignmentRecallMsg, strActRefNo);
                }
                else if (workflowModel.Workflow.DecisionID == (int)Constant.WorkFlow.WorkflowDecision.Return)
                {
                    strMsg = string.Format("{0} {1}", Constant.WorkFlow.WorkflowDecision.Return.ToString(), " Activity");
                    strDescription = string.Format(Constant.RecentActivity.ActivityAssignmentReturnMsg, strActRefNo);
                }
                else
                {
                    strMsg = string.Format("{0} {1}", Constant.WorkFlow.WorkflowDecision.Reassign.ToString(), " Activity");
                    strDescription = string.Format(Constant.RecentActivity.ActivityAssignmentUpdatedMsg, strActRefNo);
                }

                AuditLogTxn(AuditService.AuditEventID.AssignBackOffice,
                  AuditService.ResultType.Success,
                  AuditService.ActionType.Update,
                  userSvc.DisplayName,
                  dtNow, strMsg,
                   data.Select(a => new AuditDetailViewModel
                   {
                       FieldName = a.DisplayName,
                       OldValue = a.OldValue,
                       NewValue = a.NewValue
                   }).Cast<AuditDetailViewModel>().ToArray().ToList(),
                    "Workflow", workflowModel.Workflow.ActivityID
                );
            }

            // Insert Recent Activity
            RecentActivityTxn("Activity Assignment", workflowModel.Workflow.ActivityID, strDescription, workflowModel.Workflow.CreatedBy, workflowModel.Workflow.AssignByName, dtNow, string.Format(Constant.RecentActivity.ActivityURL, workflowModel.Workflow.ActivityID));

            if (dTblResult != null && dTblResult.Rows.Count > 0)
            {
                foreach (DataRow row in dTblResult.Rows)
                {
                    //Insert Task Alert
                    RecentTaskAlertNotify(row["AssignToLogin"].ToString(), (short)(Constant.TableType.Activity), workflowModel.Workflow.ActivityID, (int)(Constant.MessageType.New), string.Format(Constant.RecentActivity.TaskAlertForActivity, strActRefNo),
                                  string.Format(Constant.RecentActivity.ActivityURL, workflowModel.Workflow.ActivityID), blnAlertIsRead, strLastUpdatedBy, workflowModel.Workflow.AssignByName, dtNow);
                    strAssignToEmail += row["AssignToEmail"].ToString() + ",";
                }

            }
         
            if (!string.IsNullOrEmpty(strAssignToEmail))
            {
                strAssignToEmail = strAssignToEmail.TrimEnd(',');
                List<string> lstEmailTo = new List<string>();
                List<string> lstEmailCC = new List<string>();
                lstEmailTo.Add(strAssignToEmail);
               
                long i = emailSvc.SendEmailNotification(lstEmailTo, lstEmailCC, (int)Constant.EmailTemplate.ActBackOfficeReviewNotification, workflowModel.Workflow.CreatedBy, workflowModel.Workflow.ActivityID, dtNow);
            }

            return Json(data);

        }


        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Activity.PrintNotaTemuduga)]
        public IHttpActionResult PrintActPenerimaanDoc(PrintPreviewViewModel model)
        {
            string strContent = svc.PrintActPenerimaanDoc(model.ActID, userSvc.DisplayName, userSvc.UserInfo.Unit.UnitName, model.QRCode, model.QRCodeDate);

            return Json(strContent);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult InsertSlipKedatanganAction(PrintActionViewModel model)
        {
            model.PrintedBy = userSvc.LoginID;
            model.PrintedDateTime = DateTime.Now;
            svc.InsertSlipKedatanganAction(model);
            return Ok();
        }

        public ActReturnViewModel CreateActivity(ActivityUpdateViewModel model)
        {
            ActReturnViewModel resultVM = new ActReturnViewModel();
            long lngActivityID = 0;
            string strActRefNo = "";
            string strDescription = "";
            string strText = "";
            byte[] arrChangeStamp = null;
            bool blnIsStatusChanged = false;
            //bool blnIsSaveDraft = false;
            DateTime dtNow = DateTime.Now;
            string strUserName = model.Activity.IsDraft == true ? Constant.System.Name : userSvc.DisplayName;
            string strUserID = model.Activity.IsDraft == true ? Constant.System.Name : userSvc.LoginID;
            string strUserEmail = model.Activity.IsDraft == true ? AdminService.ParameterSettings.Where(x => x.ParameterID == 5).FirstOrDefault().ParameterValue : userSvc.Email;
            AuditService.ActionType actionType = new AuditService.ActionType();
            AuditService.AuditEventID eventID = model.Activity.IsDraft == true ? AuditService.AuditEventID.CreateActivityDraft : AuditService.AuditEventID.CreateUpdateActivityProfile;
            TaskViewModel modelTask = null;
            AuditService.ActionType taskAuditActionType = new AuditService.ActionType();

            var data = svc.SaveActivity(model, dtNow, out lngActivityID, out strActRefNo, out blnIsStatusChanged, out arrChangeStamp, out modelTask, out taskAuditActionType, userSvc.UserInfo);

            List<AuditDetailViewModel> lstChgHistory = null;
            //TODO : 
            //1. system create draft eventid, userid =system, 
            //2. user save draft, action type= ADD, addinfo ='Create Activity From Draft'
            strText = string.Format(Constant.AuditAdditionalInfo.Activity, strUserName, strUserID, lngActivityID);

            if (model.Activity.ActivityID == 0) // Insert
            { 
                actionType = AuditService.ActionType.Add;
                strDescription = string.Format(Constant.RecentActivity.ActivityCreatedMsg, strActRefNo);
            }
            else //Update
            {
                strText = model.IsSaveDraft == true ? "Create Activity from Draft. " + strText : strText;
                actionType = model.IsSaveDraft == true ? AuditService.ActionType.Add : AuditService.ActionType.Update;
                lstChgHistory = data.Select(a => new AuditDetailViewModel
                {
                    FieldName = a.DisplayName,
                    OldValue = a.OldValue,
                    NewValue = a.NewValue
                }).ToList();

                if (blnIsStatusChanged)
                {
                    var ActivityStatus = AdminService.LookupParams.Where(x => x.LookupCode == "ActivityStatus" && x.IsActive == true && x.LookupValue == ((int)Constant.StatusLevel1.Selesai).ToString()).FirstOrDefault();
                    if (model.Activity.ActStatusID == ActivityStatus.LookupParamID)
                        strDescription = string.Format(Constant.RecentActivity.ActivityClosedMsg, strActRefNo);
                    else
                        strDescription = string.Format(Constant.RecentActivity.ActivityReopenMsg, strActRefNo);
                }
                else
                    strDescription = string.Format(Constant.RecentActivity.ActivityUpdatedMsg, strActRefNo);
            }

            AuditLogTxn(eventID,
                        AuditService.ResultType.Success,
                        actionType,
                        strUserID,
                        dtNow,
                        strText,
                        lstChgHistory, "Activity", lngActivityID);

            if (model.Activity.IsDraft != true)
                // Insert Recent Activity
                RecentActivityTxn("Activity", lngActivityID, strDescription, strUserID, strUserName, dtNow, string.Format(Constant.RecentActivity.ActivityURL, lngActivityID));

            var aliran = AdminService.LookupParams.Where(x => x.LookupCode == "Aliran" && x.IsActive == true && x.LookupValue == Constant.Aliran.Outbound).FirstOrDefault();

            //if (model.Activity.IsDraft == true && model.Activity.ActChannelID == (int)Constant.ActChannel.CFF && model.Activity.AliranID == aliran.LookupParamID)
            //{
            //    //update Case assignto
            //}

            if (Convert.ToBoolean(Utilities.GetAppSetting("IntegrateWithCFF")))
            {
                //Reply to TP = CFF & Outbound & CaseID > 0
                //var aliran = AdminService.LookupParams.Where(x => x.LookupCode == "Aliran" && x.IsActive == true && x.LookupValue == Constant.Aliran.Outbound).FirstOrDefault();
                // Integrate with Kube
                if (model.Activity.ActChannelID == (int)Constant.ActChannel.CFF && model.Activity.AliranID == aliran.LookupParamID && model.Activity.CaseID > 0)
                {
                    if (model.Activity.ActCFF != null)
                    {
                        List<long> lstCFFFormID = caseSvc.GetCFFListByCaseID((long)model.Activity.CaseID);
                        lstCFFFormID.RemoveAll(x => x == 0);
                        CRMUpdateFieldViewModel cffUpdate = new CRMUpdateFieldViewModel();
                        cffUpdate.CFFFormIDList = lstCFFFormID;
                        cffUpdate.CRMLastUpdatedDate = dtNow;
                        cffUpdate.CRMRemarks = model.Activity.ActCFF.CFFRemarks;
                        cffUpdate.CRMStatus = Constant.Status.BelumSelesai;

                        //HttpClient to call CFF.WebApi
                        //UpdateField(cffUpdate);

                        svc.InsertCFFQueue(cffUpdate, strUserID);
                    }
                }
            }

            //Task 
            if (modelTask != null && modelTask.TaskRefNo != null && modelTask.TaskStatusID == (int)Constant.TaskStatus.Open)
            {
                string strTaskRefNo = modelTask.TaskRefNo;
                long lngTaskID = modelTask.TaskID;
                string strTaskDescription = "";
                string strTaskAlertDescription = "";
                bool blnAlertIsRead = false;
                AuditService.AuditEventID taskEventID = AuditService.AuditEventID.CreateUpdateTask;
                if (taskAuditActionType == AuditService.ActionType.Update)
                {
                    strText = "Update Task";
                    strTaskDescription = string.Format(Constant.RecentActivity.TaskUpdatedMsg, strTaskRefNo);
                }
                else if (taskAuditActionType == AuditService.ActionType.Add)
                {
                    strText = "Create Task";
                    strTaskDescription = string.Format(Constant.RecentActivity.TaskCreatedMsg, strTaskRefNo);
                }
                else if (taskAuditActionType == AuditService.ActionType.Delete)
                {
                    strText = "Delete Task";
                    strTaskDescription = string.Format(Constant.RecentActivity.TaskDeletedMsg, strTaskRefNo);
                }

                AuditLogTxn(taskEventID,
                        AuditService.ResultType.Success,
                        taskAuditActionType,
                        strUserID,
                        dtNow,
                        strText,
                        null,
                        "Task", lngTaskID);

                strTaskAlertDescription = string.Format(Constant.RecentActivity.TaskAlertForTask, strTaskRefNo);

                // Insert Recent Activity
                RecentActivityTxn("Task", lngTaskID, strTaskDescription, strUserID, strUserName, dtNow, string.Format(Constant.RecentActivity.TaskURL, lngTaskID));

                //Insert Task Alert
                RecentTaskAlertNotify(modelTask.AssignToLogin, (Int16)(Constant.TableType.Task), lngTaskID, (int)(Constant.MessageType.New), strTaskAlertDescription, string.Format(Constant.RecentActivity.TaskURL, lngTaskID), blnAlertIsRead, strUserID, strUserName, dtNow);

                // Send email
                if (!string.IsNullOrEmpty(modelTask.AssignToEmail))
                {
                    List<string> lstEmailTo = new List<string>();
                    List<string> lstEmailCC = new List<string>();
                    lstEmailTo.Add(modelTask.AssignToEmail);
                    lstEmailCC.Add(strUserEmail);
                    emailSvc.SendEmailNotification(lstEmailTo, lstEmailCC, (int)Constant.EmailTemplate.TaskNotification, strUserID, lngTaskID, dtNow);
                }
            }

            resultVM.ActivityID = lngActivityID;
            resultVM.ChangeStamp = arrChangeStamp;
            resultVM.Activity = model.Activity;

            return resultVM;
        }

        [HttpPost]
        [AllowAnonymous]
        public IHttpActionResult SaveActivityCFF(ActivityUpdateViewModel model)
        {
            var data = CreateActivity(model);
            return Json(data);
        }

        [HttpGet]
        public IHttpActionResult RouteToAgent(long id = 0)
        {
            //route and get StatusCode, InteractionID
            string strUserID = userSvc.LoginID;
            var data = svc.RouteToAgent(id, strUserID);

            return Json(data);
        }

        [HttpGet]
        [CacheWebApi]
        [ValidateAjaxRequest]
        public IHttpActionResult GetActOutboundDetails(long lgOutboundId)
        {
            ActivityViewModel vm = new ActivityViewModel();
            vm.Outbound = svc.GetOutboundDetails(lgOutboundId, 0, 0);

            return Json(vm);
        }

    }
}
