using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App.Entity;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Param;
using System.Text;
using System.Web;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Tools;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 健康俱乐部
	/// </summary>
	public class HealthClubService : BaseService, IHealthClubService
    {
        IPubUserInfoRepository _pubUserInfoRepository;
        private readonly IPubClubYouZanOrderRepository _pubYouZanOrderRepository;
        private readonly IYouZanService _youZanService;
        private readonly IPubUserClickRepository _pubUserClickRepository;
        private readonly ILogger<HealthClubService> _logger;
        IHealthClubRepository _healthClubRepository;
        ISysRepository _sysRepository;
        IOutMapDocPatRepository _outMapDocPatRepository;
        IOutMapPatTagService _outMapPatTagService;
        IPubMapPatuserDocuserRepository _pubMapPatuserDocuserRepository;
        ITencentService _tencentService;
        /// <summary>
        /// 健康俱乐部
        /// </summary>
        public HealthClubService(
            IHealthClubRepository healthClubRepository, 
            IPubUserInfoRepository pubUserInfoRepository,
            ISysRepository sysRepository, 
            IOutMapDocPatRepository outMapDocPatRepository,
            IOutMapPatTagService outMapPatTagService, 
            IPubMapPatuserDocuserRepository pubMapPatuserDocuserRepository,
            ITencentService tencentService, 
            IPubClubYouZanOrderRepository pubYouZanOrderRepository,
            IYouZanService youZanService, 
            IPubUserClickRepository pubUserClickRepository,
            ILogger<HealthClubService> logger)
        {
            _pubUserInfoRepository = pubUserInfoRepository;
            _pubYouZanOrderRepository = pubYouZanOrderRepository;
            _youZanService = youZanService;
            _pubUserClickRepository = pubUserClickRepository;
            _logger = logger;
            _healthClubRepository = healthClubRepository;
            _sysRepository = sysRepository;
            _outMapDocPatRepository = outMapDocPatRepository;
            _outMapPatTagService = outMapPatTagService;
            _pubMapPatuserDocuserRepository = pubMapPatuserDocuserRepository;
            _tencentService = tencentService;
        }


        public async Task<List<Pub_Club_Vedio>> GetIndexVedio()
        {
            return await _healthClubRepository.GetIndexVedio();
        }

        /// <summary>
        /// 同步有赞订单
        /// </summary>
        /// <param name="requestBodyString"></param>
        /// <returns></returns>
        public async Task SyncYouZanOrder(string requestBodyString)
        {
            try
            {
                var tradePaidParam = JsonConvert.DeserializeObject<TradePaidParam>(requestBodyString);

                if (tradePaidParam == null)
                {
                    return;
                }

                var fullOrderInfoString = HttpUtility.UrlDecode(tradePaidParam.msg, Encoding.UTF8);

                var tradePaidPushDto = JsonConvert.DeserializeObject<TradePaidPushDto>(fullOrderInfoString);

                var fullOrderInfo = tradePaidPushDto.full_order_info;

                //判断是不是“健康俱乐部”的订单 
                if (!fullOrderInfo.Orders.Exists(x => x.Alias == YouZanConfig.HealthClubGoodsAlias))
                {
                    return;
                }

                var pubYouZanOrder = new Pub_Club_YouZanOrder
                {
                    YzOpenId = fullOrderInfo.BuyerInfo.YzOpenId,
                    YzOrderId = fullOrderInfo.OrderInfo.Tid,
                    CreateTime = DateTime.Now
                };

                //解密出买家手机号
                var buyerPhoneResponse = _youZanService.DecryptSingle(new DecryptSingleRequest
                {
                    Source = fullOrderInfo.BuyerInfo.BuyerPhone
                });

                if (buyerPhoneResponse != null && buyerPhoneResponse.code == 200 && buyerPhoneResponse.success && !string.IsNullOrEmpty(buyerPhoneResponse.data))
                {
                    pubYouZanOrder.Phone = buyerPhoneResponse.data;

                    //根据买家手机号去pub_user_info中去匹配
                    var pubUser = _pubUserInfoRepository.GetUserByPhone(buyerPhoneResponse.data);
                    if (pubUser != null)
                    {
                        pubYouZanOrder.UserId = pubUser.ID;

                        //标记为付费观看
                        _pubUserInfoRepository.YouZanRecordWatchMode(pubUser.ID, 2);

                        //判断是否需要更新有赞opid
                        if (pubUser.YZOpenId != fullOrderInfo.BuyerInfo.YzOpenId)
                        {
                            await _pubUserInfoRepository.YouZanMatchUserOpenId(pubUser.ID, fullOrderInfo.BuyerInfo.YzOpenId);
                        }
                    }
                    else
                    {
                        var newPubUserInfo = new Pub_User_Info
                        {
                            Language = 1,
                            Registration_Source = 5,
                            Phone = buyerPhoneResponse.data,
                            IsReadSignOff = false,
                            Is_Deleted = false,
                            Is_Read_Informed = false,
                            YZWatchMode = 2,
                            Create_Time = DateTime.Now
                        };

                        #region 通过订单关联的“买家信息”的有赞openid，查询有赞用户

                        //通过订单关联的“买家信息”的有赞openid，查询有赞用户
                        var yzUserResponse = _youZanService.GetYouZanUser(fullOrderInfo.BuyerInfo.YzOpenId);
                        if (yzUserResponse != null && yzUserResponse.user_list.Any())
                        {
                            var yzUser = yzUserResponse.user_list.FirstOrDefault();
                            if (yzUser != null)
                            {
                                newPubUserInfo.Nick_Name = yzUser.primitive_info.nick_name.RemoveEmoji();
                                newPubUserInfo.Country = yzUser.primitive_info.country;
                                newPubUserInfo.City = yzUser.primitive_info.city;
                                newPubUserInfo.HeadImg = yzUser.primitive_info.avatar;
                                newPubUserInfo.YZOpenId = yzUser.primitive_info.yz_open_id;

                                switch (yzUser.primitive_info.gender)
                                {
                                    case 0:
                                    case 1:
                                        newPubUserInfo.Gender = 1;
                                        break;
                                    case 2:
                                        newPubUserInfo.Gender = 0;
                                        break;
                                }

                                //获取生日字段
                                var yzCustomerInfo = _youZanService.GetYouZanCustomer(new CustomerGetRequest
                                {
                                    yz_open_id = yzUser.primitive_info.yz_open_id,
                                    fields = "user_base,tags,benefit_cards,benefit_level,benefit_rights,credit,behavior,giftcard,prepaid,coupon,level"
                                });

                                if (yzCustomerInfo != null)
                                {
                                    newPubUserInfo.Birthday = yzCustomerInfo.data.birthday.Substring(0, 10);
                                }
                            }
                        }

                        #endregion

                        _pubUserInfoRepository.InsertPubUserInfo(newPubUserInfo);
                    }
                }

                //储存订单信息
                await _pubYouZanOrderRepository.InsertAndReturnIdAsync(pubYouZanOrder);
            }
            catch (System.Exception e)
            {
                _logger.LogInformation($"trade_TradePaid:requestBodyString---{requestBodyString}");
                _logger.LogError(e.ToJson());
            }
        }

        /// <summary>
        /// 记录“下载app免年费”按钮点击
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public async Task RecordDownloadAppClickAsync(string ip)
        {
            var clickRecord = new Pub_User_Click
            {
                Ip = ip,
                CreateTime = DateTime.Now,
            };

            await _pubUserClickRepository.InsertAndReturnAsync(clickRecord);
        }
        public int AddHealthClub(OutHealthClub model)
        {
            _healthClubRepository.InsertHealthClub(model);
            AddHealthClubMap(model.Phone, model.TagId);
            return 1;
        }

        public void AddHealthClubMap(string phone, string tagIdList)
        {
            Pub_User_Info pubUserInfo = _pubUserInfoRepository.SelectByPhone(phone);
            if (pubUserInfo != null)
            {
                //添加好友
                //1.查找医生端账号
                //PubDoctorUserInfo doctorUserInfo = doctorUserInfoMapper.selectDocListByHealthClub();
                var sysDoc = _sysRepository.SelectDocListByHealthClub();
                if (sysDoc != null)
                {
                    //2.将好友添加
                    Out_Map_Doc_Pat mapDocPat = _outMapDocPatRepository.SelectByDocIdWithPatId(sysDoc.Id, pubUserInfo.ID);
                    if (mapDocPat != null)
                    {
                        //已经是好友了，添加标签
                        if (!string.IsNullOrEmpty(tagIdList))
                        {
                            List<string> tagList = tagIdList.Split(',')?.ToList();
                            if (tagList?.Count() > 0)
                            {
                                foreach (var tagId in tagList)
                                {
                                    _outMapPatTagService.SetTag(sysDoc.Id, Convert.ToInt32(tagId), pubUserInfo.ID);
                                }
                            }
                        }
                        return;
                    }
                    else
                    {
                        Pub_Map_Patuser_Docuser mapPatuserDocuser = new Pub_Map_Patuser_Docuser();
                        mapPatuserDocuser.Pat_User_Id = pubUserInfo.ID;
                        mapPatuserDocuser.Doc_User_Id = sysDoc.Id;
                        mapPatuserDocuser.Status = 1;
                        mapPatuserDocuser.Create_Time = DateTime.Now;
                        _pubMapPatuserDocuserRepository.InsertPatuserDocuser(mapPatuserDocuser);

                        mapDocPat = new Out_Map_Doc_Pat();
                        mapDocPat.Doctor_Id = sysDoc.Id;
                        mapDocPat.Pat_Id = pubUserInfo.ID;
                        mapDocPat.Is_Star = 0;
                        mapDocPat.Is_Topping = 0;
                        mapDocPat.Status = 1;
                        mapDocPat.Create_Time = DateTime.Now;
                        _outMapDocPatRepository.InsertOutMapDocPat(mapDocPat);

                        _tencentService.FriendAdd(pubUserInfo.IM_ID, new List<string> { sysDoc.ImId });
                        //发送一条消息
                        _tencentService.SendFriendMsg(sysDoc.ImId, pubUserInfo.IM_ID, "我们已经互相关注了，快发起会话吧。" + "We have followed each other,let's start chat.");
                        //3.添加患者标签

                        if (!string.IsNullOrEmpty(tagIdList))
                        {
                            List<string> tagList = tagIdList.Split(',')?.ToList();
                            if (tagList?.Count() > 0)
                            {
                                foreach (var tagId in tagList)
                                {
                                    _outMapPatTagService.SetTag(sysDoc.Id, Convert.ToInt32(tagId), pubUserInfo.ID);
                                }
                            }
                        }
                    }
                }
            }
        }


    }
}
