using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;

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

        public IPagedCollectionResult<Shift> GetShifts(int sectionid,int projectid,int page, int pagesize)
        {
            var query = _context.siger_project_shift.Where(q => q.status == (int) RowState.Valid && q.projectid == projectid);
            var querylist = from q in query
                join pu in _context.siger_project_user on q.create_mid equals pu.mid into puser
                from pu in puser.DefaultIfEmpty()
                join se in _context.siger_project_section on q.sectionid equals se.id into sec
                from se in sec.DefaultIfEmpty()
                select new Shift
                {
                    title = q.title,
                    name = pu != null ? pu.name : "",
                    sectionName = se != null ? se.title : "",
                    sectionid = se != null ? se.id : 0,
                    shiftName = q.title,
                    start_time = q.start_time.ToString(),
                    end_time = q.end_time.ToString(),
                    shiftID = q.id,
                    description = q.description,
                    create_time = q.create_time.ToString(),
                };

            Expression<Func<Shift, bool>> sectionidExpression = q => true;
            if (sectionid != 0)
            {
                sectionidExpression = q => q.sectionid == sectionid;
            }
            var predicate = sectionidExpression;

            var totalCount = querylist.Count(predicate);
            var entities = querylist.Where(predicate).OrderByDescending(q => q.create_time).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

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

        public ShiftInfo GetShiftInfo(int id)
        {
            var query = _context.siger_project_shift.Where(q => q.status == (int)RowState.Valid && q.id == id);
            var querylist = from q in query
                join pu in _context.siger_project_user on q.create_mid equals pu.mid into puser
                from pu in puser.DefaultIfEmpty()
                join se in _context.siger_project_section on q.sectionid equals se.id into sec
                from se in sec.DefaultIfEmpty()
                select new ShiftInfo
                {
                    name = pu != null ? pu.name : "",
                    sectionName = se != null ? se.title : "",
                    sectionid = se != null ? se.id : 0,
                    shiftName = q.title,
                    start_time = q.start_time,
                    end_time = q.end_time,
                    description = q.description,
                    title = q.title
                };

            return querylist.FirstOrDefault();
        }

        public IEnumerable<string> GetSectionShiftUserLists(int sectionid, int shiftid, int departmentid, int projectid)
        {
            var userNames = new List<string>();
            var station = _context.siger_project_station.Where(q =>
                q.sectionid == sectionid && q.shiftid == shiftid && q.status == (int) RowState.Valid);
            if (!station.Any())
            {
                return userNames;
            }

            var mids = station.Select(q => q.dutymid);
            var usergroupids = _context.siger_project_user.Where(q =>
                    q.status == (int) RowState.Valid && q.projectid == projectid
                                                     && q.sectionid == departmentid && mids.Contains(q.mid))
                .Select(m => m.usergroupid);

            if (!usergroupids.Any())
            {
                return userNames;
            }

            var groupIds = usergroupids.Select(s => int.Parse(s)).ToList();
            userNames = _context.siger_project_usergroup.Where(q =>
                q.status == (int) RowState.Valid && q.projectid == projectid
                                                 && groupIds.Contains(q.id)).Select(m => m.title).ToList();

            return userNames;
        }

        public Dictionary<int, string> GetCurrentShit(List<int> wprkGroupShift, int userid)
        {
            var dict = new Dictionary<int, string>();
            foreach (var key in wprkGroupShift)
            {
                var shit = _context.siger_project_shift.FirstOrDefault(f => f.id == key); //_sigerProjectShift.Get(f => f.id == key);
                if (shit == null)
                {
                    continue;
                }
                //var now = DateTime.Now;
                //var shitStart = DateTime.Now.Date.AddSeconds(shit.start_time);
                //var shitEnd = DateTime.Now.Date.AddSeconds(shit.end_time);
                //if (now >= shitStart && now <= shitEnd)
                //{
                dict.Add(shit.id, shit.title);
                break;
                //}
            }
            return dict;
        }
    }
}
