using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Api.IService.App;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PoJun.Util;
using PoJun.Util.Maps;
using Renci.SshNet.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 授权
	/// </summary>
	public class AuthorizationService : BaseService, IAuthorizationService
    {
        AppConfigurtaion _appConfigurtaion;
        IPubAuthorizationRepository _pubAuthorizationRepository;
        IPubPatInfoRepository _pubPatInfoRepository;
        /// <summary>
        /// 授权  不要在这调用别的service
        /// </summary>
        public AuthorizationService(AppConfigurtaion appConfigurtaion, IPubAuthorizationRepository pubAuthorizationRepository, IPubPatInfoRepository pubPatInfoRepository)
        {
            _appConfigurtaion = appConfigurtaion;
            _pubAuthorizationRepository = pubAuthorizationRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
        }

        public string IsHasAuth(int userId, int patId, int authType, int language)
        {
            List<int> patids = new List<int>();
            patids.Add(patId);
            //患者是本人，不需要授权
            var map = _pubPatInfoRepository.GetMapUserPat(userId, patids);
            if (map.Any() && map.Where(w => w.Ties == 1).Any())
            {
                return null;
            }
            //患者年龄小于18，不需要授权
            var pat = _pubPatInfoRepository.SelectById(patId);
            if (pat != null && !string.IsNullOrEmpty(pat.Birthday) && Tools.Tools.GetAgeByBirth(DateTime.Parse(pat.Birthday)) < 18)
            {
                return null;
            }


            var auth = _pubAuthorizationRepository.GetUserAuthorizationByPat(userId, patId);
            if (auth != null && auth.Status == 3 && auth.ExamineDetailIds.Contains(authType.ToString()))
            {
                if (auth.IsForever)
                {
                    return null;
                }
                else if (auth.AuthorizationValidity > DateTime.Now.AddDays(-1))
                {
                    return null;
                }
            }
            return language == 1 ? "您未被该患者授权" : "Unauthorized By Patient";
        }

        public bool RemoveAuth(int userId, int patId)
        {
            _pubAuthorizationRepository.RemoveUserAuthorization(userId, patId);
            return true;
        }


        public List<Pub_Pat_Info> GetUserAuthPats(int userId, int authType)
        {
            var pats = _pubPatInfoRepository.GetPatientsByUserId(userId);
            var maps = _pubPatInfoRepository.GetMapUserPat(userId, pats.Select(w => w.Id).ToList());
            var auths = _pubAuthorizationRepository.GetUserAuthorization(userId);
            if (pats == null || auths == null)
            {
                return new List<Pub_Pat_Info>();
            }
            var retList = new List<Pub_Pat_Info>();
            foreach (var pat in pats)
            {
                var age = 99;
                try
                {
                    age = Tools.Tools.GetAgeByBirth(DateTime.Parse(pat.Birthday));
                }
                catch (System.Exception e) { }
                //如果患者未成年，那么将不需要授权
                if (age < 18)
                {
                    retList.Add(pat);
                }
                else
                {
                    //查看关系是否为本人
                    var map = maps.Where(w => w.Pat_ID == pat.Id).FirstOrDefault();
                    if (map != null && map.Ties == 1)
                    {
                        retList.Add(pat);
                    }
                    else
                    {
                        //不为本人判断授权记录
                        var patAuths = auths.FindAll(p => p.PatId == pat.Id);
                        var lastAuth = patAuths.Find(p => p.AuthorizationTime == patAuths.Max(q => q.AuthorizationTime));
                        if (lastAuth == null)
                        {
                            continue;
                        }
                        if (lastAuth.Status == 3 && lastAuth.ExamineDetailIds.Contains(authType.ToString()) && (lastAuth.IsForever || lastAuth.AuthorizationValidity > DateTime.Now))
                        {
                            retList.Add(pat);
                        }
                    }
                }
            }
            return retList;
        }
    }
}
