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

namespace SignTokenApi.Repositories
{
    public class Sys_ClassGroup_User_MapRepository : BaseRepository<Sys_ClassGroup_User_Map, string>, ISys_ClassGroup_User_MapRepository
    {
        protected readonly ILogger<BaseRepository<Sys_ClassGroup_User_Map, string>> _logger;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        protected readonly IMongoCollection<Sys_Role_Info> _collection_role_info;
        protected readonly IMongoCollection<Sys_ClassGroup> _collection_sys_classgroup;
        protected readonly IMongoCollection<Distri_Workorder_Plan> _collection_distri_workorder_plan;
        public Sys_ClassGroup_User_MapRepository(
            IOptions<MongodbOptions> settings, 
            ILogger<BaseRepository<Sys_ClassGroup_User_Map, 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_classgroup = _context.GetCollection<Sys_ClassGroup>();
            _collection_distri_workorder_plan = _context.GetCollection<Distri_Workorder_Plan>();
        }     

        /// <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> GetClassGroupUserList(string projectid, string listday,int card, UserInfoModel userinfo)
        {
            //, 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.id,
                               p.head_img,
                               p.usercode,
                               p.username,
                               p.projectlist,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            userlist = userlist.Where(p => p.rolecode == "SSY_DTG" || p.rolecode == "SSY_PSG");
            if (!string.IsNullOrEmpty(projectid))
                userlist = userlist.Where(p => p.projectlist.Contains(projectid));
            //if (!string.IsNullOrEmpty(usercode))
            //    userlist = userlist.Where(p => p.usercode == usercode);

            // 如果card>0，说明是打卡调用，显示是当前用户打卡
            if (card > 0)
                userlist = userlist.Where(p => p.usercode == userinfo.usercode);
            #region 获取排班信息
            ////时间条件处理，默认当天
            //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);
            //}

            var classUserlists = from p in _collection.AsQueryable()
                                     where p.isdelete == 0
                                     select new
                                     {
                                         p.id,
                                         p.projectid,
                                         p.usercode,
                                         //p.groupcode,
                                         p.date,
                                         p.isstatus,
                                         p.classgroupList,
                                         p.isjoin,
                                         p.distri_planList,
                                         p.isdelete
                                     };
            if (!string.IsNullOrEmpty(projectid))
                classUserlists = classUserlists.Where(x => x.projectid == projectid);
            //if (!string.IsNullOrEmpty(usercode))
            //    classUserlists = classUserlists.Where(x => x.usercode == usercode);
            //if (!string.IsNullOrEmpty(groupcode))
            //    classUserlists = classUserlists.Where(x => string.Join(",", x.classgroupList.ToList().Select(p => p.code)).Contains(groupcode));
            if (userinfo.isallproject == 0)
                classUserlists = classUserlists.Where(it => userinfo.projectlist.Contains(it.projectid));

            //由于 x.date 需要处理，所以 ToList
            var classUserlist = classUserlists.ToList();
            //if (!string.IsNullOrEmpty(startdatetime.ToString()))
            //    classUserlist = classUserlist.Where(x => Convert.ToDateTime(x.date + " 00:00:00") >= Convert.ToDateTime(startdatetime.ToString("yyyy-MM-dd") + " 00:00:00")).ToList();
            //if (!string.IsNullOrEmpty(enddatetime.ToString()))
            //    classUserlist = classUserlist.Where(x => Convert.ToDateTime(x.date + " 00:00:00") <= Convert.ToDateTime(enddatetime.ToString("yyyy-MM-dd") + " 23:59:59")).ToList();
            //获取最后一个点击日期
            var dayend = "";
            if (!string.IsNullOrWhiteSpace(listday))
            {
                //var typearr = listday.Split(',');
                string[] typearr = listday.Split(',');
                dayend = typearr[typearr.Length - 1];
            }
            else
            {
                dayend = DateTime.Now.ToString("yyyy-MM-dd");
            }
            classUserlist = classUserlist.Where(x => x.date == dayend).ToList();
            #endregion

            //班别
            var classlist = _collection_sys_classgroup.AsQueryable().ToList();
            classlist = classlist.Where(x => x.isdelete == 0).ToList();
            //配送计划
            DateTime dt_Plan = DateTime.Now;
            var distriPlanList = _collection_distri_workorder_plan.AsQueryable().Where(x=>x.isdelete == 0 && x.planstate == 0 && x.enddate >= dt_Plan).ToList();    // && x.startdate <= dt_Plan不用了，在计划结束之前排班就行

            var list = userlist.ToList().Select(p =>
            {
                #region 排班结果 model
                //变量去
                string classuserid = null;
                int isstatus_class = 0;                                 //出勤状态(0未排版 1正常 2休息 3请假)
                bool isjoin_class = false;                              //是否参与计划
                var groupList_class = new List<ClassGroupList>();       //绑定班别
                var distri_planList_class = new List<DistriPlanList>(); //绑定计划
                var modelClassUser = classUserlist.FirstOrDefault(cu => cu.usercode == p.usercode);
                if (modelClassUser != null)
                {
                    classuserid = modelClassUser.id;
                    isstatus_class = modelClassUser.isstatus;
                    groupList_class = modelClassUser.classgroupList;
                    isjoin_class = modelClassUser.isjoin;
                    distri_planList_class = modelClassUser.distri_planList;
                }
                #endregion

                #region 出勤状态列表
                var isstatusList = EnumberHelper.EnumToList<EnumClassGroupUserIsStatus>().Select(s => {
                    return new
                    {
                        s.EnumName,
                        s.EnumValue,
                        ischeck = s.EnumValue == isstatus_class ? true : false     //出勤状态选中
                    };
                });
                #endregion

                #region 班别 - 排班
                var classlist_Class = classlist.Select(c => 
                {
                    var roleList = new List<ClassGroupRoleList>();
                    bool ischeck_class = false;
                    foreach (var item in c.roleList)
                    {
                        if (groupList_class != null && groupList_class.Count > 0)
                        {
                            var modelClass = groupList_class.FirstOrDefault(x => x.code == c.code);
                            if (modelClass != null)
                            {
                                ischeck_class = true;
                                //判断是否选中
                                var model_role = new ClassGroupRoleList();
                                if (modelClass.roleList != null && modelClass.roleList.Count > 0)
                                {
                                    var model_rolebycode = modelClass.roleList.FirstOrDefault(x => x.rolecode == item.rolecode);
                                    if (model_rolebycode != null)
                                    {
                                        item.ischeck = false;
                                        if (model_rolebycode.ischeck == true)
                                            item.ischeck = true;
                                    }
                                }
                            }
                        }
                        roleList.Add(item);
                    }
                    return new
                    {
                        c.code,
                        c.name,
                        ischeck = ischeck_class,     //班别是否选中
                        roleList
                        //c.starttime,
                        //c.endtime,
                        //c.remark
                    };
                });
                #endregion

                #region 配送计划列表
                var distriPlanList_Plan = distriPlanList.Select(d =>
                {
                    bool ischeck_plan = false;
                    if (groupList_class != null)
                    {
                        if (distri_planList_class != null && distri_planList_class.Count > 0)
                        {
                            var modelPlan = distri_planList_class.FirstOrDefault(x => x.planid == d.id);
                            if (modelPlan != null)
                                ischeck_plan = true;
                        }
                    }
                    return new
                    {
                        d.id,
                        d.planname,
                        ischeck = ischeck_plan    //计划是否选中
                    };
                });
                #endregion

                return new
                {
                    p.id,
                    p.usercode,
                    p.username,
                    p.head_img,
                    classuserid,            //排班id
                    isstatus_class,         //排班状态
                    isstatusList,           //排班状态列表
                    classlist_Class,        //班别结果列表
                    isjoin_class,           //是否参与计划
                    distriPlanList_Plan,    //配送计划结果
                };
            }).ToList();

            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 GetClassGroupMarker(string projectid, string usercode, UserInfoModel userinfo)
        {
            //获取坐席
            var markerlist = from map in _collection.AsQueryable()
                           //join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where map.isdelete == 0
                             select new
                           {
                               map.id,
                               map.date,
                               map.usercode,
                               map.isstatus
                           };

            //var list = markerlist.ToList();
            if (!string.IsNullOrEmpty(usercode))
                markerlist = markerlist.Where(x => x.usercode == usercode);
            
            List<string> dateList_normal = new List<string>();
            List<string> dateList_rest = new List<string>();
            List<string> dateList_eave = new List<string>();
            foreach (var item in markerlist)
            {
                if (item.isstatus == 1)
                {
                    dateList_normal.Add(item.date);
                }
                else if (item.isstatus == 2)
                {
                    dateList_rest.Add(item.date);
                }
                else if (item.isstatus == 3)
                {
                    dateList_eave.Add(item.date);
                }
            }
            var obj = new
            {
                dateList_normal = dateList_normal,
                dateList_rest = dateList_rest,
                dateList_eave = dateList_eave
            };
            return obj;
        }

        /// <summary>
        /// 获取班次时间段上班的人员 - 今天
        /// </summary>
        /// <param name="today"></param>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        public object GetWorkUserListByDay(UserInfoModel userinfo)
        {
            DateTime dtnow = DateTime.Now;
            string nowDay = dtnow.ToString("yyyy-MM-dd");

            //获取坐席
            var listmapuser = from map in _collection.AsQueryable()
                           //join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                            where map.isdelete == 0 && map.isstatus == (int)EnumClassGroupUserIsStatus.正常
                            select new
                            {
                                map.id,
                                map.projectid,
                                map.date,
                                map.usercode,
                                map.isstatus,
                                map.classgroupList
                            };

            //班别列表
            var listClass = (from map in _collection_sys_classgroup.AsQueryable()
                             where map.isdelete == 0
                             select map).ToList();
            listClass = listClass.ToList().Where(x => DateTime.Parse(nowDay + " " + x.starttime) <= dtnow && DateTime.Parse(nowDay + " " + x.endtime) >= dtnow).ToList();
            
            if (userinfo.isallproject == 0)
                listmapuser = listmapuser.Where(it => userinfo.projectlist.Contains(it.projectid));
            if (!string.IsNullOrEmpty(nowDay))
                listmapuser = listmapuser.Where(x => x.date == nowDay);

            #region 获取用户符合条件的用户
            //var listUser = (await _sys_user_accountrepository.Get(x => x.delete_flag == false && x.lock_flag == false)).ToList();
            List<string> listUserCode = new List<string>();
            foreach (var item in listmapuser)
            {
                //获取班别code                      
                var list_code = new List<string> { };   //班别code
                var list_r = item.classgroupList.ToList();
                foreach (var item_r in list_r)
                {
                    if (item_r.roleList != null && item_r.roleList.Count > 0)
                    {
                        //角色 - 班别
                        var mode_r = item_r.roleList.Where(x => x.ischeck == true && x.rolecode == "SSY_PSG").ToList();    // && x.rolecode == rolecode
                        if (mode_r != null && mode_r.Count > 0)
                            list_code.Add(item_r.code);
                    }
                }

                if (list_code != null && list_code.Count > 0)
                {
                    listClass = listClass.Where(x => list_code.Contains(x.code)).ToList();
                    foreach (var item_Class in listClass)
                    {
                        listUserCode.Add(item.usercode);
                    }
                }
            }
            #endregion
            if (listUserCode.Contains(userinfo.usercode))
                listUserCode.Remove(userinfo.usercode);
            return listUserCode;
        }

    }
}
