using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Coupon.Entity;
using ASHermed.SinoInterface.Api.ContractModel.Coupon.Model;
using ASHermed.SinoInterface.Api.ContractModel.Tencent;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Enum.App;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.Tools;
using Microsoft.Extensions.Logging;
using PoJun.Util.Maps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PoJun.Util;
using System.Net;

namespace ASHermed.SinoInterface.Api.Service
{
    public class AdvisoryService : BaseService, IAdvisoryService
    {
        ILogger<AdvisoryService> _logger;
        IPubUserInfoRepository _pubUserInfoRepository;
        ITencentService _tencentService;
        IOutIMGroupRepository _outIMGroupRepository;
        IOutMapUserImgroupRepository _outMapUserImgroupRepository;
        IPubMessageInfoRepository _pubMessageInfoRepository;
        IJpushService _jpushService;
        IOutDoctorStatusInfoRepository _outDoctorStatusInfoRepository;
        IDicDoctorRepository _dicDoctorRepository;

        public AdvisoryService(ILogger<AdvisoryService> logger, IPubUserInfoRepository pubUserInfoRepository, ITencentService tencentService, IOutIMGroupRepository outIMGroupRepository, IOutMapUserImgroupRepository outMapUserImgroupRepository, IPubMessageInfoRepository pubMessageInfoRepository, IJpushService jpushService, IOutDoctorStatusInfoRepository outDoctorStatusInfoRepository, IDicDoctorRepository dicDoctorRepository)
        {
            _logger = logger;
            _tencentService = tencentService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _outIMGroupRepository = outIMGroupRepository;
            _outMapUserImgroupRepository = outMapUserImgroupRepository;
            _pubMessageInfoRepository = pubMessageInfoRepository;
            _jpushService = jpushService;
            _outDoctorStatusInfoRepository = outDoctorStatusInfoRepository;
            _dicDoctorRepository = dicDoctorRepository;
        }


