using ASHermed.SinoInterface.Api.ContractModel.App.Entity;
using ASHermed.SinoInterface.Api.IRepository.App;
using ASHermed.SinoInterface.Entity.Test;
using ASHermed.SinoInterface.Repository.MySql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel.App;
using Org.BouncyCastle.Bcpg;

namespace ASHermed.SinoInterface.Api.MySqlRepository.App
{
    public class PubAuthorizationRepository : BaseRepositoryToASHermed_SinoInterface<Pub_AuthorizationDto>, IPubAuthorizationRepository
    {
        public List<Pub_Authorization_Detail> GetAuthorizationDetail()
        {
            var sql = @" select * from pub_authorization_detail Where IsDelete = false ";
            return Query<Pub_Authorization_Detail>(sql).ToList();
        }

        public List<Pub_AuthorizationDto> GetPubAuthorizationList(int patId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where PatId = @PatId and IsDelete = false ";
            return Query<Pub_AuthorizationDto>(sql, new { PatId = patId }).ToList();
        }

        public int InsertAuthorization(Pub_AuthorizationDto model)
        {
            var sql = @" INSERT INTO `pub_authorization`(`UserId`, `PatId`, `Status`, `CreateTime`, `ApplyDetailIds`, `ExamineDetailIds`, `AuthorizationValidity`, `AuthorizationMethod`, `IsDelete`,IsForever,AuthorizationTime,AuthorizationImg,AuthorizationPdf,Source,IsOneSelf) VALUES (@UserId, @PatId, @Status, @CreateTime, @ApplyDetailIds, @ExamineDetailIds, @AuthorizationValidity, @AuthorizationMethod, @IsDelete,@IsForever,@AuthorizationTime,@AuthorizationImg,@AuthorizationPdf,@Source,@IsOneSelf) ";
            return Insert(sql, model);
        }

        public Pub_AuthorizationDto GetAuthorization(int userid, int patId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @UserId And PatId = @PatId order by CreateTime desc limit 1 ";
            return Query<Pub_AuthorizationDto>(sql, new { UserId = userid, PatId = patId }).FirstOrDefault();
        }

        public Pub_AuthorizationDto GetUserAuthorizationByPat(int userid, int patId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @UserId and PatId=@PatId order by AuthorizationTime desc ,CreateTime desc limit 1 ";
            return Query<Pub_AuthorizationDto>(sql, new { UserId = userid, PatId = patId }).FirstOrDefault();
        }

        public Pub_AuthorizationDto GetUserAuthorizationByPatStatus(int userid, int patId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @UserId and PatId=@PatId and `Status` = 1 order by CreateTime desc limit 1 ";
            return Query<Pub_AuthorizationDto>(sql, new { UserId = userid, PatId = patId }).FirstOrDefault();
        }

        public Pub_AuthorizationDto GetAuthorizationForId(int id)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and Id = @Id  limit 1 ";
            return Query<Pub_AuthorizationDto>(sql, new { Id = id }).FirstOrDefault();
        }

        public Pub_AuthorizationDto GetAllAuthorizationForId(int id)
        {
            var sql = @" select * from pub_authorization where isdelete = false and Id = @Id  limit 1 ";
            return Query<Pub_AuthorizationDto>(sql, new { Id = id }).FirstOrDefault();
        }

        public int UpdateAuthorization(int id, int status, DateTime authorizationTime, string examineDetailIds, DateTime authorizationValidity, bool isForever, string authorizationPdf, string authorizationImg)
        {
            var sql = @" Update `pub_authorization` set `Status`=@Status,AuthorizationTime=@AuthorizationTime,ExamineDetailIds=@ExamineDetailIds,AuthorizationValidity = @AuthorizationValidity,IsForever=@IsForever,AuthorizationPdf=@AuthorizationPdf,AuthorizationImg=@AuthorizationImg  Where Id = @Id ";
            return Execute(sql, new { Status = status, AuthorizationTime = authorizationTime, ExamineDetailIds = examineDetailIds, AuthorizationValidity = authorizationValidity, IsForever = isForever, AuthorizationPdf = authorizationPdf, AuthorizationImg = authorizationImg, Id = id });
        }

        public int UpdateAuthorizationStatus(int id, int status)
        {
            var sql = @" Update `pub_authorization` set `Status`=@Status,AuthorizationTime=@AuthorizationTime Where Id = @Id ";
            return Execute(sql, new { Status = status, Id = id, AuthorizationTime = DateTime.Now });
        }

        public int InvalidAuthorization(int userid, int patid)
        {
            var sql = @" Update `pub_authorization` set IsDelete = 1 Where UserId = @UserId and PatId=@PatId and IsDelete = 0 ";
            return Execute(sql, new { UserId = userid, PatId = patid });
        }

