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_nSecInfo> repository;
        private readonly SqlSugarClient dbClient;
        public ZXService(ISqlSugarRepository<YB_nSecInfo> 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_nSecInfo>().Where(x => x.Status == AdStatus.Run);
            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 => SqlFunc.Subqueryable<YB_nSecInfoAppId>().Where(e => e.AppId == param.appid && e.InfoId == x.Id).Any());
            }
            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 != AdType.Text).Select(x => x.Id).ToList();
                        return dbClient.Queryable<YB_nSecInfoContent>().Where(x => ids.Contains(x.InfoId)).ToList();
                    });
                    if (it.Type != AdType.Text)
                    {
                        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(Guid id)
        {
            var data = await dbClient.Queryable<YB_nSecInfo>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            //返回内容
            var contentdata = await dbClient.Queryable<YB_nSecInfoContent>()
                .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 == StatusType.Enabled);
            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 == StatusType.Enabled).Where(x => x.BusienssId == 0).ToListAsync();
            }
            return new ResultInfo(ResultState.SUCCESS, "success", list);
        }

        /// <summary>
        /// 轮播图列表,最多获取5条,平台两条,客户三条
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ParamReturnData<BannerApiListModel>> GetBannerListAsync(BannerListC2SDto param)
        {
            var temquery = dbClient.Queryable<YB_Banner>().Where(x => x.Status == AdStatus.Run && x.AppId == param.AppId);
            // 查询家庭成员的最新测量记录
            var lastresult = await dbClient.Queryable<YB_nResult>()
                .Where(x => SqlFunc.Subqueryable<YB_nUserResult>().Where(e => e.Id == x.Id && e.FamilyId == param.FamilyId).Any())
                .OrderBy(x => x.CreateTime, OrderByType.Desc)
                .Select(x => new YB_nResult
                {
                    EquId = x.EquId,
                    BusinessId = x.BusinessId
                }).FirstAsync();
            var lastequid = lastresult != null ? lastresult.EquId : 0;
            if (lastequid > 0 && await dbClient.Queryable<YB_BannerEqu>().AnyAsync(x => x.EquId == lastequid))
            {
                temquery = temquery.Where(x => SqlFunc.Subqueryable<YB_BannerEqu>().Where(e => e.EquId == lastequid && e.BannerId == x.Id).Any());
            }
            var list = new List<BannerApiListModel>();

            //首先获取两条平台轮播图
            var plist = await temquery.Clone()
                .Where(x => x.PositionType == BannerPositionType.Platform)
                .OrderBy(x => x.Createtime, OrderByType.Desc)
                .Take(2)
                .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 == AdType.URL || x.Type == AdType.MINIAPP).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;
                 })
                .ToListAsync();
            if (plist.Count > 0)
            {
                list.AddRange(plist);
            }
            var clist = await temquery.Clone()
                .Where(x => x.PositionType == BannerPositionType.Business)
                .OrderBy(x => x.Createtime, OrderByType.Desc)
                .Take(3)
                .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 == AdType.URL || x.Type == AdType.MINIAPP).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;
                 })
                .ToListAsync();
            if (clist.Count > 0)
            {
                list.AddRange(clist);
            }
            return new ParamReturnData<BannerApiListModel>
            {
                page = 1,
                items = list,
                totalnum = list.Count(),
                pagesize = 10
            };
        }
        /// <summary>
        /// 轮播图详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> BannerDetailAsync(int id)
        {
            var data = await dbClient.Queryable<YB_Banner>()
                .Select(x => new YB_Banner
                {
                    Createtime = x.Createtime
                })
                .FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            //返回内容
            var contentdata = await dbClient.Queryable<YB_BannerContent>()
                .Select(x => new YB_BannerContent
                {
                    Content = x.Content
                })
                .FirstAsync(x => x.BannerId == id);
            return new ResultInfo(ResultState.SUCCESS, "success",new BannerDetaimS2CDto
            {
                Content = contentdata?.Content,
                CreateTime = data.Createtime.ToYearDate()
            });
        }
        /// <summary>
        /// 更新点击数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> UpdateClickCountAsync(Guid id)
        {
            await dbClient.Updateable<YB_nSecInfo>().SetColumns(x => new YB_nSecInfo
            {
                ClickCount = x.ClickCount + 1
            }).Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "success");
        }
    }
}
