using MadRunFabric.Common;
using MadRunFabric.Common.Options;
using MadRunFabric.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SignTokenApi.IRepositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace SignTokenApi.Repositories
{
    public class Sys_Work_UserGroupRepository : BaseRepository<Sys_Work_UserGroup, string>, ISys_Work_UserGroupRepository
    {
        protected readonly ILogger<BaseRepository<Sys_Work_UserGroup, string>> _logger;
        protected readonly IMongoCollection<Sys_Work_Group> _collection_sys_work_group;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        protected readonly IMongoCollection<Sys_Role_Info> _collection_role_info;
        public Sys_Work_UserGroupRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Sys_Work_UserGroup, string>> logger) : base(settings, logger)
        {
            _logger = logger;
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
            _collection_role_info = _context.GetCollection<Sys_Role_Info>();
            _collection_sys_work_group= _context.GetCollection<Sys_Work_Group>();
        }

        /// <summary>
        /// 获取排班人员
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public IEnumerable<object> GetUserList(string projectid, string keyword)
        {
            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.head_img,
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null,
                               p.idcardno,
                               p.remark
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG" || p.rolecode == "YWZG");
            if (!string.IsNullOrEmpty(keyword))
                wxlist.Where(p => p.usercode.Contains(keyword) || p.username.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                wxlist = wxlist.Where(p => p.projectid == projectid);
            return wxlist;
        }

        /// <summary>
        /// 获取排班详情
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="usercode"></param>
        /// <param name="groupcode"></param>
        /// <returns></returns>
        public IEnumerable<object> GetUserGroupList(string projectid, string startdate, string enddate, string usercode, string groupcode)
        {
            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.projectlist,
                               p.head_img,
                               p.usercode,
                               p.username,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG" || p.rolecode == "YWZG");
            if (!string.IsNullOrEmpty(projectid))
                wxlist = wxlist.Where(p => p.projectlist.Contains(projectid));
            if (!string.IsNullOrEmpty(usercode))
                wxlist = wxlist.Where(p => p.usercode == usercode);

            var datenow = DateTime.Now;
            var startdatetime = datenow;
            var enddatetime = datenow;

            if (!string.IsNullOrEmpty(startdate) && !string.IsNullOrEmpty(enddate))
            {
                startdatetime = DateTime.Parse(startdate);
                enddatetime = DateTime.Parse(enddate);
            }
            else
            {
                startdatetime = datenow.AddDays(1 - datenow.Day);  //本月月初  
                enddatetime = startdatetime.AddMonths(1).AddDays(-1);  //本月月末  
            }

            var listApp = new List<FilterDefinition<Sys_Work_UserGroup>>();
            listApp.Add(Builders<Sys_Work_UserGroup>.Filter.Eq("isdelete", 0));
            listApp.Add(Builders<Sys_Work_UserGroup>.Filter.Gte("date", startdatetime.ToString("yyyy-MM-dd")));
            listApp.Add(Builders<Sys_Work_UserGroup>.Filter.Lte("date", enddatetime.ToString("yyyy-MM-dd")));
            if (!string.IsNullOrEmpty(usercode))
                listApp.Add(Builders<Sys_Work_UserGroup>.Filter.Eq("usercode", usercode));
            if (!string.IsNullOrEmpty(groupcode))
                listApp.Add(Builders<Sys_Work_UserGroup>.Filter.Eq("groupcode", groupcode));

            var filter = Builders<Sys_Work_UserGroup>.Filter.And(listApp);
            var grouplist = _collection_sys_work_group.AsQueryable().ToList();
            var lists = _collection.Find(filter).ToList();

            var days = enddatetime.Subtract(startdatetime).Days + 1;

            var list = wxlist.ToList().Select(p =>
            {
                string[] dates = new string[days];
                string[] groups = new string[days];
                for (int i = 0; i < days; i++)
                {
                    dates[i] = startdatetime.AddDays(i).ToString("yyyy-MM-dd");
                    groupcode = lists.Where(q => q.usercode == p.usercode && q.date == dates[i]).FirstOrDefault()?.groupcode ?? "";
                    //if (p.projectlist != null && p.projectlist.Count > 0)
                    //{
                    //    groups[i] = grouplist.Where(q => q.projectid == p.projectlist[0] && q.code == groupcode).FirstOrDefault()?.name ?? "";
                    //}
                    //else
                    //{
                    //    groups[i] = "";
                    //}

                    groups[i] = grouplist.Where(q => q.code == groupcode).FirstOrDefault()?.name ?? "";
                }
                return new
                {
                    p.head_img,
                    p.usercode,
                    p.username,
                    dates,
                    groups
                };
            }).ToList();

            return list;
        }

        /// <summary>
        /// 获取用户排班详情
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public object GetUserGroupInfo(string usercode, string date)
        {
            var query = from p in _collection.AsQueryable()
                        join r in _collection_sys_work_group.AsQueryable() on p.groupcode equals r.code into groupinfo
                        join u in _collection_sys_user_account.AsQueryable() on p.usercode equals u.usercode into userinfo
                        where p.isdelete == 0 && p.usercode == usercode && p.date == date
                        select new
                        {
                            p.usercode,
                            p.groupcode,
                            p.date,
                            username = userinfo != null && userinfo.Count() > 0 ? userinfo.First().username : null,
                            headimg = userinfo != null && userinfo.Count() > 0 ? userinfo.First().head_img : null,
                            groupname = groupinfo != null && groupinfo.Count() > 0 ? groupinfo.First().name : null,
                            starttime = groupinfo != null && groupinfo.Count() > 0 ? groupinfo.First().starttime : null,
                            endtime = groupinfo != null && groupinfo.Count() > 0 ? groupinfo.First().endtime : null
                        };

            var model = query.FirstOrDefault();
            if (model != null)
            {
                return model;
            }
            return null;
        }


    
    }
}
