using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.ContractModel.Tencent;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using Newtonsoft.Json;
using ASHermed.SinoInterface.Tools.Base;
using PoJun.Util;
using PoJun.Util.Maps;
using System;
using System.Collections.Generic;
using System.Text;
using TencentCloud.Common;
using TencentCloud.Cvm.V20170312;
using TencentCloud.Cvm.V20170312.Models;
using tencentyun;
using Microsoft.Extensions.Logging;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 腾讯IM
	/// </summary>
	public class TencentService : BaseService, ITencentService
    {
        #region 初始化
        AppConfigurtaion _appConfigurtaion;
        IPubUserInfoRepository _pubUserInfoRepository;
        ITencentOutService _tencentOutService;
        IOutService _outService;
        IPubMessageInfoRepository _pubMessageInfoRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        ILogger<TencentService> _logger;
        public TencentService(AppConfigurtaion appConfigurtaion, IPubUserInfoRepository pubUserInfoRepository, ITencentOutService tencentOutService, IOutService outService, IPubMessageInfoRepository pubMessageInfoRepository, IPubPatInfoRepository pubPatInfoRepository, ILogger<TencentService> logger)
        {
            _appConfigurtaion = appConfigurtaion;
            _pubUserInfoRepository = pubUserInfoRepository;
            _tencentOutService = tencentOutService;
            _outService = outService;
            _pubMessageInfoRepository = pubMessageInfoRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _logger = logger;
        }
        #endregion
        private readonly string addFriendUrl = "";



        public VideoUserSignResp GetUsersigByPat(int userId)
        {
            VideoUserSignResp result = new VideoUserSignResp();
            string imId = _appConfigurtaion.GetTencentUserPrefix + "_pat_" + userId;

            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(_appConfigurtaion.GetTencentAppid.ToInt(), _appConfigurtaion.GetTencentKey);
            string usersig = tlsSigAPIv2.genUserSig(imId, _appConfigurtaion.GetTencentSignTime.ToInt());
            //修改用户IMID
            Pub_User_Info info = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            info.IM_ID = imId;
            _pubUserInfoRepository.UpdatePubUserInfo(info);

            //导入用户
            ImportUser(imId, info.Nick_Name, info.HeadImg);

            result.Key = usersig;
            result.UserId = imId;
            return result;
        }

        public string GetKey(string identifier)
        {
            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(_appConfigurtaion.GetTencentAppid.ToInt(), _appConfigurtaion.GetTencentKey);
            return tlsSigAPIv2.genUserSig(identifier, _appConfigurtaion.GetTencentSignTime.ToInt());
        }

        /// <summary>
        /// 获取管理员签名
        /// </summary>
        /// <returns></returns>
        public string GetAdminUserSig()
        {
            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(_appConfigurtaion.GetTencentAppid.ToInt(), _appConfigurtaion.GetTencentKey);
            string adminUsersig = tlsSigAPIv2.genUserSig(_appConfigurtaion.GetTencentAdmin, _appConfigurtaion.GetTencentSignTime.ToInt());
            return adminUsersig;
        }

        /// <summary>
        /// 导入用户
        /// </summary>
        /// <param name="imId"></param>
        /// <param name="nickName"></param>
        /// <param name="headImg"></param>
        public void ImportUser(string imId, string nickName, string headImg)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/im_open_login_svc/account_import?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            //var dic = new Dictionary<string, string>();
            //dic.Add("Identifier", imId);
            //dic.Add("Nick", nickName);
            //dic.Add("FaceUrl", headImg);
            var listParm = new List<(string Name, string FileName, object Value)>();
            listParm.Add(("Identifier", "", imId));
            listParm.Add(("Nick", "", nickName));
            listParm.Add(("FaceUrl", "", headImg == null ? "" : headImg));
            _tencentOutService.ImportUser(_appConfigurtaion.GetTencentUrl, apiUrl, listParm);

        }
        /// <summary>
        /// 创建群组
        /// </summary>
        public ImRepBody CreateTencentGroup(string groupName, string doc, string pat, int aptId, string helperImId)
        {
            string importUsersig = GetAdminUserSig();
            var api = "v4/group_open_http_svc/create_group?sdkappid=" + _appConfigurtaion.GetTencentAppid + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            //var listParm = new List<(string Name, string FileName, object Value)>();
            //listParm.Add(("Name", "", groupName));//群名称（必填）
            //listParm.Add(("Type", "", "Public")); //群组类型：Private / Public / ChatRoom / AVChatRoom

            //listParm.Add(("Owner_Account", "", helperImId));//群主的 UserId（选填）
            //listParm.Add(("GroupId", "", _appConfigurtaion.GetTencentUserPrefix + aptId));//用户自定义群组 ID（选填）
            var members = new List<Member>();
            members.Add(new Member { Member_Account = doc });//医生
            members.Add(new Member { Member_Account = pat });//患者
                                                             //listParm.Add(("MemberList", "", members.ToArray()));//初始群成员列表，最多500个（选填）
                                                             //listParm.Add(("ApplyJoinOption", "", "DisableApply"));//申请加群处理方式（选填）包含 FreeAccess（自由加入），NeedPermission（需要验证），DisableApply（禁止加群），不填默认为 NeedPermission（需要验证）

            var parms = new Dictionary<string, object>();
            parms.Add("Name", groupName);
            parms.Add("Type", "Public");
            parms.Add("FaceUrl", "");
            parms.Add("Owner_Account", helperImId);
            //parms.Add("GroupId", _appConfigurtaion.GetTencentUserPrefix + aptId);
            parms.Add("MemberList", members.ToArray());
            parms.Add("ApplyJoinOption", "DisableApply");
            var rett = _tencentOutService.CreateGroup(_appConfigurtaion.GetTencentUrl, api, parms);
            return rett;// _tencentOutService.CreateGroup(_appConfigurtaion.GetTencentUrl, api, listParm);
        }

        /// <summary>
        /// 群组添加成员
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="patIMID"></param>
        /// <returns></returns>
        public GroupAddMemberReb AddTencentGroupMember(string groupId, string patIMID)
        {
            string importUsersig = GetAdminUserSig();
            var api = "v4/group_open_http_svc/add_group_member?sdkappid=" + _appConfigurtaion.GetTencentAppid + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";

            var members = new List<Member>();
            members.Add(new Member { Member_Account = patIMID });//患者

            var parms = new Dictionary<string, object>();
            parms.Add("GroupId", groupId);
            parms.Add("Silence", 1);
            parms.Add("MemberList", members.ToArray());
            var rett = _tencentOutService.AddGroupMember(_appConfigurtaion.GetTencentUrl, api, parms);
            return rett;// _tencentOutService.CreateGroup(_appConfigurtaion.GetTencentUrl, api, listParm);
        }

        /// <summary>
        /// 群组删除成员
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="patIMID"></param>
        /// <returns></returns>
        public TencentResponse DeleteTencentGroupMember(string groupId, string patIMID)
        {
            string importUsersig = GetAdminUserSig();
            var api = "v4/group_open_http_svc/delete_group_member?sdkappid=" + _appConfigurtaion.GetTencentAppid + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";

            var members = new List<string>();
            members.Add(patIMID);//患者
            var parms = new Dictionary<string, object>();
            parms.Add("GroupId", groupId);
            parms.Add("Silence", 1);
            parms.Add("MemberToDel_Account", members.ToArray());
            var rett = _tencentOutService.DeleteGroupMember(_appConfigurtaion.GetTencentUrl, api, parms);
            return rett;
        }

        public class Member
        {
            public string Member_Account { get; set; }
        }


        public TencentResponse ForbiddenUser(string groupId, string patImId, bool isForbidden)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/forbid_send_msg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("GroupId", groupId);
            var list = new List<string>() { patImId };
            dic.Add("Members_Account", list.ToArray());
            if (isForbidden)
            {
                dic.Add("ShutUpTime", 4294967295);//永久禁言
            }
            else
            {
                dic.Add("ShutUpTime", 0);//解除禁言
            }
            return _tencentOutService.ForbiddenUser(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }
        /// <summary>
        /// 普通消息
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="fromWho"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public TencentMsgRes SendMsgToGroup(string groupId, string fromWho, string content)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/send_group_msg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("GroupId", groupId);
            if (!string.IsNullOrEmpty(fromWho))
            {
                dic.Add("From_Account", fromWho);
            }
            Random rnd = new Random();
            var str = rnd.Next(100000, 999999);
            dic.Add("Random", str);

            var list = new List<Message> {
                new Message() {
                    MsgType = "TIMTextElem",
                    MsgContent=new TIMTextElem() {
                        Text = content }
                }
            };
            dic.Add("MsgBody", list.ToArray());
            return _tencentOutService.SendMsgToGroup(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }

        /// <summary>
        /// 自定义消息
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="fromWho"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public TencentMsgRes SendCusMsgToGroup(string groupId, string fromWho, string content)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/send_group_msg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("GroupId", groupId);
            if (!string.IsNullOrEmpty(fromWho))
            {
                dic.Add("From_Account", fromWho);
            }
            Random rnd = new Random();
            var str = rnd.Next(100000, 999999);
            dic.Add("Random", str);


            var list = new List<CusMessage> {
                new CusMessage() {
                    MsgType = "TIMCustomElem",
                    MsgContent=new TIMCustomElem() {
                        Data= content,Desc="20",Ext="30",Sound="40" }
                }
            };
            dic.Add("MsgBody", list.ToArray());
            return _tencentOutService.SendMsgToGroup(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }

        /// <summary>
        /// 系统消息
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="content"></param>
        /// <param name="toMembers"></param>
        /// <returns></returns>
        public TencentResponse SendSysMsgToGroup(string groupId, string content, List<string> toMembers)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/send_group_system_notification?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("GroupId", groupId);
            if (toMembers != null && toMembers.Count > 0)
            {
                dic.Add("ToMembers_Account", toMembers.ToArray());
            }
            dic.Add("Content", content);
            return _tencentOutService.SendSysMsgToGroup(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }

        //
        public IMRecord GetIMRecord(string msgTime, string chatType)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/open_msg_svc/get_history?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("ChatType", chatType);//Group //C2C
            dic.Add("MsgTime", msgTime);
            return _tencentOutService.GetIMRecord(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }

        public void GetIMRecordjob()
        {
            var date = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            string hour = string.Empty;
            for (int i = 0; i < 24; i++)//24小时
            {
                if (i < 10)
                {
                    hour = "0" + i;
                }
                else
                {
                    hour = i.ToString();
                }
                var groupRecord = GetIMRecord(date + hour, "Group");
                if (groupRecord != null && groupRecord.ErrorCode == 0 && groupRecord.File != null && groupRecord.File.Count > 0)
                {
                    for (int j = 0; j < groupRecord.File.Count; j++)
                    {
                        UploadHelper.HttpDownloadFile(groupRecord.File[j].Url, groupRecord.ChatType + groupRecord.MsgTime + "_" + j + ".gz", "IMRecord");
                    }
                }
                groupRecord = GetIMRecord(date + hour, "C2C");//去拉单发消息
                if (groupRecord != null && groupRecord.ErrorCode == 0 && groupRecord.File != null && groupRecord.File.Count > 0)
                {
                    for (int j = 0; j < groupRecord.File.Count; j++)
                    {
                        UploadHelper.HttpDownloadFile(groupRecord.File[j].Url, groupRecord.ChatType + groupRecord.MsgTime + "_" + j + ".gz", "IMRecord");
                    }
                }
            }
        }

        /// <summary>
        /// 添加好友
        /// </summary>
        /// <returns></returns>
        public AddFriendReb FriendAdd(string from, List<string> list)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/sns/friend_add?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("From_Account", from);
            var friends = new List<FriendItem>();
            foreach (var item in list)
            {
                var friend = new FriendItem() { To_Account = item };
                friends.Add(friend);
            }
            dic.Add("AddFriendItem", friends.ToArray());
            dic.Add("ForceAddFlags", 1);
            return _tencentOutService.FriendAdd(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }

        /// <summary>
        /// 单聊发送消息(监控质询)
        /// </summary>
        /// <returns></returns>
        public MsgFriendReb SendFriendMsg(string from, string toWho, string content)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/openim/sendmsg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("SyncOtherMachine", 1);
            dic.Add("From_Account", from);
            dic.Add("To_Account", toWho);
            dic.Add("MsgRandom", Common.NewCode().ToInt());
            dic.Add("MsgTimeStamp", Common.GetTimeStamp().ToInt());
            var list = new List<CusMessage> {
                new CusMessage() {
                    MsgType = "TIMCustomElem",
                    MsgContent=new TIMCustomElem() {
                        Data= content,Desc="20",Ext="30",Sound="40" }
                }
            };
            dic.Add("MsgBody", list.ToArray());
            return _tencentOutService.SendFriendMsg(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }
        /// <summary>
        /// 单发消息(文本)
        /// </summary>
        /// <param name="from"></param>
        /// <param name="toWho"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public MsgFriendReb SendFriendMsgOnly(string from, string toWho, string content)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/openim/sendmsg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("SyncOtherMachine", 1);
            dic.Add("From_Account", from);
            dic.Add("To_Account", toWho);
            dic.Add("MsgRandom", Common.NewCode().ToInt());
            dic.Add("MsgTimeStamp", Common.GetTimeStamp().ToInt());
            var list = new List<Message> {
                new Message() {
                    MsgType = "TIMTextElem",
                    MsgContent=new TIMTextElem() {
                        Text = content }
                }
            };
            dic.Add("MsgBody", list.ToArray());
            return _tencentOutService.SendFriendMsg(_appConfigurtaion.GetTencentUrl, apiUrl, dic);

        }
        public ImGroup GetGroupById(string groupId)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/get_group_member_info?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";
            var dic = new Dictionary<string, object>();
            dic.Add("GroupId", groupId);
            return _tencentOutService.GetGroupMemberInfo(_appConfigurtaion.GetTencentUrl, apiUrl, dic);
        }

        /// <summary>
        /// 发送@所有人消息//java转过来的
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="imid"></param>
        /// <param name="content"></param>
        public void SendAtAll(string groupId, string sendImId, string content)
        {
            string importUsersig = GetAdminUserSig();
            //导入用户
            string apiUrl = "v4/group_open_http_svc/send_group_msg?sdkappid=" + _appConfigurtaion.GetTencentAppid.ToInt() + "&identifier=" + _appConfigurtaion.GetTencentAdmin + "&usersig=" + importUsersig + "&random=99999999&contenttype=json";

            Random rnd = new Random();
            var str = rnd.Next(100000, 999999);
            TenGroupSendModel sendAllMsg = new TenGroupSendModel();
            sendAllMsg.GroupId = groupId;
            sendAllMsg.Random = str;
            sendAllMsg.FromAccount = sendImId;

            TenBodyModel msgBodyBean = new TenBodyModel();
            msgBodyBean.MsgType = "TIMTextElem";

            TenMsgContentModel msgContentBean = new TenMsgContentModel();
            msgContentBean.Text = "@ALL " + content;
            msgBodyBean.MsgContent = msgContentBean;

            GroupAtModel groupAtInfoBean = new GroupAtModel();
            groupAtInfoBean.GroupAtAllFlag = 1;

            sendAllMsg.MsgBody = new List<TenBodyModel>();
            sendAllMsg.MsgBody.Add(msgBodyBean);
            sendAllMsg.GroupAtInfo = new List<GroupAtModel>();
            sendAllMsg.GroupAtInfo.Add(groupAtInfoBean);
            string jsonObject = JsonConvert.SerializeObject(sendAllMsg);
            _tencentOutService.SendAtAll(_appConfigurtaion.GetTencentUrl + apiUrl, jsonObject);
        }

        public class FriendItem
        {
            public string To_Account { get; set; }
            public string AddSource { get; set; } = "AddSource_Type_Sino";
        }

        public class Message
        {
            public string MsgType { get; set; }
            public TIMTextElem MsgContent { get; set; }
        }

        public class CusMessage
        {
            public string MsgType { get; set; }
            public TIMCustomElem MsgContent { get; set; }
        }
        public class TIMTextElem
        {
            public string Text { get; set; }

        }

        public class TIMCustomElem
        {
            public string Data { get; set; }
            public string Desc { get; set; }
            public string Ext { get; set; }
            public string Sound { get; set; }
        }

        public WXLoginResb WXLogin(string code, int language)
        {
            var appId = _appConfigurtaion.GetWXAppletId;
            var appSecret = _appConfigurtaion.GetWXAppletSecret;
            var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

            var res = _outService.HttpGet<WXLoginResb>(url);
            if (res == null)
            {
                res = new WXLoginResb() { Errcode = -1, Errmsg = language == 1 ? "微信登录请求失败" : "WeChat Login Error" };
            }
            _logger.LogInformation("微信第一部" + res?.ToJson());
            return res;
        }


        /// <summary>
        /// 把消息设置为已读
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int ReadMessage(ReadInfo info)
        {
            _pubMessageInfoRepository.UpdateMsgRead(info.PatId, info.DocId);
            return 1;
        }

        /// <summary>
        /// 添加消息记录-用于云诊室列表页红点
        /// </summary>
        /// <param name="patId"></param>
        /// <param name="servType">0=用户-小影/1=客服-用户/2用户-科室/3科室-用户/4医生/5医助</param>
        /// <param name="servId"></param>
        /// <param name="content"></param>
        /// <param name="messageType">0=文本/1=图片/2=患教</param>
        /// <returns></returns>
        public int AddMessage(int patId, int userID, int servType, string servId, string content, int messageType)
        {
            var info = new Pub_Message_Info();
            info.Content = content;
            info.Content_Type = 6;
            info.Create_Time = DateTime.Now;
            info.Doctor_Read = false;
            info.Message_Type = messageType;
            info.Pat_Id = patId;
            info.Service_Id = servId;
            info.Source_Type = servType;
            info.Status = 0;
            info.User_Id = userID;
            info.User_Read = false;
            return _pubMessageInfoRepository.InsertPubMessageInfo(info);
        }
    }
}