        public int RemoveUserAuthorization(int userid, int patId)
        {
            var sql = @" Update `pub_authorization` set `Status`=@Status,isdelete=1  Where UserId = @UserId and PatId=@PatId and `Status` in (1,3)";
            return Execute(sql, new { Status = 5, UserId = userid, PatId = patId });
        }

        /// <summary>
        /// 删除就诊人之后，所有的授权记录改为已删除
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="patId"></param>
        /// <returns></returns>
        public async Task<int> RemoveUserAuthorizationAsync(int userId, int patId)
        {
            var sql = @" Update `pub_authorization` set isdelete=1  Where UserId = @UserId and PatId=@PatId ";
            return await ExecuteAsync(sql, new { UserId = userId, PatId = patId });
        }

        /// <summary>
        /// 删除”本人“的授权
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="patId"></param>
        /// <returns></returns> 
        public async Task<int> RemoveOneSelfAuthorizationAsync(int userId, int patId)
        {
            var sql = @" Update `pub_authorization` set isdelete=1  Where UserId = @UserId and PatId=@PatId and IsOneSelf=true ";
            return await ExecuteAsync(sql, new { UserId = userId, PatId = patId });
        }

        public List<Pub_AuthorizationDto> GetUserAuthorization(int userId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @UserId  ";
            return Query<Pub_AuthorizationDto>(sql, new { UserId = userId }).ToList();
        }

        public List<Pub_AuthorizationDto> GetAuthorizationUserPat(int patid)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source ,IsOneSelf from pub_authorization Where isdelete = false and PatId=@PatId And (Status = 3 or Status = 1) and IsOneSelf=false ";
            return Query<Pub_AuthorizationDto>(sql, new { PatId = patid }).ToList();
        }

        public List<Pub_AuthorizationDto> GetUserAuthorizationsByPats(int userId, List<int> patIds)
        {
            if (patIds == null || patIds.Count == 0)
            {
                return new List<Pub_AuthorizationDto>();
            }

            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @userId and PatId in @patIds ";

            var parms = new Dictionary<string, object>
            {
                { "@userId", userId },
                { "@patIds", patIds }
            };

            return Query<Pub_AuthorizationDto>(sql, parms).ToList();
        }

        public async Task<List<Pub_AuthorizationDto>> GetUserAuthorizationsByPatsAsync(int userId, List<int> patIds)
        {
            if (patIds == null || patIds.Count == 0)
            {
                return new List<Pub_AuthorizationDto>();
            }

            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId = @userId and PatId in @patIds ";

            var parms = new Dictionary<string, object>
            {
                { "@userId", userId },
                { "@patIds", patIds }
            };

            return (await QueryAsync<Pub_AuthorizationDto>(sql, parms)).ToList();
        }

        public List<Pub_AuthorizationDto> GetUserAuthorizationsByPats(List<int> userId, int patId)
        {
            var sql = @" select Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source from pub_authorization where isdelete = false and UserId IN @userId and PatId = @patId ";

            var parms = new Dictionary<string, object>
            {
                { "@userId", userId },
                { "@patId", patId }
            };

            return Query<Pub_AuthorizationDto>(sql, parms).ToList();
        }

        public bool RelieveAuthorization(int id)
        {
            var sql = @" Update pub_authorization Set IsDelete = 1 Where Id = @Id ";
            return Execute(sql, new { Id = id }) > 0 ? true : false;
        }

        public List<Pub_AuthorizationDto> GetAllAuthorizationExpired()
        {
            var sql = @"SELECT Id,UserId,PatId,`Status`,CreateTime,ApplyDetailIds,ExamineDetailIds,AuthorizationValidity,AuthorizationMethod,IsDelete,IsForever,AuthorizationTime,Source FROM pub_authorization where isdelete = false AND `Status` = 1 AND TIMESTAMPDIFF( MINUTE, now( ), CreateTime ) <= -30";
            return Query<Pub_AuthorizationDto>(sql).ToList();
        }

        public bool UpdateStatus(List<int> id, int status)
        {
            var sql = @" Update pub_authorization Set `Status`=@Status Where Id IN @Id ";
            return Execute(sql, new { Id = id, Status = status }) > 0 ? true : false;
        }

        public (int,int) GetUserIdPatIdByAuthorizationId(int id)
        {
            var sql = "select UserId,PatId from pub_authorization where Id=@id  ";
            var result= Query<Pub_AuthorizationDto>(sql, new { id = id }).FirstOrDefault();

            return (result?.UserId ?? default, result?.PatId ?? default);
        }

    }
}
