using LHDN.CRM.BC.Common;
using LHDN.CRM.Models.Models;
using LHDN.CRM.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LHDN.CRM.BC.Repositories
{
    public class GeneralRepository : BaseRepository<CRMContext, Task>
    {
        public DashboardTilesViewModel GetDashboardTilesCount(string CurrentUserID)
        {
            return ExecuteSP<DashboardTilesViewModel>("proc_GetDashboardTilesCount", "@CurrentUserID", CurrentUserID).FirstOrDefault();
        }

        public MyNotificationDashboardTaskListViewModel GetMyDashboardNotification(string currentloginUser, MyNotificationDashboardTaskListViewModel paging)
        {
            int intCount = 0;
            MyNotificationDashboardTaskListViewModel NotifcationCount = new MyNotificationDashboardTaskListViewModel();

            NotifcationCount.TaskListAlert = GetTaskAlertList(currentloginUser, paging.IsSeeFullList, out intCount);
            NotifcationCount.TotalNotification = intCount;

            return NotifcationCount;
        }

        public List<TaskAlertViewModel> GetTaskAlertList(string currentloginUser, bool IsSeeFullAlertList, out int intCount)
        {
            intCount = 0;
            List<TaskAlertViewModel> TaskAlertDetail = new List<TaskAlertViewModel>();
            if (!IsSeeFullAlertList)
            {
                DataSet ds = ExecuteSP("proc_GetTaskAlertDetail", "@CurrentLoginID", currentloginUser, "@IsSeeFullAlertList", IsSeeFullAlertList);
                if (ds != null)
                {
                    if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        TaskAlertDetail = DataTableToList<TaskAlertViewModel>(ds.Tables[0]).ToList();
                        if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
                            intCount = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString());
                    }
                }
            }

            return TaskAlertDetail;
        }

        public DataSet GetAlertFullDetail(string currentloginUser, MyNotificationDashboardTaskListViewModel paging)
        {
            List<object> lstParam = new List<object>(new object[] {
                                        "@PageIndex", paging.PageIndex,
                                        "@PageSize", paging.Length,
                                        "@CurrentLoginID", currentloginUser
                                    });

            if (!string.IsNullOrEmpty(paging.SortExpression))
            {
                lstParam.AddRange(new object[] {
                "@SortExpression", paging.SortExpression
                });
            }

            return ExecuteSP("proc_GetTaskAlertDetailFullList", lstParam.ToArray());
        }

        public long InsertTaskAlertNotify(string strCurrentLoginId, Int32 intTableTypeId, long lngRefID, int intMessageTypeID, string strDescription, string strURL, bool blnIsRead, string strCreatedBy, string strCreatedByName,
                                   DateTime dtCreatedDateTime)
        {
            List<object> lstParam = new List<object>(new object[] {
                                        "@UserLoginID", strCurrentLoginId,
                                        "@TableTypeID", intTableTypeId,
                                        "@RefTableID", lngRefID,
                                        "@MessageTypeID", intMessageTypeID,
                                        "@Description", strDescription,
                                        "@URL", strURL,
                                        "@IsRead", blnIsRead,
                                        "@CreatedBy",strCreatedBy  ,
                                        "@CreatedByName", strCreatedByName,
                                        "CreatedDateTime",dtCreatedDateTime,
                                    });
            DataSet ds = ExecuteSP("proc_InsertTaskAlertNotification", lstParam.ToArray());

            long lngID = 0;
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    lngID = Convert.ToInt64(ds.Tables[0].Rows[0][0]);
                }
            }

            return lngID;
        }

        public TaskAlertViewModel UpdateAlertContent(bool blnIsContentRead, long TaskAlertID)
        {
            TaskAlertViewModel vmTaskAlert = new TaskAlertViewModel();
            vmTaskAlert = ExecuteSP<TaskAlertViewModel>("proc_UpdateTaskAlertContent", "@IsRead", blnIsContentRead, "@TaskAlertID", TaskAlertID).FirstOrDefault();

            return vmTaskAlert;

        }

        public AdvancedRulesMainViewModel GetAdvancedRulesDetails(int intViewID, int intTableType)
        {
            DataSet ds = ExecuteSP("proc_GetAdvancedRulesDetails", "@viewID", intViewID, "@tableType", intTableType);
            AdvancedRulesMainViewModel vmAdvRule = new AdvancedRulesMainViewModel();
            if (ds != null)
            {
                vmAdvRule = Utilities.RetrieveAdvanceRulesViewModel(ds);
            }

            return vmAdvRule;
        }

        public DashboardTilesStatusViewModel GetActDashboardWidget()
        {
            return ExecuteSP<DashboardTilesStatusViewModel>("proc_GetDashboardTilesByTableType", "@TableType", (int)Constant.TableType.Activity).FirstOrDefault();
        }

        public long UpdateTaskOverdue(long lgTaskID, bool blnIsActive, string LastUpdatedBy, DateTime dtnow)
        {
            List<object> lstParam = new List<object>(new object[] {
                                        "@TaskID", lgTaskID,
                                        "@IsActive", blnIsActive,
                                        "@LastUpdatedBy",LastUpdatedBy,
                                        "@LastUpdatedDateTime",dtnow,
                                       });

            DataSet ds = ExecuteSP("proc_UpdateOverdueTask", lstParam.ToArray());
            long lngID = 0;
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    lngID = Convert.ToInt64(ds.Tables[0].Rows[0][0]);
                }
            }

            return lngID;

        }

        public TaskAlertViewModel GetTaskAlertDetail(string strCurrentUserLoginId, long reftableId)
        {
            TaskAlertViewModel taskAlertDetail = new TaskAlertViewModel();

            taskAlertDetail = ExecuteSP<TaskAlertViewModel>("proc_GetTaskAlertDetailByAssignToLogin", "@RefTableId", reftableId, "@CurrentAssignToLoginID", strCurrentUserLoginId).FirstOrDefault();
            return taskAlertDetail;

        }

        public long GetCFFID()
        {
            return ExecuteUpdateSPRetLong("proc_GetCFFLastSubmissionID");
        }

        public DataSet GetCRMKategori1AndSkillSet(string strCFFSubKategori, int intFallBackUnitID = 0)
        {
            return ExecuteSP("proc_GetDetailsByCFFSubKategori", "@CFFSubKategori", strCFFSubKategori, "@FallBackUnitID", intFallBackUnitID);
        }

 
        
        /// <summary>
        /// Get Display Column for advanced rules 
        /// Sorting based on SeqNo is done here
        /// </summary>
        /// <param name="intTableType">Table Type</param>
        /// <param name="intJenisKempenID">Passed in if it is Outbound</param>
        /// <returns></returns>
        public DisplaySettingViewModel GetDisplayColSystemView(int intTableType, int intJenisKempenID)
        {
            DisplaySettingViewModel obj = new DisplaySettingViewModel();
            DataSet ds;
            ds = ExecuteSP("proc_GetDisplayColSystemView",
                                                        "@TableType", intTableType,
                                                        "@JenisKempenID", intJenisKempenID);
            obj = RetrieveDisplaySetting(ds);
            return obj;
        }

        /// <summary>
        /// Get Display Column for saved view
        /// </summary>
        /// <param name="intTableType">Table type</param>
        /// <param name="intViewID">Saved view ID</param>
        /// <returns></returns>
        public DisplaySettingViewModel GetDisplayColSavedView(int intTableType, int intViewID)
        {
            DisplaySettingViewModel obj = new DisplaySettingViewModel();
            DataSet ds;
            ds = ExecuteSP("proc_GetDisplayColSavedView",
                                                        "@TableType", intTableType,
                                                        "@ViewID", intViewID);
            obj = RetrieveDisplaySetting(ds);
            return obj;
        }

        public List<DashboardDisplayColumn> GetDashboardDisplayCol(int intTableType, int intViewID)
        {
            List<DashboardDisplayColumn> obj = new List<DashboardDisplayColumn>();
            DataSet ds;
            ds = ExecuteSP("proc_GetDashboardDisplayCol",
                                                        "@TableType", intTableType,
                                                        "@ViewID", intViewID);
            obj = (DataTableToList<DashboardDisplayColumn>(ds.Tables[0])).OrderBy(x => x.Sequence).ToList();
            return obj;
        }


        public DisplaySettingViewModel RetrieveDisplaySetting(DataSet ds)
        {
            DisplaySettingViewModel obj = new DisplaySettingViewModel();
            if (ds != null && ds.Tables.Count > 1)
            {
                obj.DisplayColumns = (DataTableToList<DisplayColumnViewModel>(ds.Tables[0])).OrderBy(x => x.Sequence).ToList();
                obj.FieldsSorting = (DataTableToList<RulesSortingViewModel>(ds.Tables[1])).OrderBy(x => x.Sequence).ToList();
            }
            return obj;
        }

        public DashboardViewModel GetDashboardbyLoginUnit(int DashboardID, long lnUserProfileID)
        {
            DashboardViewModel obj = new DashboardViewModel();
            DataSet ds = ExecuteSP("proc_GetDashboardByLoginUnit",
                               "@ID", DashboardID,
                               "@UserProfileID", lnUserProfileID);

            if (ds != null && ds.Tables.Count > 1)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    obj.DashboardID = ds.Tables[0].Rows[0]["DashboardID"].ToIntSafe();
                    obj.DashboardName = ds.Tables[0].Rows[0]["DashboardName"].ToStringSafe();
                }
                obj.DashboardZones = (DataTableToList<DashboardZonViewModel>(ds.Tables[1])).OrderBy(x => x.Sequence).ToList();
            }

            return obj;
        }

        public List<SearchSavedViewViewModel> GetDashboardDynamicCol(int viewID, int tableType)
        {
            return ExecuteSPDynamic<SearchSavedViewViewModel>("proc_GetDashboardDynamicCol",
                                                    "@ViewID", viewID,
                                                    "@TableType", tableType).ToList();
        }

        public DataSet GetDashboardTableResults(string strSortExpr, int intPageIndex, int intPageSize, int viewID,
                                          int tableType, string strUserLogin)
        {
            DataSet ds = new DataSet();

            List<object> lstParam = new List<object>(new object[] {
                                        "@PageIndex", intPageIndex,
                                        "@PageSize", intPageSize,
                                        "@ViewID", viewID,
                                        "@TableType", tableType,
                                        "@loginID", strUserLogin
                                    });

            if (!string.IsNullOrEmpty(strSortExpr))
            {
                lstParam.AddRange(new object[] {
                "@SortExpression", strSortExpr
                });
            }

            return ExecuteSP("proc_GetDashboardTableResults", lstParam.ToArray());
        }


        public void UpdatePermissionUser(int? intTableType, List<PermissionUserViewModel> lstPermissionUser, int intViewID)
        {
            DataTable dTblPermissionUser = lstPermissionUser.ToDataTable<PermissionUserViewModel>();
            dTblPermissionUser.Columns.Remove("LoginID");
            dTblPermissionUser.Columns.Remove("DisplayName");

            ExecuteSP("proc_UpdateViewPermissionUser",
                        "@tableType", intTableType,
                        "@tblPermissionUser", dTblPermissionUser,
                        "@ViewID", intViewID);
        }

        public void UpdatePermissionRole(int? intTableType, List<PermissionRoleViewModel> lstPermissionRole, int intViewID)
        {
            DataTable dTblPermissionRole = lstPermissionRole.ToDataTable<PermissionRoleViewModel>();
            dTblPermissionRole.Columns.Remove("RoleName");
            ExecuteSP("proc_UpdateViewPermissionRole",
                        "@tableType", intTableType,
                        "@tblPermissionRole", dTblPermissionRole,
                        "@ViewID", intViewID);
        }

        public ChartList GetDashboardChartResult(int DashboardZonID, int viewID, int tableType,
                                                                         int xFieldMappingID, int yFieldMappingID, string strUserLogin)
        {
            ChartList obj = new ChartList();
            List<ChartResult> lstChartResults = new List<ChartResult>();
            ChartResult objResult = new ChartResult();
            List<DashboardChart> lstDashboardChart = new List<DashboardChart>();

            //lstDashboardChart = ExecuteSPDynamic<DashboardChart>("proc_GetDashboardChartResults",
            //                                        "@DashboardZonID", DashboardZonID,
            //                                        "@ViewID", viewID,
            //                                        "@TableType", tableType,
            //                                        "@xFieldMappingID", xFieldMappingID,
            //                                        "@yFieldMappingID", yFieldMappingID
            //                                        ).ToList();

            DataSet ds = ExecuteSP("proc_GetDashboardChartResults",
                                                    "@DashboardZonID", DashboardZonID,
                                                    "@ViewID", viewID,
                                                    "@TableType", tableType,
                                                    "@xFieldMappingID", xFieldMappingID,
                                                    "@yFieldMappingID", yFieldMappingID,
                                                    "@loginID", strUserLogin
                                                    );
            if (ds != null)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    //lstDashboardChart = DataTableToList<DashboardChart>(ds.Tables[0]).ToList();     
                    foreach(DataRow row in ds.Tables[0].Rows)
                    {
                        DashboardChart objChart = new DashboardChart();
                        objChart.y = row["y"];
                        objChart.Label = row["Label"].ToStringSafe();
                        lstDashboardChart.Add(objChart);
                    }           
                }
            }

            objResult.Result = lstDashboardChart;
            lstChartResults.Add(objResult);
            obj.ChartResults = lstChartResults;

            return obj;
        }

        public bool CheckDashboardPermission(int DashboardID, long lnUserProfileID)
        {
            int intCount = ExecuteUpdateSP("proc_CheckDashboardPermission",
                               "@ID", DashboardID,
                               "@UserProfileID", lnUserProfileID);



            return (intCount > 0 ? true : false);
        }

        public List<DashboardViewModel> GetDashboardList(long lnUserProfileID)
        {
            List<DashboardViewModel> lstDashboardMenu = new List<DashboardViewModel>();
            lstDashboardMenu = ExecuteSPDynamic<DashboardViewModel>("proc_GetDashboardList",
                               "@UserProfileID", lnUserProfileID).ToList();



            return lstDashboardMenu;
        }

        public AdvancedRulesMainViewModel DeleteViewConfig(int intViewID, int intTableType, string lastupdateBy, string lastupdateByName, DateTime now)
        {
            AdvancedRulesMainViewModel advanceRuleViewDetail = new AdvancedRulesMainViewModel();

            advanceRuleViewDetail = ExecuteSP<AdvancedRulesMainViewModel>("proc_DeleteViewConfig",
                                                                  "@tableType", intTableType,
                                                                  "@ViewID", intViewID,
                                                                  "@LastUpdatedBy", lastupdateBy,
                                                                  "@LastUpdateByName", lastupdateByName,
                                                                  "@LastUpdateDateTime", now).FirstOrDefault();
            return advanceRuleViewDetail;

            //ExecuteSP("proc_DeleteViewConfig",
            //          "@tableType", intTableType,
            //          "@ViewID", intViewID);
        }

        //Enhancement (Chew 2021-03-08)
        public DataSet GetCRMFormBranchDetails(string strFormBranch)
        {
            return ExecuteSP("proc_GetCFFFormBranchDetails", "@UnitID", strFormBranch);
        }
    }
}
