using Furion.DependencyInjection;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.NApi.Application.ZXInfo
{
    /// <summary>
    /// 科普资讯、轮播图、开屏广告管理
    /// </summary>
    public class ZXService : BaseService, IZXService, ITransient
    {
        private readonly ISqlSugarRepository<YB_SecInfo> repository;
        private readonly SqlSugarClient dbClient;
        public ZXService(ISqlSugarRepository<YB_SecInfo> sqlSugarRepository)

        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }

        /// <summary>
        /// 科普资讯列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ParamReturnData<SecInfoApiListModel>> GetInfoListAsync(ParamQuery param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<YB_SecInfo>();
            if (authInfo != null && (authInfo.UserId == 8 || authInfo.UserId == 7))
            {
                temquery = temquery.Where(x => x.Id == 22 || x.Id == 23 || x.Status == 1);
            }
            else
            {
                temquery.Where(x =>x.Status == 1);
            }
            if (!string.IsNullOrEmpty(param.keyword))
            {
                int tagid = param.keyword.ToInt();
                if (tagid > 0)
                {
                    temquery = temquery.Where(x => x.TagId == tagid);
                }
            }
            if (!string.IsNullOrEmpty(param.appid))
            {
                temquery = temquery.Where(x => x.AppId == param.appid);
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                .Select(x => new SecInfoApiListModel
                {
                    Id = x.Id,
                    Title = x.Title,
                    HeadImg = x.HeadImg,
                    time = x.CreateTime,
                    ClickCount = x.ClickCount,
                    Type = x.Type
                })
                .Mapper((it, cache) =>
                {
                    if (!string.IsNullOrEmpty(it.HeadImg))
                    {
                        it.HeadImg = $"{CDNURL}{it.HeadImg}";
                    }
                    it.CreateTime = it.time.ToYearDate();
                    var allcontent = cache.Get(list => {
                        var ids = list.Where(x => x.Type > 1).Select(x=>x.Id).ToList();
                        return dbClient.Queryable<YB_SecInfoContent>().Where(x => ids.Contains(x.InfoId)).ToList();
                    });
                    if(it.Type != 1)
                    {
                        var content = allcontent.FirstOrDefault(x => x.InfoId == it.Id);
                        it.Content = content != null ? content.Content : "";
                    }
                })
                 .ToPageListAsync(param.page, param.pagesize, totalnum);
            return new ParamReturnData<SecInfoApiListModel>
            {
                page = param.page,
                items = query,
                totalnum = totalnum,
                pagesize = param.pagesize
            };
        }
        /// <summary>
        /// 科普资讯详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> InfoDetailAsync(int id)
        {
            var data = await dbClient.Queryable<YB_SecInfo>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            //返回内容
            var contentdata = await dbClient.Queryable<YB_SecInfoContent>()
                .FirstAsync(x => x.InfoId == data.Id);
            return new ResultInfo(ResultState.SUCCESS, "success", new AdDetailModel
            {
                Content = contentdata?.Content,
                Title = data.Title,
                CreateTime = data.CreateTime.ToYearDate()
            });
        }

        /// <summary>
        /// 类型列表
        /// </summary>
        /// <param name="appid">小程序appid</param>
        /// <returns></returns>
        public async Task<ResultInfo> GetInfoTagListAsync(string appid="")
        {
            var tempquery = dbClient.Queryable<YB_SecInfoType>().Where(x => x.Status == 1);
            if (!string.IsNullOrEmpty(appid))
            {
                tempquery = tempquery.Where(x => SqlFunc.Subqueryable<YB_BusinessOffice>().Where(e => e.BusinessId == x.BusienssId && e.AppId == appid).Any());
            }
            var list = await tempquery
                .OrderBy(x => x.SortCode, OrderByType.Asc).ToListAsync();
            if(list.Count == 0)
            {
                list = await dbClient.Queryable<YB_SecInfoType>().Where(x => x.Status == 1).Where(x => x.BusienssId == 0).ToListAsync();
            }
            return new ResultInfo(ResultState.SUCCESS, "success", list);
        }

        /// <summary>
        /// 轮播图列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ParamReturnData<BannerApiListModel>> GetBannerListAsync(ParamQuery param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<YB_Banner>();
            if(authInfo !=null && (authInfo.UserId == 8 || authInfo.UserId == 7))
            {
                temquery = temquery.Where(x => x.Id == 3 || x.Status == 1);
            }
            else
            {
                temquery = temquery.Where(x =>x.Status == 1);
            }
            if (!string.IsNullOrEmpty(param.appid))
            {
                temquery = temquery.Where(x => x.AppId == param.appid);
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                .Select(x => new BannerApiListModel
                {
                    Id = x.Id,
                    HeadImg = x.HeadImg,
                    Type = x.Type
                })
                .Mapper((it, cache) =>
                {
                    it.HeadImg = $"{CDNURL}{it.HeadImg}";
                    var allcontent = cache.Get(list => {
                        var ids = list.Where(x => x.Type == 2 || x.Type == 3).Select(x => x.Id).ToList();
                        return dbClient.Queryable<YB_BannerContent>().Where(x => ids.Contains(x.BannerId)).ToList();
                    });
                    it.content = allcontent.FirstOrDefault(x => x.BannerId == it.Id)?.Content;
                })
                 .ToPageListAsync(param.page, param.pagesize, totalnum);
            return new ParamReturnData<BannerApiListModel>
            {
                page = param.page,
                items = query,
                totalnum = totalnum,
                pagesize = param.pagesize
            };
        }
        /// <summary>
        /// 轮播图详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> BannerDetailAsync(int id)
        {
            var data = await dbClient.Queryable<YB_Banner>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            //返回内容
            var contentdata = await dbClient.Queryable<YB_BannerContent>().FirstAsync(x => x.BannerId == data.Id);
            return new ResultInfo(ResultState.SUCCESS, "success", contentdata);
        }
        /// <summary>
        /// 更新点击数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> UpdateClickCountAsync(int id)
        {
            await dbClient.Updateable<YB_SecInfo>().SetColumns(x => new YB_SecInfo { 
                ClickCount = x.ClickCount+1
            }).Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "success");
        }
    }
}
