using Mall.Common.Models;
using Mall.Common.Enum;
using Mall.IM.Service.Account;
using Mall.IM.Service.Message;
using Mall.IM.Service.Message.ResultModel;
using Mall.IM.Service.User;
using Mall.IM.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mall.IM.Service
{
    public class IMService
    {
        private static AccountService accountService = new AccountService();
        private static UserService userService = new UserService();
        private static MessageService messageService = new MessageService();
        private static PushService pushService = new PushService();

        #region 用户账号管理

        /// <summary>
        /// 根据IM 账号获取账号信息
        /// </summary>
        /// <param name="accID">网易云通信ID</param>
        /// <returns></returns>
        public static UserInfoModel GetUserInfo(String accID)
        {
            try
            {
                var result = userService.GetUserInfo(accID);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("GetUserInfo云信Code: {0}", result.code)));
                }
                else
                {
                    return result.uinfos[0];
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "GetUserInfo异常信息");
            }
            return null;
        }

        /// <summary>
        /// 使用基本信息创建账号
        /// </summary>
        /// <param name="accID">网易云通信ID</param>
        /// <param name="name">用户名</param>
        /// <param name="icon">头像</param>
        /// <returns>用户信息对象，成功，里面会返回包括账号，密码，昵称，失败为null</returns>
        public static AccountModel CreateAccount(String accID, String name, String icon)
        {
            try
            {
                var result = accountService.CreateAccount(accID, name, icon);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("CreateAccount云信Code: {0}", result.code)));
                }
                else
                {
                    return result.info;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "CreateAccount异常信息");
            }
            return null;
        }

        /// <summary>
        /// 更新账号密码
        /// </summary>
        /// <param name="accID">网易云通信ID</param>
        /// <param name="password">新密码</param>
        /// <returns></returns>
        public static bool UpdateAccountPassword(String accID, String password)
        {
            try
            {
                var result = accountService.UpdateAccountPassword(accID, password);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("UpdateAccountPassword:accid {0},云信Code: {1}", accID, result.code)));
                }
                else
                {
                    return true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "UpdateAccountPassword异常信息");
            }
            return false;
        }

        /// <summary>
        /// 重设密码
        /// </summary>
        /// <param name="accID">网易云通信ID</param>
        /// <returns></returns>
        public static bool ResetAccountPassword(String accID)
        {
            try
            {
                var result = accountService.ResetAccountPassword(accID);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("ResetAccountPassword:accid {0},云信Code: {1}", accID, result.code)));
                }
                else
                {
                    return true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "ResetAccountPassword异常信息");
            }
            return false;
        }

        /// <summary>
        ///更新并获取账号新密码（密码随机生成）
        /// </summary>
        /// <param name="accID">网易云通信ID</param>
        /// <returns>用户信息对象，成功，里面会返回包括账号，密码失败为null</returns>
        public static AccountModel RefreshToke(String accID)
        {
            try
            {
                var result = accountService.RefreshToken(accID);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("RefreshToke云信Code: {0}", result.code)));
                }
                else
                {
                    return result.info;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "RefreshToke异常信息");
            }
            return null;
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user">用户信息对象</param>
        /// <returns>返回操作的结果</returns>
        public static Boolean UpdateUserInfo(String accID, String name, String icon)
        {
            var flag = false;
            try
            {
                var result = userService.UpdateUserInfo(accID, icon, name);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("UpdateUserInfo云信Code: {0}", result.code)));
                    flag= false;
                }
                else
                {
                    flag= true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "UpdateUserInfo异常信息");
            }
            return flag;
        }

        /// <summary>
        /// 获取默认密码
        /// </summary>
        /// <returns></returns>
        public static String DefaultPassword()
        {
            return AccountService.PASSWORD;
        }

        #endregion

        #region 消息管理
        /// <summary>
        /// 发送系统通知消息
        /// </summary>
        /// <param name="to">接收账号（OPID）</param>
        /// <returns></returns>
        public static Boolean SendNoticeMessage(String to)
        {
            var flag = false;
            try
            {
                var result = messageService.SendSysMessage(SysMessageType.NOTICE, to);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("SendNoticeMessage云信Code: {0}", result.code)));
                }
                else
                {
                    flag= true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "SendNoticeMessage异常信息");
            }
            return flag;
        }

        /// <summary>
        /// 发送系统通知消息，群发
        /// </summary>
        /// <param name="to">接收账号集合（OPID）</param>
        /// <returns></returns>
        public static Boolean SendNoticeMessage(List<String> to)
        {
            var flag = false;
            try
            {
                var result = messageService.SendSysMessage(SysMessageType.NOTICE, to);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("SendNoticeMessage云信Code: {0}", result.code)));
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "SendNoticeMessage异常信息");
            }
            return flag;
        }

        /// <summary>
        /// 发送系统通知消息，群发，自定义消息内容
        /// </summary>
        /// <param name="to">接收账号集合（OPID）</param>
        /// <param name="content">消息内容</param>
        /// <returns></returns>
        public static Boolean SendNoticeMessage(List<String> to, string content)
        {
            var flag = false;
            try
            {
                var result = messageService.SendNoticeMessage(content, to);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("SendNoticeMessage云信Code: {0}", result.code)));
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "SendNoticeMessage异常信息");
            }
            return flag;
        }

        /// <summary>
        /// 发送聊天消息
        /// </summary>
        /// <param name="from">发送账号账号（OPID）</param>
        /// <param name="to">接收账号（OPID）</param>
        /// <param name="content">消息内容</param>
        /// <returns></returns>
        public static Boolean SendIMMessage(String from, String to, String content)
        {
            var flag = false;
            try
            {
                var result = messageService.SendMessage(from, to, content);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("SendIMMessage云信Code: {0}", result.code)));
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "SendIMMessage异常信息");
            }
            return flag;
        }
        #endregion

        #region 推送管理
        /// <summary>
        /// 发送系统推送(OA)
        /// </summary>
        /// <param name="to">接收账号集合（OPID）</param>
        /// <param name="empId">发送人id</param>
        /// <param name="content">消息内容</param>
        /// <param name="title">标题</param>
        /// <param name="pushType">推送类型</param>
        /// <param name="pushLogType">推送日志记录类型</param>
        /// <param name="extras">额外信息</param>
        /// <param name="IsRecordLog">是否记录日志</param>
        /// <returns></returns>
        public static Boolean PushMessage(List<EmAccoutIdModel> to, int? empId, string content, string title, SysTemPushTypeEnum pushType, SystemPushLogTypeEnum pushLogType, Dictionary<string, object> extras = null,bool IsRecordLog=true)
        {
            var flag = false;
            try
            {
                var result = pushService.PushMessage(to, empId, content, title, pushType, pushLogType, extras, IsRecordLog);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("PushMessage1云信Code: {0}", result.code)));
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "PushMessage1异常信息");
            }
            return flag;
        }

        #endregion

        
        #region 群管理
        ///<summary>
        /// 拉人进群
        /// </summary>
        /// <param name="tid">网易云通信服务器产生，群唯一标识，创建群时会返回，最大长度128字符</param>
        /// <param name="owner">群主用户帐号，最大长度32字符</param>
        /// <param name="members">	["aaa","bbb"](JSONArray对应的accid，如果解析出错会报414)，一次最多拉200个成员</param>
        /// <param name="magree">管理后台建群时，0不需要被邀请人同意加入群，1需要被邀请人同意才可以加入群。其它会返回414</param>
        /// <param name="msg">邀请发送的文字，最大长度150字符</param>
        /// <returns></returns>
        public static TeamAddReturnInfo TeamAdd(string tid, string owner, List<String> members, int magree, string msg)
        {
            try
            {
                var result = messageService.TeamAdd(tid, owner, members, magree, msg);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamAdd云信Code: {0}", result.code)));
                }
                else
                {
                    return result.FaccId;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamAdd异常信息");
            }
            return null;
        }

        // <summary>
        /// 更新群At信息
        /// </summary>
        /// <param name="tid">群聊ID</param>
        /// <param name="ats">ats内容集合</param>
        /// <returns></returns>
        public Result TeamUpdateAts(string tid, string ats)
        {
            try
            {
                var result = messageService.TeamUpdateAts(tid, ats);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamUpdateAts云信Code: {0}", result.code)));
                }
                return result;
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamUpdateAts异常信息");
            }
            return null;
        }

        /// <summary>
        /// 创建群进群
        /// </summary>
        /// <param name="tname">群名称，最大长度64字符</param>
        /// <param name="owner">群主用户帐号，最大长度32字符</param>
        /// <param name="members">	["aaa","bbb"](JSONArray对应的accid，如果解析出错会报414)，一次最多拉200个成员</param>
        /// <param name="msg">邀请发送的文字，最大长度150字符</param>
        /// <param name="magree">管理后台建群时，0不需要被邀请人同意加入群，1需要被邀请人同意才可以加入群。其它会返回414</param>
        /// <param name="joinmode">群建好后，sdk操作时，0不用验证，1需要验证,2不允许任何人加入。其它返回414</param>
        /// <param name="invitemode">谁可以邀请他人入群，0-管理员(默认),1-所有人。其它返回414</param>
        /// <returns></returns>
        public static TeamAddResult TeamCreate(string tname, string owner, List<String> members, string msg, int magree = 0, int joinmode = 0, int invitemode = 1)
        {
            try
            {
                var result = messageService.TeamCreate(tname, owner, members, msg, magree, joinmode, invitemode);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamCreate云信Code: {0}", result.code)));
                }
                return result;
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamCreate异常信息");
                return new TeamAddResult() { code = 414 };
            }
        }


        /// <summary>
        /// 踢人出群
        /// </summary>
        /// <param name="tid">网易云通信服务器产生，群唯一标识，创建群时会返回，最大长度128字符</param>
        /// <param name="owner">群主用户帐号，最大长度32字符</param>
        /// <param name="members">	["aaa","bbb"](JSONArray对应的accid，如果解析出错会报414)，一次最多踢拉200个成员</param>
        /// <returns></returns>
        public static void TeamKick(string tid, string owner, List<String> members)
        {
            try
            {
                var result = messageService.TeamKick(tid, owner, members);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamKick云信Code: {0}", result.code)));
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamKick异常信息");
            }
        }

        /// <summary>
        /// 修改群信息
        /// </summary>
        /// <param name="tid">网易云通信服务器产生，群唯一标识，创建群时会返回，最大长度128字符</param>
        /// <param name="owner">群主用户帐号，最大长度32字符</param>
        /// <param name="tname">	群名称，最大长度64字符</param>
        /// <returns></returns>
        public static void TeamUpdate(string tid, string owner, string tname)
        {
            try
            {
                var result = messageService.TeamUpdate(tid, owner, tname);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamUpdate云信Code: {0}", result.code)));
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamUpdate异常信息");
            }
        }

        /// <summary>
        /// 解散群
        /// </summary>
        /// <param name="tid">网易云通信服务器产生，群唯一标识，创建群时会返回，最大长度128字符</param>
        /// <param name="owner">群主用户帐号，最大长度32字符</param>
        /// <returns></returns>
        public static bool TeamRemove(string tid, string owner)
        {
            bool isSuccess = false;
            try
            {
                var result = messageService.TeamRemove(tid, owner);
                if (result.code != 200)
                {
                    IM.Util.LogHelper.Write(new Exception(String.Format("TeamRemove云信Code: {0}", result.code)));
                }
                else
                {
                    isSuccess = true;
                }
            }
            catch (Exception e)
            {
                IM.Util.LogHelper.Write(e, "TeamRemove异常信息");
            }
            return isSuccess;
        }
        #endregion
    }
}