using AutoMapper;
using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Application.Services
{
    [ApiExplorerSettings(GroupName = "Financial")]
    public class TrialPaymentPriceService : BaseService, ITrialPaymentPriceService
    {
        private readonly IRepository<TrialPaymentPrice> _trialExtRepository;
        private readonly IRepository<Enroll> _enrollRepository;
        private readonly IRepository<Doctor> _doctorRepository;
        private readonly IRepository<CRO> _croRepository;


        private readonly IRepository<Trial> _trialRepository;
        public TrialPaymentPriceService(IRepository<Trial> trialRepository, IRepository<TrialPaymentPrice> trialExtRepository,
            IRepository<Enroll> enrollRepository,
            IRepository<Doctor> doctorRepository,
            IRepository<CRO> croCompanyRepository, IMapper mapper)
        {
            _trialExtRepository = trialExtRepository;
            _croRepository = croCompanyRepository;
            _enrollRepository = enrollRepository;
            _doctorRepository = doctorRepository;

            _trialRepository = trialRepository;
        }

        /// <summary>
        /// 添加或更新项目支付价格信息
        /// </summary>
        [NonDynamicMethod]
        public async Task<IResponseOutput> AddOrUpdateTrialPaymentPrice(TrialPaymentPriceCommand addOrUpdateModel)
        {

            var trialExistedItem = await _trialExtRepository.FirstOrDefaultAsync(u => u.TrialId == addOrUpdateModel.TrialId);
            if (trialExistedItem == null)//insert
            {

                await _trialExtRepository.InsertFromDTOAsync(addOrUpdateModel);

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

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


        [HttpPost]
        public async Task<IResponseOutput> UploadTrialSOW(TrialSOWPathDTO trialSowPath)
        {
            var trialPaymentPrice = await _trialExtRepository.FirstOrDefaultAsync(u => u.TrialId == trialSowPath.TrialId);

            if (trialPaymentPrice == null)//添加
            {
                await _trialExtRepository.InsertFromDTOAsync(trialSowPath);
            }
            else//更新
            {
                await _trialExtRepository.UpdateFromDTOAsync(trialSowPath);
            }

            var success = await _trialExtRepository.SaveChangesAsync();

            return ResponseOutput.Result(success);
        }


        [HttpPost]
        public async Task<IResponseOutput> DeleteTrialSOW(DeleteSowPathDTO trialSowPath)
        {
            var success = await _trialExtRepository.BatchUpdateNoTrackingAsync(u => u.TrialId == trialSowPath.TrialId, s => new TrialPaymentPrice
            {
                SowPath = "",
                SowName = "",
                UpdateTime = DateTime.Now,
                UpdateUserId = _userInfo.Id
            });

            return ResponseOutput.Result(success);
        }

        /// <summary>
        /// 获取项目支付价格信息列表
        /// </summary>
        [HttpPost]
        public async Task<PageOutput<TrialPaymentPriceDTO>> GetTrialPaymentPriceList(TrialPaymentPriceQueryDTO queryParam)
        {
            #region hwt
            //var trialQueryable = from trial in _trialRepository.AsQueryable()
            //                    .WhereIf(queryParam.CroId != null, o => o.CROId == queryParam.CroId)
            //                    .WhereIf(!string.IsNullOrEmpty(queryParam.KeyWord), o => o.TrialCode.Contains(queryParam.KeyWord) || o.Indication.Contains(queryParam.KeyWord))
            //                     join cro in _croRepository.AsQueryable() on trial.CROId equals cro.Id into CRO
            //                     from croInfo in CRO.DefaultIfEmpty()
            //                     join trialExt in _trialExtRepository.Where()
            //                     on trial.Id equals trialExt.TrialId into trialInfo
            //                     from trialExt in trialInfo.DefaultIfEmpty()
            //                     select new TrialPaymentPriceDTO
            //                     {
            //                         //Id = trialExt.Id ,
            //                         IsNewTrial = trialExt.IsNewTrial,
            //                         TrialId = trial.Id,
            //                         TrialCode = trial.TrialCode,
            //                         Cro = croInfo.CROName,
            //                         Indication = trial.Indication,
            //                         Expedited = trial.Expedited,
            //                         TrialAdditional = trialExt.TrialAdditional,
            //                         AdjustmentMultiple = trialExt.AdjustmentMultiple,
            //                         SowName = trialExt.SowName,
            //                         SowPath = trialExt.SowPath,
            //                         CreateTime = trial.CreateTime,
            //                     };

            //var namelist = (from enroll in _enrollRepository.AsQueryable()
            //                join doctor in _doctorRepository.Where() on enroll.DoctorId equals doctor.Id
            //                select new DtoDoctorList()
            //                {
            //                    TrialId = enroll.TrialId,
            //                    Name = doctor.ChineseName
            //                }).ToList().GroupBy(x => new { x.TrialId },
            //(key, lst) => new DtoDoctorList
            //{
            //    TrialId = key.TrialId,
            //    Name = string.Join(',', lst.Select(x => x.Name))
            //});

            //var returndata = trialQueryable.ToPagedList(queryParam.PageIndex, queryParam.PageSize, "CreateTime", queryParam.Asc);

            //returndata.CurrentPageData.ForEach(x => {
            //    x.DoctorsNames = namelist.Where(y => y.TrialId == x.TrialId).Select(y => y.Name).FirstOrDefault() ?? string.Empty;
            //});
            //return returndata;

            #endregion

            #region byzhouhang  方式一

            //var trialQueryable = _trialExtRepository.Where(t => t.Trial.IsDeleted == false)
            //        .WhereIf(queryParam.CroId != null, o => o.Trial.CROId == queryParam.CroId)
            //        .WhereIf(!string.IsNullOrEmpty(queryParam.KeyWord), o => o.Trial.TrialCode.Contains(queryParam.KeyWord) || o.Trial.Indication.Contains(queryParam.KeyWord))
            //        .Select(trialExt => new TrialPaymentPriceDTO()
            //        {
            //            TrialCode = trialExt.Trial.TrialCode,
            //            Cro = trialExt.Trial.CRO.CROName,
            //            Indication = trialExt.Trial.Indication,
            //            Expedited = trialExt.Trial.Expedited,

            //            TrialId = trialExt.TrialId,
            //            IsNewTrial = trialExt.IsNewTrial,
            //            SowName = trialExt.SowName,
            //            SowPath = trialExt.SowPath,
            //            TrialAdditional = trialExt.TrialAdditional,
            //            AdjustmentMultiple = trialExt.AdjustmentMultiple,
            //            CreateTime = trialExt.CreateTime,
            //            DoctorsNames = string.Join(',', trialExt.Trial.EnrollList.Select(t => t.Doctor.ChineseName))
            //        });

            //return trialQueryable.ToPagedList(queryParam.PageIndex, queryParam.PageSize, string.IsNullOrEmpty(queryParam.SortField) ? "CreateTime" : queryParam.SortField, queryParam.Asc);

            #endregion


            #region byzhouhang  方式二

            var trialQueryable2 = _trialExtRepository.Where(t => t.Trial.IsDeleted == false)
                   .WhereIf(queryParam.CroId != null, o => o.Trial.CROId == queryParam.CroId)
                   .WhereIf(!string.IsNullOrEmpty(queryParam.KeyWord), o => o.Trial.TrialCode.Contains(queryParam.KeyWord) || o.Trial.Indication.Contains(queryParam.KeyWord))
                  .ProjectTo<TrialPaymentPriceDTO>(_mapper.ConfigurationProvider);

            return await trialQueryable2.ToPagedListAsync(queryParam.PageIndex, queryParam.PageSize, string.IsNullOrEmpty(queryParam.SortField) ? "CreateTime" : queryParam.SortField, queryParam.Asc);

            #endregion



        }


    }
}
