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

namespace MessageApi.Repositories
{
    public class Sys_NewsRepository : BaseRepository<Sys_News, string>, ISys_NewsRepository
    {
        protected readonly ILogger<BaseRepository<Sys_News, string>> _logger;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Sys_Provinces> _collection_sys_provinces;
        protected readonly IMongoCollection<Sys_City> _collection_sys_city;
        public Sys_NewsRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Sys_News, string>> logger) : base(settings, logger)
        {
            _logger = logger;
            _collection_pro_project_info= _context.GetCollection<Pro_Project_Info>();
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_sys_provinces = _context.GetCollection<Sys_Provinces>();
            _collection_sys_city = _context.GetCollection<Sys_City>();
        }

        /// <summary>
        /// 列表 -- 关联查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="typeid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<SysNewsDto> GetListsByPage(string keyword, string projectid, string typeid, int state, int level, UserAccountInfoModel userinfo,string rolecode, int pageIndex, int pageSize, out int recordCount)
        {
            DateTime dtnow = DateTime.Now;
            var query = from p in _collection.AsQueryable()
                        join pro in _collection_pro_project_info.AsQueryable() on p.projectid equals pro.id into proinfo
                        join dic in _collection_sys_dictionaryvalue.AsQueryable() on p.typeid equals dic.id into dicinfo
                        join city in _collection_sys_city.AsQueryable() on p.city equals city.citycode into cityDefa
                        join provinces in _collection_sys_provinces.AsQueryable() on p.province equals provinces.provincecode into provincesDefa
                        where p.isdelete == 0  //&& (p.endtime == null || p.endtime <= dtnow) //有效期时间 //&& p.state == 0
                        select new SysNewsDto
                        {
                            id = p.id,
                            province = p.province,
                            city = p.city,
                            cityname = cityDefa.Count() > 0 ? cityDefa.First().cityname : "所有市",
                            provincename = provincesDefa.Count() > 0 ? provincesDefa.First().provincename : "所有省",
                            projectid = p.projectid,
                            projectname = proinfo.Count() > 0 ? proinfo.First().project_name : "所有项目",
                            typeid = p.typeid,
                            typename = dicinfo.Count() > 0 ? dicinfo.First().name : "",
                            title = p.title,
                            content = p.content,
                            headimg = p.headimg,
                            headsmallimg = p.headsmallimg,
                            level = p.level,
                            sort = p.sort,
                            state = p.state,
                            publishtype = p.publishtype,
                            timingtime = p.timingtime,
                            endtime = p.endtime,
                            rolecode = p.rolecode,
                            createtime = p.createtime,
                            createuser = p.createuser,
                            createusername = p.createusername
                        };

            #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(typeid))
                query = query.Where(it => it.typeid == typeid);
            if (level != 0)
                query = query.Where(it => it.level == level);
            if (state >= 0)
            {
                //有效期时间/显示不显示
                query = query.Where(it => it.state == state);
                if (state == 2)
                    query = query.Where(it => it.endtime < dtnow);  //已到期
                else
                    query = query.Where(it => (it.endtime == null || it.endtime >= dtnow));  //未到期 和 所有
            }
            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
                //文章 角色权限（空值所有人都可以看）
                if (!string.IsNullOrEmpty(rolecode))
                    query = query.Where(it => it.rolecode == "" || it.rolecode == null || it.rolecode.Contains(rolecode));
            }
            #endregion

            recordCount = query.Count();
            var list = query.OrderByDescending(it => it.createtime).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return list;
        }

        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string id)
        {
            var query = from p in _collection.AsQueryable()
                        join pro in _collection_pro_project_info.AsQueryable() on p.projectid equals pro.id into proinfo
                        join dic in _collection_sys_dictionaryvalue.AsQueryable() on p.typeid equals dic.id into dicinfo
                        join city in _collection_sys_city.AsQueryable() on p.city equals city.citycode into cityDefa
                        join provinces in _collection_sys_provinces.AsQueryable() on p.province equals provinces.provincecode into provincesDefa
                        where p.isdelete == 0 && p.id == id
                        select new
                        {
                            p.id,
                            p.province,
                            p.city,
                            cityname = cityDefa.Count() > 0 ? cityDefa.First().cityname : "所有市",
                            provincename = provincesDefa.Count() > 0 ? provincesDefa.First().provincename : "所有省",
                            p.projectid,
                            projectname = proinfo.Count() > 0 ? proinfo.First().project_name : "所有项目",
                            p.typeid,
                            typename = dicinfo.Count() > 0 ? dicinfo.First().name : "",
                            p.title,
                            p.content,
                            p.headimg,
                            p.headsmallimg,
                            p.files,
                            p.level,
                            p.sort,
                            p.state,
                            p.publishtype,
                            p.timingtime,
                            p.endtime,
                            p.rolecode,
                            p.createtime,
                            createuser = p.createuser,
                            createusername = p.createusername
                        };

            var model = query.FirstOrDefault();
            return model;
        }
    }
}
