protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                loadStates();

                using (Lib.Repositories.PeriodRepository repository = new PeriodRepository(this.ActiveUser))
                {
                    var period = repository.getLastPublishedPeriod();

                    if (period != null && this.ActiveUser != null && this.ActiveUser.UserTypeEnum != Lib.Enumerations.UserType.Site)
                    {
                        lblTitle.Text = String.Format("{0} - {1} até {2}", period.Name, period.InitialDate.ToString("dd/MM/yyyy"), period.FinalDate.ToString("dd/MM/yyyy"));

                        //Verifica se existe questionário anterior
                        if (period.BaseForms != null && period.BaseForms.Count == 1)
                        {
                            hdLastPeriodId.Value = Commons.SecurityUtils.criptografar(period.Id.ToString());
                            phLastForm.Visible = true;
                        }
                    }
                    else
                    {
                        lblTitle.Text = "Resultado";
                    }
                }
            }
        }
        /// <summary>
        /// Inicializa as propriedades.
        /// </summary>
        public TestSupport()
        {
            _createdBaseForm = new List<BaseForm>();
            _createdPeriods = new List<Period>();
            _createdResponseForm = new List<ResponseForm>();
            _createdUser = new List<User>();
            _createdSubmit = new List<Submit>();

            //Cria o usuário Master
            createMasterUser();

            BaseFormRepository = new BaseFormRepository(activeUser);
            PeriodRepository = new PeriodRepository(activeUser);
            ResponseFormRepository = new ResponseFormRepository(activeUser);
            UserRepository = new UserRepository(activeUser);
            SubmitRepository = new SubmitRepository(activeUser);
        }
        /// <summary>
        /// Busca todos as entidades do ultimo periodo publicado e que possuam o ultimo submit como accepted
        /// </summary>
        /// <returns></returns>
        public List<ResponseForm> getRanking()
        {
            try
            {
                Lib.Entities.Period period = null;
                List<Lib.Entities.ResponseForm> ranking = new List<ResponseForm>();

                using (Lib.Repositories.PeriodRepository repository = new PeriodRepository(this.ActiveUser))
                {
                    period = repository.getLastPublishedPeriod();
                }

                if (period == null)
                {
                    return new List<ResponseForm>();
                }

                var baseFormsIds = period.BaseForms.Select(g => g.Id).ToList();

                //Buscando uma determinada entidade e seus relacionamentos
                var responseForms = context.ResponseForms
                    .Include("BaseForm")
                    .Include("Answers")
                    .Include("City")
                    .Include("City.State")
                    .Include("Submits")
                    .Include("User")
                    .Where(f => baseFormsIds.Contains(f.BaseFormId))
                    .ToList();

                responseForms.ForEach(responseForm =>
                {
                    responseForm.Submits = context.Submits.Where(r => r.ResponseFormId == responseForm.Id).ToList();
                    var submit = responseForm.Submits.OrderBy(f => f.Id).LastOrDefault();

                    if (submit != null)
                    {
                        if (submit.StatusEnum == Enumerations.SubmitStatus.Approved)
                        {
                            ranking.Add(responseForm);
                        }
                    }
                });

                ranking.ForEach(responseForm =>
                {
                    responseForm.Reviews = context.Reviews.Where(r => r.ResponseFormId == responseForm.Id).ToList();

                    responseForm.Reviews.ForEach(r =>
                    {
                        r.User = context.Users.Where(f => f.Id == r.UserId).FirstOrDefault();
                    });

                    //carrega os baseblocks
                    responseForm.BaseForm.BaseBlocks = context.BaseBlocks.Where(bb => bb.BaseFormId == responseForm.BaseFormId).ToList();

                    responseForm.BaseForm.BaseBlocks.ForEach(bb =>
                    {
                        //carrega os basesubblocks
                        bb.BaseSubBlocks = context.BaseSubBlocks.Where(f => f.BaseBlockId == bb.Id).ToList();

                        bb.BaseSubBlocks.ForEach(bsb =>
                        {
                            //carrega os basequestions
                            bsb.BaseQuestions = context.BaseQuestions.Where(bq => bq.BaseSubBlockId == bsb.Id).ToList();
                        });
                    });

                    responseForm.Answers = responseForm.Answers.OrderBy(ans => ans.BaseQuestion.BaseSubBlock.Index).ToList();
                });

                return ranking;
            }
            catch (Exception ex)
            {
                Log.ErrorLog.saveError("Lib.Repositories.ResponseFormRepository.getRanking", ex);
                throw new Exception("Lib.Repositories.ResponseFormRepository.getRanking - " + ex.Message, ex);
            }
        }
        public List<ResponseForm> getResponseFormsByUserIdAndPeriodId(long userId, long periodId)
        {
            try
            {
                Entities.Period period = null;
                using (Lib.Repositories.PeriodRepository rep = new PeriodRepository(this.ActiveUser))
                {
                    period = rep.getInstanceById(periodId);
                }

                if (period == null)
                {
                    return null;
                }

                List<long> baseFormsIds = null;
                baseFormsIds = period.BaseForms.Select(f => f.Id).ToList();

                //Buscando uma determinada entidade e seus relacionamentos
                var responseForms = context.ResponseForms
                    .Include("BaseForm")
                    .Include("BaseForm.Period")
                    .Include("Answers")
                    .Include("City")
                    .Include("City.State")
                    .Include("User")
                    .Include("Submits")
                    .Where(b => b.UserId == userId && baseFormsIds.Contains(b.BaseFormId)).ToList();
                //

                responseForms.ForEach(responseForm =>
                {
                    responseForm.Reviews = context.Reviews.Where(r => r.ResponseFormId == responseForm.Id).ToList();

                    responseForm.Reviews.ForEach(r =>
                    {
                        r.User = context.Users.Where(f => f.Id == r.UserId).FirstOrDefault();
                    });

                    //carrega os baseblocks
                    responseForm.BaseForm.BaseBlocks = context.BaseBlocks.Where(bb => bb.BaseFormId == responseForm.BaseFormId).ToList();

                    responseForm.BaseForm.BaseBlocks.ForEach(bb =>
                    {
                        //carrega os basesubblocks
                        bb.BaseSubBlocks = context.BaseSubBlocks.Where(f => f.BaseBlockId == bb.Id).ToList();

                        bb.BaseSubBlocks.ForEach(bsb =>
                        {
                            //carrega os basequestions
                            bsb.BaseQuestions = context.BaseQuestions.Where(bq => bq.BaseSubBlockId == bsb.Id).ToList();
                        });
                    });

                    responseForm.Answers = responseForm.Answers.OrderBy(ans => ans.BaseQuestion.BaseSubBlock.Index).ToList();
                });

                return responseForms;
            }
            catch (Exception ex)
            {
                Log.ErrorLog.saveError("Lib.Repositories.ResponseFormRepository.getAll", ex);
                throw new Exception("Lib.Repositories.ResponseFormRepository.getAll - " + ex.Message, ex);
            }
        }
        private Enumerations.RequestStatus requestAlreadyApproved(long userId, long periodId, long cityId, Enumerations.RequestType requestType)
        {
            //Busca o último período
            using (Lib.Repositories.PeriodRepository ctxPeriod = new PeriodRepository(this.ActiveUser))
            {
                var publishedPeriod = ctxPeriod.getLastPublishedPeriod();

                if (publishedPeriod != null)
                {
                    var responsable = context.Groups.Where(g => g.CityId == cityId && g.ResponsableId == userId && g.PeriodId == publishedPeriod.Id).FirstOrDefault();

                    //Verifica se a solicitação é de responsável ou colaborador
                    if (requestType == Enumerations.RequestType.RESPONSABLE)
                    {

                        if (responsable != null)
                        {
                            //No período anterior, está entidade era responsável pela cidade solicitada

                            //Verifica se já existe alguma solicitacao para esse municipio.
                            if (userCanBeResponsableForCity(cityId, userId, periodId))
                                return Enumerations.RequestStatus.APPROVED;
                            else
                                return Enumerations.RequestStatus.WAITING_APPROVE;
                        }
                        else
                        {
                            //No período anterior, está entidade não era responsável pela cidade solicitada
                            return Enumerations.RequestStatus.WAITING_APPROVE;
                        }
                    }
                    else if (requestType == Enumerations.RequestType.COLLABORATOR)
                    {
                        if (responsable != null)
                        {
                            //Entidade era responsável e agora quer ser colaboradora
                            if (userCanBeCollaboratorForCity(cityId, userId, periodId))
                                return Enumerations.RequestStatus.APPROVED;
                            else
                                return Enumerations.RequestStatus.WAITING_APPROVE;
                        }
                        else
                        {
                            //Verifica se a entidade era colaboradora no período anterior.
                            var request = context.Groups.Include("Collaborators").Where(g => g.CityId == cityId && g.PeriodId == publishedPeriod.Id).FirstOrDefault();

                            if (request != null)
                            {
                                //Verifica se o grupo do período anterior, tem o coloborador solicitado
                                if (request.Collaborators.Where(c => c.Id == userId).Count() == 1)
                                {
                                    //A entidade era uma colaboradora e continuará sendo nesse período.
                                    if (userCanBeCollaboratorForCity(cityId, userId, periodId))
                                        return Enumerations.RequestStatus.APPROVED;
                                    else
                                        return Enumerations.RequestStatus.WAITING_APPROVE;
                                }
                                else
                                {
                                    //Entidade não era colaboradora desse município
                                    return Enumerations.RequestStatus.WAITING_APPROVE;
                                }

                            }
                            else
                            {
                                //Cidade não tem responsável
                                return Enumerations.RequestStatus.WAITING_APPROVE;
                            }
                        }
                    }
                    else
                    {
                        //Nenhum solicitação valida (Colaborador ou Responsável)
                        return Enumerations.RequestStatus.WAITING_APPROVE;
                    }

                }
                else
                {
                    //Nenhum período publicado
                    return Enumerations.RequestStatus.WAITING_APPROVE;
                }

            }
        }