using FactorySystemCommon;
using FactorySystemModel.SqlSugarModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using FactorySystemModel.EnumModel;

namespace FactorySystemBll
{
    public class UserBll
    {
        /// <summary>
        /// 获取配置信息
        /// </summary>
        public object GetBasicList(int type)
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TBasicCode>().Where(s => s.FType == type && s.FState == 1).ToList();
        }

        /// <summary>
        /// 获取角色集合
        /// </summary>
        /// <returns></returns>
        public object GetRoleList()
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<TRole>().Where(s => s.FDeleted != (int)Constant.DeleteCode.已删除).ToList();
        }

        /// <summary>
        /// 获取权限配置集合
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public List<FPower> GetPower(string userid) 
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<FPower>().Where("FUserID="+ userid).ToList();
        }

        /// <summary>
        /// 获取菜单权限
        /// </summary>
        public object GetMenuList(int userId, string roleIds, bool returnAll = false)
        {
            int delete = (int)Constant.DeleteCode.已删除;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<string> roles = new List<string>();
            if (string.IsNullOrEmpty(roleIds))
            {
                TUser userInfo = db.Queryable<TUser>().Where(s => s.FID == userId && s.FDeleted != delete).First();
                roleIds = userInfo.FRoleID.ToString();
            }
            roles = roleIds.Split(',').ToList();
            List<TFunction> menuList = db.Queryable<TFunction>().Where(s => s.FDeleted != delete).OrderBy(s => s.FOrder).ToList();
            List<int> hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
                  .Where((a, b) => a.FDeleted != delete && b.FType == (int)Constant.RoleType.菜单权限 && roles.Contains(a.FID.ToString()))
                  .Select((a, b) => b.FFunctionID).GroupBy("b.FFunctionID").ToList();
            if (returnAll)
            {
                return menuList.Select(s => new
                {
                    s.FID,
                    s.FIcon,
                    s.FParentID,
                    s.FName,
                    s.FLevel,
                    s.FLocation,
                    s.FOrder,
                    s.FRemark,
                    FIsChose = hasIds.IndexOf(s.FID) != -1
                }).ToList();
            }
            else
            {
                return menuList.Where(s => hasIds.IndexOf(s.FID) != -1).Select(s => new
                {
                    s.FID,
                    s.FIcon,
                    s.FParentID,
                    s.FName,
                    s.FLevel,
                    s.FLocation,
                    s.FOrder,
                    s.FRemark,
                }).ToList();
            }
        }

        /// <summary>
        /// 获取菜单权限
        /// </summary>
        public object GetMenuList(int userId, bool returnAll = false)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            int delete = (int)Constant.DeleteCode.已删除;

            List<FPower> powers = db.Queryable<FPower>().Where(s => userId.ToString().Equals(s.FUserID)).ToList();
            List<string> roles = new List<string>();

            if (powers != null && powers.Count > 0)
            {
                powers.ForEach(power =>
                {
                    roles.Add(power.FRole);
                });
            }

            List<TFunction> menuList = db.Queryable<TFunction>().Where(s => s.FDeleted != delete).OrderBy(s => s.FOrder).ToList();
            List<int> hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
                  .Where((a, b) => a.FDeleted != delete && b.FType == (int)Constant.RoleType.菜单权限 && roles.Contains(a.FID.ToString()))
                  .Select((a, b) => b.FFunctionID).GroupBy("b.FFunctionID").ToList();
            if (returnAll)
            {
                return menuList.Select(s => new
                {
                    s.FID,
                    s.FIcon,
                    s.FParentID,
                    s.FName,
                    s.FLevel,
                    s.FLocation,
                    s.FOrder,
                    s.FRemark,
                    FIsChose = hasIds.IndexOf(s.FID) != -1
                }).ToList();
            }
            else
            {
                return menuList.Where(s => hasIds.IndexOf(s.FID) != -1).Select(s => new
                {
                    s.FID,
                    s.FIcon,
                    s.FParentID,
                    s.FName,
                    s.FLevel,
                    s.FLocation,
                    s.FOrder,
                    s.FRemark,
                }).ToList();
            }
        }

        /// <summary>
        /// 获取其他权限
        /// </summary>
        public object GetBasicRoleList(object roleIds, int roleType, string viewType, int userId, bool returnAll,object teamId,object type)
        {
            int roleType2 = -1;
            if (roleType == 36) roleType2 = (int)Constant.RoleType.事项权限;
            else if (roleType == 39) roleType2 = (int)Constant.RoleType.视图权限;
            else if (roleType == 40) roleType2 = (int)Constant.RoleType.物料视图编辑;
            else if (roleType == 44) roleType2 = (int)Constant.RoleType.物料基础编辑;
            // 20230328 新增
            // 前端新增传84，用于合并40和44
            else if (roleType == 84) roleType2 = (int)Constant.RoleType.视图编辑;
            if (roleType2 <= 0) return null;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<string> roles = new List<string>();
            if (null == roleIds || string.IsNullOrEmpty(roleIds.ToString()))
            {
                if (teamId!=null) 
                {
                    //TUser userInfo = db.Queryable<TUser>().Where(s => s.FID == userId && s.FDeleted != (int)Constant.DeleteCode.已删除).First();
                    //roleIds = userInfo.FRoleID;
                    int factoryID = 0;

                    switch (int.Parse(type.ToString())) 
                    {
                        case 0:
                            TFS_FTeamwork fTeamwork = BaseBll.GetTempModel<TFS_FTeamwork>("FID=" + teamId.ToString());
                            factoryID = fTeamwork.FCreateFactoryID;
                            break;
                        case 1:
                            TFS_FMaterialTeamwork FMaterialTeamwork = BaseBll.GetTempModel<TFS_FMaterialTeamwork>("FID=" + teamId.ToString());
                            factoryID = FMaterialTeamwork.FCreateFactoryID;
                            break; 
                        case 2:
                            TFS_HalfMaterialFTeamwork halfMaterialFTeamwork = BaseBll.GetTempModel<TFS_HalfMaterialFTeamwork>("FID=" + teamId.ToString());
                            factoryID = halfMaterialFTeamwork.FCreateFactoryID;
                            break;
                    }
                   

                    List<FPower> fPower = db.Queryable<FPower>().Where(s => s.FUserID == userId.ToString() && s.FFactoryID == factoryID.ToString()).ToList();
                    roleIds = string.Join(",", fPower.Select(m => m.FRole).Distinct().ToList());
                }
                else 
                {
                    List<FPower> fPower = db.Queryable<FPower>().Where(s => s.FUserID == userId.ToString()).ToList();
                    roleIds = string.Join(",", fPower.Select(m => m.FRole).Distinct().ToList());
                }
                
            }
            roles = roleIds.ToString().Trim(',').Split(',').ToList();

            /**
             * 20230328
             * 合并物料视图和基础视图
             * 前端只保留
             * 当roleType == 84时，分别取TBasicCode中的FType = 40和44两个类型的数据（即物料视图和基础视图的所有字段数据）
             * 当roleType == 84时，分别取TRole_Right中的FType = 4和5两个类型的数据（即物料视图和基础视图的所有权限数据）
             * **/
            List<TBasicCode> resultList = null;
            List<int> hasIds = null;
            dynamic result = null;

            if (roleType == 84)
            {

                resultList = db.Queryable<TBasicCode>().Where(s => (s.FType == 44 && s.FState == 1)).OrderBy(s => s.FOrder).ToList();
                hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
                    .Where((a, b) => a.FDeleted != (int)Constant.DeleteCode.已删除 && b.FType == 5 && roles.Contains(a.FID.ToString()))
                    .Select((a, b) => b.FFunctionID).ToList();

                if (!string.IsNullOrEmpty(viewType)) resultList = resultList.Where(s => s.F1.Equals(viewType)).ToList();

                if (returnAll)
                {
                    result = resultList.Select(s => new
                    {
                        s.FID,
                        s.FType,
                        s.FCode,
                        s.FName,
                        s.FRemark,
                        FIsChose = hasIds.IndexOf(int.Parse(s.FCode)) != -1,
                        s.F1,
                        s.F2
                    }).OrderBy(s => int.Parse(s.FCode)).ToList();
                }
                else
                {
                    result = resultList.Where(s => hasIds.IndexOf(int.Parse(s.FCode)) != -1).Select(s => new
                    {
                        s.FID,
                        s.FType,
                        s.FCode,
                        s.FName,
                        s.FRemark,
                        s.F1,
                        s.F2
                    }).OrderBy(s => int.Parse(s.FCode)).ToList();
                }


                resultList = db.Queryable<TBasicCode>().Where(s => (s.FType == 40 && s.FState == 1)).OrderBy(s => s.FOrder).ToList();
                hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
                    .Where((a, b) => a.FDeleted != (int)Constant.DeleteCode.已删除 && b.FType == 4 && roles.Contains(a.FID.ToString()))
                    .Select((a, b) => b.FFunctionID).ToList();

                if (!string.IsNullOrEmpty(viewType)) resultList = resultList.Where(s => s.F1.Equals(viewType)).ToList();

                if (returnAll)
                {
                    result.AddRange(
                        resultList.Select(s => new
                        {
                            s.FID,
                            s.FType,
                            s.FCode,
                            s.FName,
                            s.FRemark,
                            FIsChose = hasIds.IndexOf(int.Parse(s.FCode)) != -1,
                            s.F1,
                            s.F2
                        }).OrderBy(s => int.Parse(s.FCode)).ToList()
                    );
                }
                else
                {
                    result.AddRange(
                        resultList.Where(s => hasIds.IndexOf(int.Parse(s.FCode)) != -1).Select(s => new
                        {
                            s.FID,
                            s.FType,
                            s.FCode,
                            s.FName,
                            s.FRemark,
                            s.F1,
                            s.F2
                        }).OrderBy(s => int.Parse(s.FCode)).ToList()
                    );
                }
            }
            else
            {
                resultList = db.Queryable<TBasicCode>().Where(s => s.FType == roleType && s.FState == 1).OrderBy(s => s.FOrder).ToList();
                hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
                    .Where((a, b) => a.FDeleted != (int)Constant.DeleteCode.已删除 && b.FType == roleType2 && roles.Contains(a.FID.ToString()))
                    .Select((a, b) => b.FFunctionID).ToList();

                if (!string.IsNullOrEmpty(viewType)) resultList = resultList.Where(s => s.F1.Equals(viewType)).ToList();

                if (returnAll)
                {
                    result = resultList.Select(s => new
                    {
                        s.FID,
                        s.FCode,
                        s.FName,
                        s.FRemark,
                        FIsChose = hasIds.IndexOf(int.Parse(s.FCode)) != -1,
                        s.F1,
                        s.F2
                    }).OrderBy(s => int.Parse(s.FCode)).ToList();
                }
                else
                {
                    result = resultList.Where(s => hasIds.IndexOf(int.Parse(s.FCode)) != -1).Select(s => new
                    {
                        s.FID,
                        s.FCode,
                        s.FName,
                        s.FRemark,
                        s.F1,
                        s.F2
                    }).OrderBy(s => int.Parse(s.FCode)).ToList();
                }
            }

            return result;

            // 20230328 需求修改注释
            // List<TBasicCode> resultList = db.Queryable<TBasicCode>().Where(s => s.FType == roleType && s.FState == 1).OrderBy(s => s.FOrder).ToList();
            // List<int> hasIds = db.Queryable<TRole, TRole_Right>((a, b) => new JoinQueryInfos(JoinType.Left, a.FID == b.FRoleID))
            //    .Where((a, b) => a.FDeleted != (int)Constant.DeleteCode.已删除 && b.FType == roleType2 && roles.Contains(a.FID.ToString()))
            //    .Select((a, b) => b.FFunctionID).ToList();

            //视图类型
            //if (!string.IsNullOrEmpty(viewType)) resultList = resultList.Where(s => s.F1.Equals(viewType)).ToList();
            //if (returnAll)
            //{
            //    var a = resultList.Select(s => new
            //    {
            //        s.FID,
            //        s.FCode,
            //        s.FName,
            //        s.FRemark,
            //        FIsChose = hasIds.IndexOf(int.Parse(s.FCode)) != -1,
            //        s.F1,
            //        s.F2
            //    }).OrderBy(s => int.Parse(s.FCode)).ToList();
            //    return a;
            //}
            //else
            //{
            //    return resultList.Where(s => hasIds.IndexOf(int.Parse(s.FCode)) != -1).Select(s => new
            //    {
            //        s.FID,
            //        s.FCode,
            //        s.FName,
            //        s.FRemark,
            //        s.F1,
            //        s.F2
            //    }).OrderBy(s => int.Parse(s.FCode)).ToList();
            //}
        }
        /// <summary>
        /// 保存菜单集合
        /// </summary>
        public int SaveRolePower(string userId, int roleId, List<string> menuIds, List<string> viewIds, List<string> termIds, List<string> editIds, List<string> editIds2)
        {
            int result = 1;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            db.BeginTran();
            try
            {
                if (menuIds != null)
                {
                    result += db.Deleteable<TRole_Right>().Where(s => s.FRoleID == roleId && s.FType == (int)Constant.RoleType.菜单权限
                    && !menuIds.Contains(s.FFunctionID.ToString())).ExecuteCommand();
                }
                if (viewIds != null)
                {
                    result += db.Deleteable<TRole_Right>().Where(s => s.FRoleID == roleId && s.FType == (int)Constant.RoleType.视图权限
                    && !viewIds.Contains(s.FFunctionID.ToString())).ExecuteCommand();
                }
                if (termIds != null)
                {
                    result += db.Deleteable<TRole_Right>().Where(s => s.FRoleID == roleId && s.FType == (int)Constant.RoleType.事项权限
                    && !termIds.Contains(s.FFunctionID.ToString())).ExecuteCommand();
                }
                if (editIds != null)
                {
                    result += db.Deleteable<TRole_Right>().Where(s => s.FRoleID == roleId && s.FType == (int)Constant.RoleType.物料视图编辑
                    && !editIds.Contains(s.FFunctionID.ToString())).ExecuteCommand();
                }
                if (editIds2 != null)
                {
                    result += db.Deleteable<TRole_Right>().Where(s => s.FRoleID == roleId && s.FType == (int)Constant.RoleType.物料基础编辑
                    && !editIds.Contains(s.FFunctionID.ToString())).ExecuteCommand();
                }
                List<TRole_Right> inList = new List<TRole_Right>();
                List<TRole_Right> hasRoles = db.Queryable<TRole_Right>().Where(s => s.FRoleID == roleId).ToList();
                if (menuIds != null)
                {
                    inList.AddRange(CheckPowerIds(hasRoles, menuIds, (int)Constant.RoleType.菜单权限, userId, roleId));
                }
                if (viewIds != null)
                {
                    inList.AddRange(CheckPowerIds(hasRoles, viewIds, (int)Constant.RoleType.视图权限, userId, roleId));
                }
                if (termIds != null)
                {
                    inList.AddRange(CheckPowerIds(hasRoles, termIds, (int)Constant.RoleType.事项权限, userId, roleId));
                }
                if (editIds != null)
                {
                    inList.AddRange(CheckPowerIds(hasRoles, editIds, (int)Constant.RoleType.物料视图编辑, userId, roleId));
                }
                if (editIds2 != null)
                {
                    inList.AddRange(CheckPowerIds(hasRoles, editIds2, (int)Constant.RoleType.物料基础编辑, userId, roleId));
                }
                if (inList.Count() > 0) result += db.Insertable(inList).ExecuteCommand();
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
            }
            return result;
        }


        public int CreateFPower(List<FPower> list) 
        {
            int result = 0;
            if (list.Count() > 0) 
            {
                SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

                FPower power = list.LastOrDefault();
                db.Deleteable<FPower>().Where(s => s.FUserID == power.FUserID).ExecuteCommand();
                result = db.Insertable(list).ExecuteCommand();

            }

            return result;
        }
        public List<FPower> GetFPowerList()
        {
            return AppSettingsHelper.GetSqlSugar().Queryable<FPower>().ToList();
        }


        /// <summary>
        /// 获取首页信息
        /// </summary>
        public object GetHomeTopCount(int userId)
        {
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<int> topCount = new List<int>();
            topCount.Add(db.Queryable<TFS_Task>().Where(s => s.FState < 2).Where(string.Format("','+FUserID+',' like '%,{0},%'", userId)).Count());
            topCount.Add(db.Queryable<TFS_Task>().Where(string.Format("','+FUserID+',' like '%,{0},%'", userId))
                .Where(string.Format("convert(varchar(10),FAddDate,23)='{0}'", DateTime.Now.ToString("yyyy-MM-dd"))).Count());
            topCount.Add(db.Queryable<TFS_FTeamwork>().Count());
            topCount.Add(db.Queryable<TFS_FTeamwork>().Where(string.Format(@"FID in(select distinct FTeamID from TFS_FTeamProcess 
            where ','+FChargeID+',' like '%,{0},%' union select distinct FTeamID from TFS_Task where ','+FUserID+',' like '%,{0},%')",
            userId)).Count());
            return topCount;
        }

        #region 内部方法
        private List<TRole_Right> CheckPowerIds(List<TRole_Right> hasRoles, List<string> inIds, int roleType, string userId, int roleId)
        {
            List<int> ids = hasRoles.Where(ss => ss.FType == roleType).Select(sss => sss.FFunctionID).ToList();
            if (ids.Count() > 0) inIds = inIds.Where(s => !ids.Contains(int.Parse(s))).ToList();
            if (inIds.Count() > 0 && !string.IsNullOrWhiteSpace(inIds[0]))
            {
                return inIds.Select(s => new TRole_Right()
                {
                    FFunctionID = int.Parse(s),
                    FOperate = userId,
                    FType = roleType,
                    FRoleID = roleId,
                }).ToList();
            }
            return new List<TRole_Right>();
        }
        #endregion

        /// <summary>
        /// 获取冻结列
        /// </summary>
        public object GetFreezingColumns(int userId)
        {
            TFS_FreezingColumns tc = null;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
            List<TFS_FreezingColumns> tcl = db.Queryable<TFS_FreezingColumns>().Where(fc => fc.FDeleted != 1 && fc.FUserID == userId).ToList();

            if (tcl != null && tcl.Count > 0)
            {
                tc = tcl[0];
            }

            return tc;
        }

        public int CreateFreezingColumns(int userId, List<TFS_FreezingColumns> list)
        {
            int result = 0;

            if (list.Count() > 0)
            {
                SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
                db.Deleteable<TFS_FreezingColumns>().Where(s => s.FUserID == userId).ExecuteCommand();
                result = db.Insertable(list).ExecuteCommand();
            }

            return result;
        }

        public int UpdateFreezingColumns(TFS_FreezingColumns fc)
        {
            int result = 0;
            SqlSugarClient db = AppSettingsHelper.GetSqlSugar();

            result = db.Updateable(fc).IgnoreColumns(true).ExecuteCommand();

            return result;
        }
    }
}
