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

namespace EquipmentApi.Repositories
{
    public class Pro_StudyMaterials_InfoRepository: BaseRepository<Pro_StudyMaterials_Info,string>, IPro_StudyMaterials_InfoRepository
    {
        protected readonly ILogger<BaseRepository<Pro_StudyMaterials_Info, string>> _logger;
        protected readonly IMongoCollection<Sys_SystemConfig> _collection_sys_systemconfig;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        public Pro_StudyMaterials_InfoRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Pro_StudyMaterials_Info, string>> logger) : base(settings, logger)
        {
            _collection_sys_systemconfig = _context.GetCollection<Sys_SystemConfig>();//获取集合
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();//获取集合
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
            _logger = logger;
        }

        /// <summary>
        /// 获取楼层列表 分页 - Linq 关联查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetListsByPage(string keyword, string stime, string etime, string projectid, UserAccountInfoModel userinfo, int pageIndex, int pageSize, out int recordCount)
        {
            var config = from sysconfig in _collection_sys_systemconfig.AsQueryable() where sysconfig.isdelete == false && sysconfig.paramcode.Equals("AppStudyMaterialsUrl") select sysconfig;
            var configvalue = config != null&& config.Count()>0 ? config.First().paramvalue : null;
            //关联查询
            var query =
                from stud in _collection.AsQueryable()
                join account in _collection_sys_user_account.AsQueryable() on stud.createby equals account.usercode into accountDefa
                join pro in _collection_pro_project_info.AsQueryable() on stud.projectid equals pro.id into proDefa
                where stud.isdelete == 0
                orderby stud.createtime descending
                select new
                {
                    id = stud.id,
                    title = stud.title,
                    projectid = stud.projectid,
                    projectname = proDefa != null && proDefa.Count() > 0 ? proDefa.First().project_name : "所有项目",
                    url = configvalue,
                    content = stud.content,
                    userhead_img = accountDefa != null && accountDefa.Count() > 0 ? accountDefa.First().head_img : null,   //发布人图像
                    studymaterfile = stud.studymaterfile,   //附件
                    createby = stud.createby,
                    createtime = stud.createtime,
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.title.Contains(keyword) || it.content.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid || it.projectid == null);
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime + " 00:00:00"));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime + " 23:59:59"));
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion
            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }        

        /// <summary>
        /// 获取列表 分页 - Linq 关联查询
        /// </summary>
        /// <returns></returns>
        public IEnumerable<object> GetAppLists(string keyword, string stime, string etime, string projectid, UserAccountInfoModel userinfo)
        {
            var config = from sysconfig in _collection_sys_systemconfig.AsQueryable() where sysconfig.isdelete == false && sysconfig.paramcode.Equals("AppStudyMaterialsUrl") select sysconfig;
            var configvalue = config != null ? config.First().paramvalue : null;
            //关联查询
            var query =
                from stud in _collection.AsQueryable()
                join account in _collection_sys_user_account.AsQueryable() on stud.createby equals account.usercode into accountDefa
                where stud.isdelete == 0
                orderby stud.createtime descending
                select new
                {
                    id = stud.id,
                    title = stud.title,
                    projectid = stud.projectid,
                    url = configvalue,
                    content = stud.content,
                    userhead_img = accountDefa != null && accountDefa.Count() > 0 ? accountDefa.First().head_img : null,   //发布人图像
                    studymaterfile = stud.studymaterfile,   //附件
                    createby = stud.createby,
                    createtime = stud.createtime,
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.title.Contains(keyword) || it.content.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid || it.projectid == null);
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime + " 00:00:00"));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime + " 23:59:59"));
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion
            var list = query;
            return list;
        }

        /// <summary>
        /// 获取设备运行详情 by id Linq 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string id)
        {
            try
            {
                var config = from sysconfig in _collection_sys_systemconfig.AsQueryable() where sysconfig.isdelete == false && sysconfig.paramcode.Equals("AppStudyMaterialsUrl") select sysconfig;
                var configvalue = config != null ? config.First().paramvalue : null;
                //关联查询
                var query =
                     from stud in _collection.AsQueryable()
                     join account in _collection_sys_user_account.AsQueryable() on stud.createby equals account.usercode into accountDefa
                     where stud.isdelete == 0 && stud.id == id
                     orderby stud.createtime descending
                    select new
                    {
                        id = stud.id,
                        title = stud.title,
                        url = configvalue,
                        content = stud.content,
                        userhead_img = accountDefa != null && accountDefa.Count()>0 ? accountDefa.First().head_img : null,   //发布人图像
                        studymaterfile = stud.studymaterfile,   //附件
                        createby = stud.createby,
                        createtime = stud.createtime,
                    };
                var model = query.FirstOrDefault();
                if (model != null)
                {
                    return model;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }



    }
}