        public void SendGroupMsgByPat(int userId, string content, string groupId, int groupMsgType, string aiteImId)
        {
            //敏感词过滤
            BadWordFilter badWordFilter = BadWordFilter.CreateBadWordsFilter();
            badWordFilter.Init(BadWords.Words.Split(','));
            content = badWordFilter.ReplaceBadWord(content);
            //获取发送人用户信息
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            //获取群组信息
            ImGroup imGroup = _tencentService.GetGroupById(groupId);
            if (userInfo != null && imGroup != null && imGroup.MemberList != null && imGroup.MemberList.Count() > 0)
            {
                if (groupMsgType == 1) //groupMsgType 1单人艾特  2群公告  3普通消息
                {
                    List<PubUserModel> aiteUserInfo = null;
                    //艾特消息
                    //循环发送通知
                    foreach (var groupMember in imGroup.MemberList)
                    {
                        List<string> aiteList = aiteImId.Split(',').ToList();
                        if (aiteList.Count() > 0)
                        {
                            foreach (var aiteId in aiteList)
                            {
                                if (groupMember.Member_Account == aiteId)
                                {
                                    //查询被艾特人为医生还是患者
                                    aiteUserInfo = _pubUserInfoRepository.SelectUserWithDocByImid(aiteId);
                                    if (aiteUserInfo != null && aiteUserInfo.Count() > 0)
                                    {
                                        var aiteUser = aiteUserInfo[0];
                                        if (aiteUser.UserType.ToString() == "1")
                                        {
                                            //患者
                                            PushUserGroup(aiteUser.ID, groupId, 1, userInfo.Nick_Name + "@了你");
                                        }
                                        else
                                        {
                                            //医生
                                            PushDocGroup(aiteUser.ID, groupId, 1, userInfo.Nick_Name + "@了你");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (groupMsgType == 2)//2群公告  
                {
                    if (string.IsNullOrEmpty(content))
                    {
                        //清除公告
                        _outIMGroupRepository.DeleteGroupContent(groupId);
                        return;
                    }
                    //群公告
                    //添加群公告
                    Out_IM_Group outImGroup = new Out_IM_Group();
                    outImGroup.Group_Id = groupId;
                    outImGroup.Create_Time = DateTime.Now;
                    outImGroup.Status = 1;
                    outImGroup.Group_Content = content;
                    outImGroup.IM_Id = userInfo.IM_ID;
                    _outIMGroupRepository.InsertOutIMGroup(outImGroup);
                    //IM发送@所有人消息
                    _tencentService.SendAtAll(groupId, userInfo.IM_ID, content);
                    //循环发送通知
                    foreach (var groupMember in imGroup.MemberList)
                    {
                        List<PubUserModel> aiteUserInfo;
                        if (groupMember.Member_Account == userInfo.IM_ID)
                        {
                            //排除自己不推送
                            continue;
                        }
                        //查询推送人为医生还是患者
                        aiteUserInfo = _pubUserInfoRepository.SelectUserWithDocByImid(groupMember.Member_Account);
                        if (aiteUserInfo != null && aiteUserInfo.Count() > 0)
                        {
                            if (aiteUserInfo[0].UserType == 1)
                            {
                                //患者
                                PushUserGroup(aiteUserInfo[0].ID, groupId, 1, userInfo.Nick_Name + " 发起了公告:" + content);
                            }
                            else
                            {
                                //医生
                                PushDocGroup(aiteUserInfo[0].ID, groupId, 1, userInfo.Nick_Name + " 发起了公告:" + content);
                            }
                        }
                    }

                }
                else
                {
                    //其他消息
                    //查询推送人为医生还是患者
                    foreach (var groupMember in imGroup.MemberList)
                    {
                        List<PubUserModel> aiteUserInfo;
                        if (groupMember.Member_Account == userInfo.IM_ID)
                        {
                            //排除自己不推送
                            continue;
                        }
                        //查询是否开启免打扰
                        //获取免打扰信息
                        Out_Map_User_Imgroup userImgroup = _outMapUserImgroupRepository.SelectByGroup(groupId, groupMember.Member_Account);
                        if (userImgroup != null && userImgroup.Disturb)
                        {
                            continue;
                        }
                        aiteUserInfo = _pubUserInfoRepository.SelectUserWithDocByImid(groupMember.Member_Account);
                        if (aiteUserInfo != null && aiteUserInfo.Count() > 0)
                        {
                            if (aiteUserInfo[0].UserType == 1)
                            {
                                //患者
                                PushUserGroup(aiteUserInfo[0].ID, groupId, 1, userInfo.Nick_Name + ":" + content);
                            }
                            else
                            {
                                //医生
                                PushDocGroup(aiteUserInfo[0].ID, groupId, 1, userInfo.Nick_Name + ":" + content);
                            }
                        }
                    }
                }

            }
        }

        public void PushUserGroup(int userId, string groupId, int jgPushType, string content)
        {
            bool result = false;

            string[] pushKey = new String[1];
            string acceptMd = "3"; // 3Android 2IOS

            //获取用户信息
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1)
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_ID;
                    acceptMd = "3";
                }
                if (userInfo.Key_Type == 2)
                {
                    //IOS设备
                    pushKey[0] = userInfo.IOS_ID;
                    acceptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    //获取用户消息未读数量
                    int unread = _pubMessageInfoRepository.SelectUserUnRead(userId);
                    var pushResult = _jpushService.JiGuangPush(pushKey, "您收到了一条新的消息！", content,
                            jgPushType.ToString(), groupId, unread.ToString(), acceptMd, 1);
                }
            }
        }

        /**
         * 向医生推送群聊消息
         */
        public void PushDocGroup(int doctorId, string groupId, int jgPushType, string content)
        {
            bool result = false;

            string[] pushKey = new string[1];
            string acceptMd = "3";

            //获取医生在线状态信息
            Out_Doctor_Status_Info userInfo = _outDoctorStatusInfoRepository.SelectByDoc(doctorId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1)
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_Id;
                    acceptMd = "3";
                }
                if (userInfo.Key_Type == 2)
                {
                    //IOS设备
                    pushKey[0] = userInfo.Ios_Id;
                    acceptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    //获取医生消息未读数量
                    int unread = _pubMessageInfoRepository.SelectDoctorUnRead(doctorId);
                    var pushResult = _jpushService.JiGuangPush(pushKey, "您收到了一条新的消息！", content,
                            jgPushType.ToString(), groupId, unread.ToString(), acceptMd, 1);
                }
            }
        }

        public bool SendMessage(string userImId, int doctorId, string docImId, string content, int messageType, int source)
        {
            //敏感词过滤
            BadWordFilter badWordFilter = BadWordFilter.CreateBadWordsFilter();
            badWordFilter.Init(BadWords.Words.Split(','));
            content = badWordFilter.ReplaceBadWord(content);
            var userId = GetBaseUserInfo().ID;
            int result = 0;
            Pub_Message_Info info = new Pub_Message_Info();
            info.User_Id = userId;
            info.Source_Type = source;
            info.Message_Type = messageType;
            info.Content = content;
            info.Create_Time = DateTime.Now;
            info.Status = 0;
            info.Service_Id = doctorId.ToString();
            info.Content_Type = 16;//咨询
            info.Is_Hello = false;
            //医生向用户发送消息
            if (source == 3)
            {
                info.User_Read = (false);
                info.Doctor_Read = (true);
                result = _pubMessageInfoRepository.InsertPubMessageInfo(info);
                PushUserMessage(userId, doctorId.ToString(), 1, content); //1咨询
            }
            //source == MessageSourceType
            //USER2XY(0, "用户-小影"),
            //SERV2USER(1, "客服-用户"),
            //USER2DEPT(2, "用户-科室"),
            //DEPT2USER(3, "科室-用户"),
            //DOC2DOC(4, "科室-科室");
            //用户向医生发送消息
            if (source == 2)
            {
                info.User_Read = (true);
                info.Doctor_Read = (false);
                //查询医生是否开始自动回复
                Out_Doctor_Status_Info doctorInfo = _outDoctorStatusInfoRepository.SelectByDoc(doctorId);
                result = _pubMessageInfoRepository.InsertPubMessageInfo(info);
                PushDoctorMessage(userId.ToString(), doctorId, 1, content);
                if (doctorInfo != null && doctorInfo.Is_Reply && userImId != null && docImId != null)
                {
                    //开启自动回复，向用户推送自动回复内容
                    SendMessage(null, doctorId, null, "[自动回复] " + doctorInfo.Reply_Title,
                            0, 3);//3科室-用户
                    //调用im发送消息
                    _tencentService.SendFriendMsgOnly(docImId, userImId, "[自动回复] " + doctorInfo.Reply_Title);
                }
            }
            //医生向医生发送消息
            if (source == 4) //科室-科室
            {
                info.User_Read = (true);
                info.Doctor_Read = (false);
                PushDoctor2DocMessage(userId.ToString(), doctorId, 1, content);
            }
            return result > 0;
        }

        public void PushDoctor2DocMessage(string userId, int doctorId, int jgPushType, string content)
        {
            bool result = false;

            string[] pushKey = new string[1];
            string accptMd = "3";

            //获取医生在线状态信息
            Out_Doctor_Status_Info userInfo = _outDoctorStatusInfoRepository.SelectByDoc(doctorId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1)
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_Id;
                    accptMd = "3";
                }
                if (userInfo.Key_Type == 2)
                {
                    //IOS设备
                    pushKey[0] = userInfo.Ios_Id;
                    accptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    //Pub_Doctor_User_Info doctorUserInfo = _dicDoctorRepository.GetDoctorUserInfo(userId.ToInt());
                    var doctorUserInfo = _dicDoctorRepository.GetSysUserById(userId.ToInt());
                    //获取医生消息未读数量
                    var unread = _pubMessageInfoRepository.SelectDoctorUnRead(doctorId);

                    var pushiResult = _jpushService.JiGuangPush(pushKey, "您收到了一条新的消息！", doctorUserInfo.NickName + ":" + content, jgPushType.ToString(), userId, unread.ToString(), accptMd, 2);
                    if (pushiResult.StatusCode == HttpStatusCode.OK)
                    {
                        result = true;
                    }
                }
            }
        }


