using AutoMapper;
using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using System.Linq.Expressions;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Application.Services
{
    [ ApiExplorerSettings(GroupName = "Financial")]
    public class ReviewerPayInfoService : BaseService, IReviewerPayInfoService
    {
        private readonly IRepository<ReviewerPayInformation> _doctorPayInfoRepository;
        private readonly IRepository<Doctor> _doctorRepository;
        private readonly IRepository<RankPrice> _rankPriceRepository;
        private readonly IRepository<Hospital> _hospitalRepository;
        

        public ReviewerPayInfoService(IRepository<Doctor> doctorRepository, IRepository<ReviewerPayInformation> doctorPayInfoRepository,
            IRepository<RankPrice> rankPriceRepository, IRepository<Hospital> hospitalRepository, IMapper mapper)
        {
            _doctorPayInfoRepository = doctorPayInfoRepository;
            _doctorRepository = doctorRepository;
            _rankPriceRepository = rankPriceRepository;
            _hospitalRepository = hospitalRepository;
            
        }
        [NonDynamicMethod]
        public async Task<IResponseOutput> AddOrUpdateReviewerPayInfo(ReviewerPayInfoCommand addOrUpdateModel, Guid userId)
        {
            var success = false;
            var doctorPayInfoExistedItem = await _doctorPayInfoRepository.FirstOrDefaultAsync(u => u.DoctorId == addOrUpdateModel.DoctorId);
            if (doctorPayInfoExistedItem == null)//insert
            {

                await _doctorPayInfoRepository.InsertFromDTOAsync(addOrUpdateModel);
              
            }
            else//update
            {
                await _doctorPayInfoRepository.UpdateFromDTOAsync(addOrUpdateModel);

            }
            success = await _doctorPayInfoRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }

        /// <summary>
        /// 获取医生支付信息列表
        /// </summary>
        [HttpPost]
        public async Task<PageOutput<DoctorPayInfoQueryListDTO>> GetReviewerPayInfoList(DoctorPaymentInfoQueryDTO queryParam)
        {


            var doctorQueryable = from doctor in _doctorRepository.AsQueryable()
                                  .WhereIf(queryParam.HospitalId != null, o => o.HospitalId == queryParam.HospitalId)
                                  .WhereIf(!string.IsNullOrEmpty(queryParam.SearchName),
                                  u => u.ChineseName.Contains(queryParam.SearchName)|| (u.LastName+ u.FirstName).Contains(queryParam.SearchName))
                                  join hospitalItem in _hospitalRepository.AsQueryable() on doctor.HospitalId equals hospitalItem.Id into gt
                                  from hospital in gt.DefaultIfEmpty()
                                  join trialPayInfo in _doctorPayInfoRepository.Where()
                                  on doctor.Id equals trialPayInfo.DoctorId into payInfo
                                  from doctorPayInfo in payInfo.DefaultIfEmpty()
                                  join rankPrice in _rankPriceRepository.Where()
                                  on doctorPayInfo.RankId equals rankPrice.Id into rankPriceInfo
                                  from rankPrice in rankPriceInfo.DefaultIfEmpty()
                                  select new DoctorPayInfoQueryListDTO
                                  {
                                      //Id = doctorPayInfo.Id,
                                      DoctorId = doctor.Id,
                                      Code = doctor.ReviewerCode,
                                      LastName = doctor.LastName,
                                      FirstName = doctor.FirstName,
                                      ChineseName = doctor.ChineseName,
                                      Phone = doctor.Phone,
                                      DoctorNameInBank = doctorPayInfo.DoctorNameInBank,
                                      IDCard = doctorPayInfo.IDCard,
                                      BankCardNumber = doctorPayInfo.BankCardNumber,
                                      BankName = doctorPayInfo.BankName,
                                      RankId = doctorPayInfo.RankId,
                                      RankName = rankPrice.RankName,
                                      Additional = doctorPayInfo.Additional,
                                      Hospital = hospital.HospitalName,
                                      CreateTime = doctor.CreateTime
                                  };

            return await doctorQueryable.ToPagedListAsync(queryParam.PageIndex, queryParam.PageSize, "Code", queryParam.Asc);
          
            
        }


        /// <summary>
        /// 根据医生Id获取支付信息
        /// </summary>
        /// <param name="doctorId">医生Id</param>
        /// <returns></returns>
        [HttpGet("{doctorId:guid}")]
        public async Task<DoctorPayInfoQueryListDTO> GetReviewerPayInfo(Guid doctorId)
        {
            var doctorQueryable = from doctor in _doctorRepository.Where(u => u.Id == doctorId)
                                  join trialPayInfo in _doctorPayInfoRepository.Where()
                                  on doctor.Id equals trialPayInfo.DoctorId into payInfo
                                  from doctorPayInfo in payInfo.DefaultIfEmpty()
                                  join rankPrice in _rankPriceRepository.Where()
                                  on doctorPayInfo.RankId equals rankPrice.Id into rankPriceInfo
                                  from rankPrice in rankPriceInfo.DefaultIfEmpty()
                                  select new DoctorPayInfoQueryListDTO
                                  {
                                      //Id = doctorPayInfo.Id,
                                      DoctorId = doctor.Id,
                                      Code = doctor.ReviewerCode,
                                      LastName = doctor.LastName,
                                      FirstName = doctor.FirstName,
                                      ChineseName = doctor.ChineseName,
                                      Phone = doctor.Phone,
                                      DoctorNameInBank = doctorPayInfo.DoctorNameInBank,
                                      IDCard = doctorPayInfo.IDCard,
                                      BankCardNumber = doctorPayInfo.BankCardNumber,
                                      BankName = doctorPayInfo.BankName,
                                      RankId = doctorPayInfo.RankId,
                                      RankName = rankPrice.RankName,
                                      Additional = doctorPayInfo.Additional,
                                      CreateTime = doctor.CreateTime
                                  };

            return (await doctorQueryable.FirstOrDefaultAsync()).IfNullThrowException();
        }

        /// <summary>
        /// 根据rankId 获取ReviewerId，用于当Rank的单价信息改变时，触发费用计算
        /// </summary>
        /// <param name="rankId"></param>
        /// <returns></returns>
        public async Task<List<Guid>> GetReviewerIdByRankId(Guid rankId)
        {
            return await _doctorPayInfoRepository.Where(u => u.RankId == rankId).Select(u => u.DoctorId).ToListAsync();
        }
    }
}
