using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Data.Tpm;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    internal class PlanReportRepository : TpmRepositoryBase<siger_project_plan_report>, IPlanReportRepository
    {
        private readonly ApiTpmDbContext _context;
        public PlanReportRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<SetLevel> GetSetLevelInfoList(int mode, int projectId)
        {
            var query = from q in _context.siger_project_plan_report_level
                        join u in _context.siger_project_usergroup on q.usergroup_id equals u.id
                        where q.status == (int)RowState.Valid && q.mode == mode && q.project_id == projectId
                        select new SetLevel
                        {
                            level = q.level,
                            usergroup_id = q.usergroup_id,
                            id = q.id,
                            title = u.title
                        };
            return query.AsEnumerable();
        }

        public int SetMessageRepeatTime(string time)
        {
            //修改系统设置
            var config = _context.siger_system_config.FirstOrDefault(q => q.key == SystemConfigKey.MessagePlanTime && q.status == (int)RowState.Valid);
            if (config == null)
            {
                var entity = new siger_system_config
                {
                    key = SystemConfigKey.MessagePlanTime,
                    name = "计划维护消息重复推送时间间隔",
                    value = time,
                    type = "int",
                    description = "计划维护消息重复推送时间间隔"
                };
                _context.siger_system_config.Add(entity);
            }
            else if (config.value != time)
            {
                config.value = time;
                _context.siger_system_config.Update(config);
            }

            return _context.SaveChanges();
        }

        public IEnumerable<int> ListLevelUser(int projectId, int level, int mode)
        {
            var query = from l in _context.siger_project_plan_report_level
                        join u in _context.siger_project_user on l.usergroup_id.ToString() equals u.usergroupid
                        where l.project_id == projectId && l.level == level && l.status == (int)RowState.Valid
                        && l.usergroup_id > 0 && l.mode == mode
                        select u;
            var mids = new List<int>();
            if (query.ToList().Any())
            {
                mids = query.ToList().Select(t => t.mid).ToList();
            }
            return mids;
        }
    }
}
