using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;

namespace IRaCIS.Core.Application
{
    [ApiExplorerSettings(GroupName = "Trial")]
    public class PersonalWorkstation : BaseService
    {
        private readonly IRepository<Trial> _trialRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<TrialDocument> _trialDocumentRepository;
        private readonly IRepository<SystemDocument> _systemDocumentRepository;
        private readonly IRepository<SystemNotice> _systemNoticeRepository;

        public PersonalWorkstation(IRepository<Trial> trialRepository, IRepository<TrialUser> trialUserRepository, IRepository<TrialDocument> trialDocumentRepository, 
            IRepository<SystemDocument> systemDocumentRepository,IRepository<SystemNotice> systemNoticeRepository)
        {
            _trialRepository = trialRepository;
            _trialUserRepository = trialUserRepository;
            _trialDocumentRepository = trialDocumentRepository;
            _systemDocumentRepository = systemDocumentRepository;
            _systemNoticeRepository = systemNoticeRepository;
        }

        /// <summary>
        /// 个人面板 统计值
        /// </summary>
        /// <returns></returns>
        public async Task<PersonalStataDTO> GetBasicStat()
        {

            return new PersonalStataDTO()
            {
                //正参与的数量
                TrialCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? await _trialRepository.CountAsync()
                    : await _trialUserRepository.Where(t => t.UserId == _userInfo.Id).CountAsync(),

                DeletedCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? await _trialRepository.AsQueryable(true).CountAsync(t => t.IsDeleted)
                    : await _trialUserRepository.AsQueryable(true).Where(t => t.UserId == _userInfo.Id && t.IsDeleted)
                        .CountAsync(),


                TotalNeedSignTrialDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0                    
                    : await _trialDocumentRepository.AsQueryable(true).Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialStopped)
                        .Where(t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                        .Where(t => t.IsDeleted == false || (t.IsDeleted == true && t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null)))

                        .SelectMany(t => t.NeedConfirmedUserTypeList)
                        .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId),

                HaveSignedTrialDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    //废除了 已经签署了也要算进去
                    : await _trialDocumentRepository.AsQueryable(true).Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialStopped)
                        .Where( t => t.Trial.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                        .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                        .SelectMany(t => t.TrialDocConfirmedUserList)
                        .CountAsync(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime !=null),

                TotalNeedSignSystemDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    : await _systemDocumentRepository
                        .Where(t => t.IsDeleted == false || (t.IsDeleted == true && t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime !=null)))
                        .SelectMany(t => t.NeedConfirmedUserTypeList)
                        .CountAsync(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId),


                HaveSignedSystemDocCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0
                    : await _systemDocumentRepository
                        .Where(t => t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId))
                        .SelectMany(t => t.SystemDocConfirmedUserList)
                        .CountAsync(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime != null),

                TotalApprovalRequiredCount= 
                    _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM ?
                    _trialRepository.Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id)).SelectMany(t=>t.TrialSiteSurveyList).Where(t => t.State == TrialSiteSurveyEnum.SPMApproved).Count()
                    : _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM|| _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM
                    ?  _trialRepository.Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id)).SelectMany(t => t.TrialSiteSurveyList).Where(t => t.State == TrialSiteSurveyEnum.CRCSubmitted).Count()
                    :0,


                    TotalSystemNoticeCount= _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0:await _systemNoticeRepository.Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum== Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished)
                     
                    .CountAsync(),

                    NeedReadSystemNoticeCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                    ? 0 : await _systemNoticeRepository.Where(t => t.NoticeUserTypeList.Any(t => t.UserTypeId == _userInfo.UserTypeId) && t.NoticeStateEnum == Domain.Share.Management.SystemNotice_NoticeStateEnum.HavePublished
                     && !t.NoticeUserReadList.Any(t=>t.CreateUserId==_userInfo.Id))
                    .Where(t => t.EndDate == null || t.EndDate != null && t.EndDate > DateTime.Now)
                    .CountAsync(),


            };

        }


        /// <summary>
        /// Site 调研 每个项目 需要处理的审批统计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialSiteSurveyStat>> GetSiteSurveyApprovalList(TrialSiteSurveyStatQuery query)
        {


            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM ||
                _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM)
            {
                return await _trialRepository
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.SPMApproved).Count() > 0)
                    .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM, c => c.TrialSiteSurveyList.Where(t => t.State == TrialSiteSurveyEnum.CRCSubmitted).Count() > 0)
                    .ProjectTo<TrialSiteSurveyStat>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id })
                    .OrderByDescending(t => t.ApprovalRequiredCount).ToPagedListAsync(query.PageIndex, query.PageSize, query.SortField, query.Asc);
            }

            else
            {
                return new PageOutput<TrialSiteSurveyStat>(query.PageIndex, query.PageSize, 0, new List<TrialSiteSurveyStat>());

            }

        }


        /// <summary>
        ///  需要签署文件数量  系统级别的在第一行
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DocSignStat>> GetTrialDocStatList(TrialSiteSurveyStatQuery query)
        {
            if (_userInfo.IsAdmin)
            {
                return new PageOutput<DocSignStat>(query.PageIndex, query.PageSize, 0, new List<DocSignStat>());
            }
            else
            {
                var trialDocStat = await _trialRepository/*.AsQueryable(true)*/.Where(t=>t.TrialStatusStr != StaticData.TrialState.TrialStopped)
                    .Where(t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id))
                    .WhereIf(!_userInfo.IsAdmin, c => c.TrialDocumentList.Where(t => t.IsDeleted == false && t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId) && !t.TrialDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id && t.ConfirmTime!=null))
                            .Count() > 0)
                    .ProjectTo<DocSignStat>(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id, userTypeId = _userInfo.UserTypeId })
                    .OrderByDescending(t => t.WaitSignCount)
                    .ToPagedListAsync(query.PageIndex, query.PageSize , query.SortField, query.Asc);

                //var sysDocStat = new DocSignStat()
                //{
                //    IsSystemDoc = true,
                //    WaitSignCount = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin
                //        ? 0
                //        : await _systemDocumentRepository
                //            .Where(t =>
                //                t.NeedConfirmedUserTypeList.Any(t => t.NeedConfirmUserTypeId == _userInfo.UserTypeId) &&
                //                !t.SystemDocConfirmedUserList.Any(t => t.ConfirmUserId == _userInfo.Id))
                //            .CountAsync()
                //};
                //var list = trialDocStat.CurrentPageData.ToList();
                //list.Insert(0, sysDocStat);
                //trialDocStat.CurrentPageData = list;
                //trialDocStat.TotalCount++;


                return trialDocStat;
            }

           

        }






    }
}
