using Learun.DataBase.Repository;
using Learun.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace Learun.Application.Organization
{
    /// <summary>
    /// 版 本 Learun-ADMS-Ultimate V7.0.0 数字化智慧校园 
    /// Copyright (c) 2013-2018 北京泉江科技有限公司 
    /// 创建人:陈彬彬
    /// 日 期:2017.03.04
    /// 描 述:用户模块数据操作服务类
    /// </summary>
    public class UserService : RepositoryFactory
    {
        #region  属性 构造函数
        private string fieldSql;
        public UserService()
        {
            fieldSql = "t.*";
        }
        #endregion

        #region  获取数据
        /// <summary>
        /// 获取实体,通过用户账号
        /// </summary>
        /// <param name="account">用户账号</param>
        /// <returns></returns>
        public UserEntity GetEntityByAccount(string account)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_User t ");
                strSql.Append(" WHERE t.F_Account = @account AND t.F_DeleteMark = 0  ");
                return this.BaseRepository().FindEntity<UserEntity>(strSql.ToString(), new { account = account });
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体,通过用户账号
        /// </summary>
        /// <param name="account">用户账号</param>
        /// <returns></returns>
        public UserEntity GetEntityByName(string name)
        {
            try
            {
                return this.BaseRepository()
                    .FindEntity<UserEntity>(a => a.F_RealName.Equals(name) && a.F_DeleteMark == 0);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 用户列表(根据公司主键)
        /// </summary>
        /// <param name="companyId">公司主键</param>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetList(string companyId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql.Replace("t.F_Password,", "").Replace("t.F_Secretkey,", ""));
                strSql.Append(" FROM LR_Base_User t WHERE t.F_DeleteMark = 0 AND t.F_CompanyId = @companyId ORDER BY t.F_DepartmentId,t.F_RealName ");
                return this.BaseRepository().FindList<UserEntity>(strSql.ToString(), new { companyId = companyId });
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        internal bool GetStuAny()
        {
            try
            {
                return this.BaseRepository().FindList<UserEntity>(a => a.F_Description == "学生").ToList().Count() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        internal bool GetAny()
        {
            try
            {
                return this.BaseRepository().FindList<UserEntity>(a => a.F_Description == "教师").ToList().Count() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 用户列表(根据公司主键)(分页)
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="departmentId"></param>
        /// <param name="pagination"></param>
        /// <param name="keyword"></param>
        /// <param name="tp">类型 0学生 1 教师</param>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetPageList(string companyId, string departmentId, Pagination pagination, string keyword, string tp)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql.Replace("t.F_Password,", "").Replace("t.F_Secretkey,", ""));
                strSql.Append(",F_UserId as F_UserId_Log FROM LR_Base_User t WHERE t.F_DeleteMark = 0 AND t.F_CompanyId = @companyId  ");

                if (!string.IsNullOrEmpty(departmentId))
                {
                    strSql.Append(" AND t.F_DepartmentId = @departmentId ");
                }
                if (!string.IsNullOrEmpty(tp))
                {
                    switch (tp)
                    {
                        case "0":
                            strSql.Append(" AND t.F_Description='教师' ");
                            break;
                        case "1":
                            strSql.Append(" AND t.F_Description='学生' ");
                            break;
                    }
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    keyword = "%" + keyword + "%";
                    strSql.Append(" AND( t.F_Account like @keyword or t.F_RealName like @keyword  or t.F_Mobile like @keyword  ) ");
                }

                return this.BaseRepository().FindList<UserEntity>(strSql.ToString(), new { companyId, departmentId, keyword }, pagination);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 用户列表,全部
        /// </summary>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetAllList()
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql.Replace("t.F_Password,", "").Replace("t.F_Secretkey,", ""));
                strSql.Append(" FROM LR_Base_User t WHERE t.F_DeleteMark = 0  ORDER BY t.F_CompanyId,t.F_DepartmentId,t.F_RealName ");
                return this.BaseRepository().FindList<UserEntity>(strSql.ToString());
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 用户列表(导出Excel)
        /// </summary>
        /// <returns></returns>
        public DataTable GetExportList()
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT u.F_Account
                                  ,u.F_RealName
                                  ,CASE WHEN u.F_Gender=1 THEN '男' ELSE '女' END AS F_Gender
                                  ,CASE WHEN u.F_EnabledMark=1 THEN '正常' ELSE '禁用' END AS F_EnabledMark
                                  ,u.F_Birthday
                                  ,u.F_Mobile
                                  ,u.F_Telephone
                                  ,u.F_WeChat
                                  ,o.F_FullName AS F_Company
                                  ,d.F_FullName AS F_Department
                                  ,u.F_Description
                                  ,u.F_CreateDate
                                  ,u.F_CreateUserName
                              FROM LR_Base_User u
                              INNER JOIN LR_Base_Department d ON u.F_DepartmentId=d.F_DepartmentId
                              INNER JOIN LR_Base_Company o ON u.F_CompanyId=o.F_CompanyId 
                              WHERE u.F_DeleteMark = 0 and u.F_Description = '教师'");
                return this.BaseRepository().FindTable(strSql.ToString());
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 用户列表(导出Excel)【学生】
        /// </summary>
        /// <returns></returns>
        public DataTable GetExportListOfStudent()
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT u.F_Account
                                  ,u.F_RealName
                                  ,CASE WHEN u.F_Gender=1 THEN '男' ELSE '女' END AS F_Gender
                                  ,u.F_Birthday
                                  ,u.F_Mobile
                                  ,u.F_Telephone
                                  ,u.F_WeChat
                                  ,o.F_FullName AS F_Company
                                  ,u.F_DepartmentId AS F_Department
                                  ,u.F_Description
                                  ,u.F_CreateDate
                                  ,u.F_CreateUserName
                              FROM LR_Base_User u
                              INNER JOIN LR_Base_Company o ON u.F_CompanyId=o.F_CompanyId 
                              WHERE u.F_DeleteMark = 0 and u.F_Description = '学生'");
                return this.BaseRepository().FindTable(strSql.ToString());
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 用户实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public UserEntity GetEntity(string keyValue)
        {
            try
            {
                return this.BaseRepository().FindEntity<UserEntity>(t => t.F_UserId == keyValue && t.F_DeleteMark == 0);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }



        #endregion

        #region  验证数据
        /// <summary>
        /// 账户不能重复
        /// </summary>
        /// <param name="account">账户值</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public bool ExistAccount(string account, string keyValue)
        {
            try
            {
                var expression = LinqExtensions.True<UserEntity>();
                expression = expression.And(t => t.F_Account == account);
                if (!string.IsNullOrEmpty(keyValue))
                {
                    expression = expression.And(t => t.F_UserId != keyValue);
                }
                return this.BaseRepository().IQueryable(expression).Count() == 0 ? true : false;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region  提交数据
        /// <summary>
        /// 虚拟删除
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDelete(string keyValue)
        {
            try
            {
                UserEntity entity = new UserEntity()
                {
                    F_UserId = keyValue,
                    F_DeleteMark = 1
                };
                this.BaseRepository().Update(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 虚拟删除(批量)
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDeleteBatch(string keyValue)
        {
            var db = this.BaseRepository().BeginTrans();
            try
            {
                foreach (var item in keyValue.Split(','))
                {
                    UserEntity entity = new UserEntity()
                    {
                        F_UserId = item,
                        F_DeleteMark = 1
                    };
                    db.Update(entity);
                    db.ExecuteBySql("delete from LR_Base_UserRelation where F_UserId='" + keyValue + "'");
                }
                db.Commit();
            }
            catch (Exception ex)
            {
                db.Rollback();
            }
        }

        internal List<UserEntity> GetStudents()
        {
            try
            {
                return this.BaseRepository().FindList<UserEntity>(a => a.F_Description == "学生").ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存用户表单(新增、修改)
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="userEntity">用户实体</param>
        /// <returns></returns>
        public void SaveEntity(string keyValue, UserEntity userEntity)
        {
            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    userEntity.Create();
                    userEntity.F_Secretkey = Md5Helper.Encrypt(CommonHelper.CreateNo(), 16).ToLower();
                    userEntity.F_Password = Md5Helper.Encrypt(DESEncrypt.Encrypt(userEntity.F_Password, userEntity.F_Secretkey).ToLower(), 32).ToLower();
                    this.BaseRepository().Insert(userEntity);
                }
                else
                {
                    userEntity.Modify(keyValue);
                    userEntity.F_Secretkey = null;
                    userEntity.F_Password = null;
                    this.BaseRepository().Update(userEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 修改用户登录密码
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="password">新密码(MD5 小写)</param>
        public void RevisePassword(string keyValue, string password)
        {
            try
            {
                UserEntity userEntity = new UserEntity();
                userEntity.Modify(keyValue);
                userEntity.F_Secretkey = Md5Helper.Encrypt(CommonHelper.CreateNo(), 16).ToLower();
                userEntity.F_Password = Md5Helper.Encrypt(DESEncrypt.Encrypt(password, userEntity.F_Secretkey).ToLower(), 32).ToLower();
                this.BaseRepository().Update(userEntity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 修改用户登录密码(批量)
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="password">新密码(MD5 小写)</param>
        public void RevisePasswordBatch(string keyValue, string password)
        {
            var db = this.BaseRepository().BeginTrans();
            try
            {
                foreach (var item in keyValue.Split(','))
                {
                    UserEntity userEntity = new UserEntity();
                    userEntity.Modify(item);
                    userEntity.F_Secretkey = Md5Helper.Encrypt(CommonHelper.CreateNo(), 16).ToLower();
                    userEntity.F_Password = Md5Helper.Encrypt(DESEncrypt.Encrypt(password, userEntity.F_Secretkey).ToLower(), 32).ToLower();
                    db.Update(userEntity);
                }
                db.Commit();
            }
            catch (Exception ex)
            {
                db.Rollback();
            }
        }
        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="state">状态:1-启动;0-禁用</param>
        public void UpdateState(string keyValue, int state)
        {
            try
            {
                UserEntity userEntity = new UserEntity();
                userEntity.Modify(keyValue);
                userEntity.F_EnabledMark = state;
                this.BaseRepository().Update(userEntity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userEntity">实体对象</param>
        public void UpdateEntity(UserEntity userEntity)
        {
            try
            {
                this.BaseRepository().Update(userEntity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        public List<UserEntity> GetUserByDepartmentId(string departmentId)
        {
            try
            {
                return this.BaseRepository().FindList<UserEntity>(a => a.F_DepartmentId == departmentId).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        public List<UserEntity> GetListByDepartmentIds(string departmentId)
        {
            try
            {
                var ids = departmentId.Split(',');
                return this.BaseRepository().FindList<UserEntity>(a => ids.Contains(a.F_DepartmentId)).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }



        /// <summary>
        /// 保存用户的设备号
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="deviceId">设备号</param>
        public void UpdateDeviceId(string keyValue, string deviceId)
        {
            try
            {
                var userEntity = this.BaseRepository().FindEntity<UserEntity>(keyValue);
                if (userEntity != null)
                {
                    userEntity.F_DeviceId = deviceId;
                    userEntity.Modify(keyValue);
                    this.BaseRepository().Update(userEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion


        public UserEntity GetEntityByWeixinOpenId(string openid)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_User t ");
                strSql.Append(" WHERE t.OpenIdForWeixin = @openid AND t.F_DeleteMark = 0  ");
                return this.BaseRepository().FindEntity<UserEntity>(strSql.ToString(), new { openid = openid });
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public UserEntity GetEntityByWeixinOpenIdPC(string openid)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_User t ");
                strSql.Append(" WHERE t.OpenIdForWeixinPC = @openid AND t.F_DeleteMark = 0  ");
                return this.BaseRepository().FindEntity<UserEntity>(strSql.ToString(), new { openid = openid });
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public void UpdateWeixinOpenId(string keyValue, string openid)
        {
            try
            {
                var userEntity = this.BaseRepository().FindEntity<UserEntity>(keyValue);
                if (userEntity != null)
                {
                    userEntity.OpenIdForWeixin = openid;
                    userEntity.Modify(keyValue);
                    this.BaseRepository().Update(userEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        public void UpdateWeixinOpenIdPC(string keyValue, string openid)
        {
            try
            {
                var userEntity = this.BaseRepository().FindEntity<UserEntity>(keyValue);
                if (userEntity != null)
                {
                    userEntity.OpenIdForWeixinPC = openid;
                    userEntity.Modify(keyValue);
                    this.BaseRepository().Update(userEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取超级管理员用户列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetAdminList()
        {
            try
            {
                return this.BaseRepository().FindList<UserEntity>(t => t.F_SecurityLevel == 1);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 解绑微信
        /// </summary>
        public void DoUnbundWeiXin(string keyValue)
        {
            try
            {
                this.BaseRepository().ExecuteBySql("update LR_Base_User set OpenIdForWeixin=null where F_UserId='" + keyValue + "' ");
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public void UpdateIp(string ip, string id)
        {
            try
            {
                this.BaseRepository().ExecuteBySql("update LR_Base_User set LastIp='" + ip + "' where F_UserId='" + id + "' ");
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取用户头像,取empinfo照片
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetEmpPhotoPath(string userid)
        {
            string path = "";
            try
            {
                var userentity = BaseRepository().FindEntity<UserEntity>("select a.*,b.Photo from LR_Base_User a " +
                                                                       "left join " + BaseRepository("CollegeMIS").getDbConnection().Database +
                                                                       ".dbo.empinfo b on a.F_Account=b.empno where a.F_UserId='" + userid + "'", null);
                if (userentity != null && !string.IsNullOrEmpty(userentity.Photo))
                {
                    //获取图片
                    var LR_Base_AnnexesFile = BaseRepository().FindEntity<dynamic>("select * from LR_Base_AnnexesFile where F_FolderId='" + userentity.Photo + "'", null);
                    if (LR_Base_AnnexesFile != null)
                    {
                        path = LR_Base_AnnexesFile.F_FilePath;
                    }
                }
                return path;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
    }

}