        /// <summary>
        ///   MESSAGE(1, "咨询"),SUFFERING(2, "患教"),VIDEO(3, "音视频"),QUEST(4, "满意度调查"), APT_COMIT(5, "预约提交"),APT_CANCEL(6, "预约取消"),INTERACTIVE(7, "互动"),APP_VERSION_NEW(8, "APP更新"), SING_OFF(9, "报告SignOff");
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="doctorId"></param>
        /// <param name="jgPushType"></param>
        /// <param name="content"></param>
        public void PushDoctorMessage(string userId, int doctorId, int jgPushType, string content)
        {
            bool result = false;

            string[] pushKey = new string[1];
            string accptMd = "3";

            //获取医生在线状态信息
            Out_Doctor_Status_Info userInfo = _outDoctorStatusInfoRepository.SelectByDoc(doctorId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1)
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_Id;
                    accptMd = "3";
                }
                if (userInfo.Key_Type == 2 && !string.IsNullOrEmpty(userInfo.Ios_Id))
                {
                    //IOS设备
                    pushKey[0] = userInfo.Ios_Id;
                    accptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    Pub_User_Info pubUserInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId.ToInt());
                    //获取医生消息未读数量
                    var unread = _pubMessageInfoRepository.SelectDoctorUnRead(doctorId);
                    var pushiResult = _jpushService.JiGuangPush(pushKey, "您收到了一条新的消息！", pubUserInfo.Nick_Name + ":" + content, jgPushType.ToString(), userId, unread.ToString(), accptMd, 2);
                    if (pushiResult.StatusCode == HttpStatusCode.OK)
                    {
                        result = true;
                    }
                }

            }
        }

        public void PushUserMessage(int userId, string doctorId, int jgPushType, string content)
        {
            bool result = false;

            string[] pushKey = new string[1];
            string accptMd = "3";

            //获取用户信息
            Pub_User_Info userInfo = _pubUserInfoRepository.SelectByPrimaryKey(userId);
            if (userInfo != null && userInfo.Key_Type != 0)
            {
                //1.判断用户推送key设备类型
                if (userInfo.Key_Type == 1)
                {
                    //安卓设备
                    pushKey[0] = userInfo.Android_ID;
                    accptMd = "3";
                }
                if (userInfo.Key_Type == 2 && !string.IsNullOrEmpty(userInfo.IOS_ID))
                {
                    //IOS设备
                    pushKey[0] = userInfo.IOS_ID;
                    accptMd = "2";
                }
                //开始推送
                if (pushKey[0] != null)
                {
                    //Pub_Doctor_User_Info doctorUserInfo = _dicDoctorRepository.GetDoctorUserInfo(doctorId.ToInt());
                    var doctorUserInfo = _dicDoctorRepository.GetSysUserById(doctorId.ToInt());
                    //获取用户消息未读数量
                    int unread = _pubMessageInfoRepository.SelectUserUnRead(userId);

                    var pushiResult = _jpushService.JiGuangPush(pushKey, "您收到了一条新的消息！", doctorUserInfo.NickName + ":" + content, jgPushType.ToString(), doctorId, unread.ToString(), accptMd, 1);
                    if (pushiResult.StatusCode == HttpStatusCode.OK)
                    {
                        result = true;
                    }
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="doctorId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="appType">1患者版2医生版</param>
        /// <returns></returns>
        public ListMeeagePage<AdvisoryMessage> GetMessageInfo(int doctorId, int pageSize, int pageIndex, int appType)
        {
            var userId = GetBaseUserInfo().ID;
            List<AdvisoryMessage> list = _pubMessageInfoRepository.SelecrMessageInfo(userId, doctorId.ToString());
            ListMeeagePage<AdvisoryMessage> resultList = new ListMeeagePage<AdvisoryMessage>() { ListData = list, PageSize = pageSize, CurPageIndex = pageIndex };
            List<AdvisoryMessage> sortlist = resultList.ListData;
            //SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            foreach (AdvisoryMessage info in list)
            {
                if (info.Create_Time != null)
                    info.MessageTime = GetTimeStr(info.Create_Time);
            }
            sortlist = sortlist.OrderBy(p => p.Create_Time).ToList();
            resultList.ListData = sortlist;
            //将该用户消息设置为已读
            _pubMessageInfoRepository.UpdateRead(userId, doctorId.ToString());
            if (appType == 1)
            {
                resultList.Unread= _pubMessageInfoRepository.SelectUserUnRead(userId);
            }
            else if (appType == 2)
            {
                resultList.Unread= _pubMessageInfoRepository.SelectDoctorUnRead(doctorId);
            }
            return resultList;
        }

        private string GetTimeStr(DateTime createTime)
        {
            long artStamp = createTime.GetMillisecond();
            long nowStamp = DateTime.Now.GetMillisecond();
            long chaStamp = nowStamp - artStamp;
            string time = "";
            long chaTime = chaStamp / 1000;
            if (chaTime < 3600 * 24)
            {
                time = createTime.ToString("HH:mm");
            }
            if (chaTime > 3600 * 24 && chaTime < 3600 * 24 * 365)
            {
                time = createTime.ToString("dd/MM");
            }
            if (chaTime > 3600 * 24 * 365)
            {
                time = createTime.ToString("dd/MM/yy");
            }
            return time;
        }


        public void test()
        {
            ImGroup imGroup = _tencentService.GetGroupById("TGS#2HE5J5DHL");
            imGroup = _tencentService.GetGroupById("TGS#25FPNESHY");
            var asda = 0;
        }

    }
}
