using System;
using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class MonthReportConfigRepository : ApiConfigRepositoryBase<siger_project_monthreport_config>, IMonthReportConfigRepository
    {
        private readonly ApiConfigDbContext _context;
        public MonthReportConfigRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseGetConfigPagedList> GetConfigPagedList(int page, int pagesize, int projectId)
        {
            var responses = new List<ResponseGetConfigPagedList>();
            var query = _context.siger_project_monthreport_config.Where(q => q.project_id == projectId && q.status == (int) RowState.Valid);

            foreach (var config in query.ToList())
            {
                var userInfo = "";
                if (!string.IsNullOrWhiteSpace(config.user_mids))
                {
                    var userIds = config.user_mids.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
                    var users = _context.siger_project_user.Where(q => userIds.Contains(q.mid.ToStr()) && q.projectid == projectId && q.status == (int) RowState.Valid).ToList();
                    foreach (var projectUser in users)
                    {
                        userInfo += projectUser.name + $"({projectUser.work_email}),";
                    }
                }
                var template = _context.siger_project_monthreport_config_template.Where(f => f.parent_id == config.id);
                responses.Add(new ResponseGetConfigPagedList
                {
                    id = config.id,
                    name = config.name,
                    cycle = (int)config.cycle,
                    first_date = config.first_date.ToString("yyyy-MM-dd"),
                    remark = config.remark,
                    user_info = userInfo.TrimEnd(','),
                     setting = template.Any() ? 1 : 0
                });
            }

            var totalCount = responses.Count;
            var entities = responses.Skip((page - 1) * pagesize).Take(pagesize).ToList();

            return new PagedCollectionResult<ResponseGetConfigPagedList>(entities, totalCount);
        }
    }
}
