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;
using SignTokenApi.Model;

namespace SignTokenApi.Repositories
{
    public class Sys_Work_ClassGroup_User_MapRepository : BaseRepository<Sys_Work_ClassGroup_User_Map, string>, ISys_Work_ClassGroup_User_MapRepository
    {
        protected readonly ILogger<BaseRepository<Sys_Work_ClassGroup_User_Map, string>> _logger;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Sys_Work_ClassGroup> _collection_sys_work_classgroup;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Sys_Work_User> _collection_sys_work_user;
        public Sys_Work_ClassGroup_User_MapRepository(
            IOptions<MongodbOptions> settings,
            ILogger<BaseRepository<Sys_Work_ClassGroup_User_Map, string>> logger) : base(settings, logger)
        {
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();  //获取集合
            _collection_sys_work_classgroup = _context.GetCollection<Sys_Work_ClassGroup>();  //获取集合
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_sys_work_user = _context.GetCollection<Sys_Work_User>();  //获取集合
            _logger = logger;
        }

        /// <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 object GetWorkClassGroupUserMarker(string projectid, string usercode, string starttime, string endtime)
        {
            //获取坐席
            var query = from map in _collection.AsQueryable()
                        join workclass in _collection_sys_work_classgroup.AsQueryable() on map.classcode equals workclass.code into workclassinfo
                        join dic_protype in _collection_sys_dictionaryvalue.AsQueryable() on map.usertype equals dic_protype.id into dic_usertypeDefa
                        where map.isdelete == 0
                        select new
                        {
                            map.id,
                            map.projectid,
                            map.classcode,
                            classname = workclassinfo.Count() > 0 ? workclassinfo.First().name : null,
                            classstarttime = workclassinfo.Count() > 0 ? workclassinfo.First().starttime : null,
                            classendtime = workclassinfo.Count() > 0 ? workclassinfo.First().endtime : null,
                            map.usertype,
                            usertypename = dic_usertypeDefa.Count() > 0 ? dic_usertypeDefa.First().name : null,
                            map.userlist,
                            map.date,
                            map.remark
                        };
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(x => x.projectid.Equals(projectid));
            if (!string.IsNullOrEmpty(usercode))
                query = query.Where(x => x.userlist.Contains(usercode));
            if (!string.IsNullOrEmpty(starttime))
                query = query.Where(x => x.date >= DateTime.Parse(starttime + " 00:00:00"));
            if (!string.IsNullOrEmpty(starttime))
                query = query.Where(x => x.date <= DateTime.Parse(endtime + " 23:59:59"));

            var query_user = (from user in _collection_sys_work_user.AsQueryable() where user.isdelete == 0 select user).ToList();
            var list = new List<WorkClassUserMarkerDto>();
            foreach (var item in query.ToList())
            {
                var model = new WorkClassUserMarkerDto();
                var usernamelist = query_user.Where(x => item.userlist.Contains(x.id)).Select(y => y.username).ToList();

                model.id = item.id;
                model.projectid = item.projectid;
                model.date = item.date;
                model.remark = item.remark;
                model.classcode = item.classcode;
                model.classname = item.classname;
                model.classstarttime = item.classstarttime;
                model.classendtime = item.classendtime;
                model.usertype = item.usertype;
                model.usertypename = item.usertypename;
                model.usernamelist = usernamelist;
                model.title = item.usertypename + " " + item.classcode + item.classname + "[" + item.classstarttime + "-" + item.classendtime + "]|" + string.Join(",", usernamelist); //拼接结果（例如：保洁部门 早班[05:00-10:00]|张三 李四）
                list.Add(model);
            }
            return list;
        }       
        
        
        /// <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 object GetUserListByDay(string projectid, string code)
        {
            DateTime nowTime = DateTime.Now;
            DateTime day = DateTime.Parse(nowTime.ToString("yyyy-MM-dd") + " 00:00:00");
            //获取部门（字典） - 默认排班人员角色【RYJS】
            if (string.IsNullOrEmpty(code))
                code = "RYJS";

            //获取部门（字典） - 默认排班人员角色【RYJS】
            var query_dic = from dic in _collection_sys_dictionaryvalue.AsQueryable() where dic.dictionarycode == code select dic;
            //获取班次
            var query_class = from classed in _collection_sys_work_classgroup.AsQueryable() where classed.isdelete == 0 select classed;
            //获取排班列表
            var query_map = from map in _collection.AsQueryable() where map.isdelete == 0 && map.date == day select map;
            //获取用户
            var query_user = from user in _collection_sys_work_user.AsQueryable() where user.isdelete == 0 select user;
            
            if (!string.IsNullOrEmpty(projectid))
            {
                query_class = query_class.Where(x => x.projectid.Equals(projectid));
                query_map = query_map.Where(x => x.projectid.Equals(projectid));
                query_user = query_user.Where(x => x.projectid.Equals(projectid));
            }

            var list = query_dic.ToList().Select(p =>
            {
                var list_c = query_class.ToList().Where(x => x.usertype == p.id).Select(s =>
                {

                    return new
                    {
                        s.code,
                        s.name,
                        s.starttime,
                        s.endtime,
                        userlist = query_map.ToList().Where(x => x.classcode == s.code).Select(x =>
                            new
                            {
                                x.id,
                                user = query_user.ToList().Where(y => x.userlist.Contains(y.id)).Select(y => y.username).ToList()
                            })
                    };
                });
                return new
                {
                    p.id,                   //code
                    p.name,                 //角色
                    list_class = list_c,    //班别list 人员list
                };
            });
            return list;
        }
    }
}
