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

namespace YBDevice.Application
{
    /// <summary>
    /// 广告管理
    /// </summary>
    public class AdService : IAdService, ITransient
    {
        private readonly ISqlSugarRepository<YB_Banner> repository;
        private readonly SqlSugarClient dbClient;
        private readonly OperatorModel currentUser;

        public AdService(ISqlSugarRepository<YB_Banner> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            currentUser = BaseInfoService.GetUserInfo();
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BannerSubmitModel> DetailAsync(int id)
        {
            var info = await dbClient.Queryable<YB_Banner>().Select(x => new BannerSubmitModel
            {
                Name = x.Name,
                HeadImg = x.HeadImg,
                Type = x.Type,
                Id = x.Id,
                AppId = x.AppId
            }).Where(x => x.Id == id).FirstAsync();
            var content = await dbClient.Queryable<YB_BannerContent>().Where(x => x.BannerId == id).FirstAsync();
            info.content = content?.Content;
            return info;
        }

        /// <summary>
        /// 获取轮播图、开屏广告列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<BannerListModel>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<YB_Banner>();
            if (param.queryParam != null && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    temquery = temquery.Where(conModels);
                }
            }
            if (currentUser.AccountType != AccountType.platform)
            {
                temquery = temquery.Where(x => x.BusinessId == currentUser.BusinessId);
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                .Select(x => new BannerListModel
                {
                    Id = x.Id,
                    BusinessId = x.BusinessId,
                    Createtime = x.Createtime,
                    ClickCount = x.ClickCount,
                    HeadImg = x.HeadImg,
                    Name = x.Name,
                    StartTime = x.StartTime,
                    Status = x.Status,
                    StatusRemark = x.StatusRemark,
                    EndTime = x.EndTime,
                    Type = x.Type,
                    AppId = x.AppId
                })
                 .Mapper((it, cache) =>
                 {
                     var allapp = cache.Get(list =>
                     {
                         var ids = list.Select(x => x.AppId).ToList();
                         return dbClient.Queryable<YB_OfficlaAccount>().Where(x => ids.Contains(x.authorizer_appid)).ToList();
                     });
                     it.AppId = allapp.FirstOrDefault(x => x.authorizer_appid == it.AppId)?.nick_name;
                 })
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<BannerListModel>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 获取轮播图设备列表
        /// </summary>
        /// <param name="orderid">轮播图ID</param>
        /// <param name="page">页码</param>
        /// <param name="pagesize">每页显示的数量</param>
        /// <param name="code">设备序列号</param>
        /// <param name="type">设备类型</param>
        /// <returns></returns>
        public async Task<PageParms<BannerEquDto>> GetOrderEquListAsync(int orderid, int page, int pagesize, string code, int type)
        {
            RefAsync<int> totalnum = 0;
            var tempquery = dbClient.Queryable<YB_Device>();
            if (currentUser.AccountType != AccountType.platform)
            {
                tempquery = tempquery.Where(x => x.BusinessId == currentUser.BusinessId || x.BindBusinessId == currentUser.BusinessId);
            }
            if (!string.IsNullOrEmpty(code))
            {
                tempquery = tempquery.Where(x => x.FacCode.Contains(code));
            }
            if (type > 0)
            {
                tempquery = tempquery.Where(x => x.Type == type);
            }
            List<YB_BannerEqu> bindlist = new List<YB_BannerEqu>();
            if (orderid > 0)
            {
                bindlist = await dbClient.Queryable<YB_BannerEqu>().Where(x => x.BannerId == orderid).ToListAsync();
            }
            var query = await tempquery.OrderBy(x => x.CreateTime, OrderByType.Desc)
                .Select(x => new BannerEquDto
                {
                    equid = x.Id,
                    facecode = x.FacCode,
                    name = x.Name
                })
                .Mapper((it, cache) =>
                {
                    if (bindlist != null && bindlist.Count == 1 && bindlist.FirstOrDefault().EquId == 0)
                    {
                        it.isall = true;
                    }
                    if (bindlist == null || bindlist.Count == 0)
                    {
                        it.ischecked = false;
                    }
                    if (
                    (bindlist != null && bindlist.Count == 1 && bindlist.FirstOrDefault().EquId == 0)
                    || (bindlist != null && bindlist.FirstOrDefault(x => x.EquId == it.equid) != null)
                    )
                    {
                        it.ischecked = true;
                    }
                })
                .ToPageListAsync(page, pagesize, totalnum);
            return new PageParms<BannerEquDto>
            {
                page = page,
                Items = query,
                totalnum = totalnum,
                limit = pagesize
            };
        }

        /// <summary>
        /// 状态修改
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="status">状态</param>
        /// <param name="remark">状态描述</param>
        /// <returns></returns>
        public async Task<ResultInfo> SetStatusAsync(int id, AdStatus status, string remark)
        {
            if (!await dbClient.Queryable<YB_Banner>().AnyAsync(x => x.Id == id))
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            //更新状态
            await dbClient.Updateable<YB_Banner>().SetColumns(x => new YB_Banner
            {
                Status = status
            }).Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "状态更新成功");
        }

        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(BannerSubmitModel model)
        {
            if (model.Id > 0)
            {
                await dbClient.Updateable<YB_Banner>().SetColumns(x => new YB_Banner
                {
                    HeadImg = model.HeadImg,
                    Name = model.Name,
                    Type = model.Type,
                    AppId = model.AppId
                }).Where(x => x.Id == model.Id).ExecuteCommandAsync();

                await dbClient.Updateable<YB_BannerContent>().SetColumns(x => new YB_BannerContent
                {
                    Content = model.content
                }).Where(x => x.BannerId == model.Id).ExecuteCommandAsync();
                if (model.equids != null && model.equids.Count > 0)
                {
                    List<YB_BannerEqu> list = new List<YB_BannerEqu>();
                    foreach (var item in model.equids)
                    {
                        list.Add(new YB_BannerEqu
                        {
                            EquId = item,
                            BannerId = model.Id
                        });
                    }
                    await dbClient.Insertable(list).ExecuteCommandAsync();
                }
                return new ResultInfo(ResultState.SUCCESS, "修改成功");
            }
            else
            {
                var info = new YB_Banner
                {
                    Createtime = DateTime.Now,
                    Status = AdStatus.Wait,
                    BusinessId = currentUser.BusinessId,
                    ClickCount = 0,
                    HeadImg = model.HeadImg,
                    StatusRemark = "",
                    EndTime = DateTime.Now,
                    Name = model.Name,
                    StartTime = DateTime.Now,
                    Type = model.Type,
                    AppId = model.AppId,
                    PositionType = currentUser.AccountType == AccountType.platform ? BannerPositionType.Platform : BannerPositionType.Business
                };
                var id = await dbClient.Insertable(info).ExecuteReturnIdentityAsync();
                var data = new YB_BannerContent
                {
                    Content = model.content,
                    BannerId = id
                };
                await dbClient.Insertable(data).ExecuteCommandAsync();
                if (model.equids != null && model.equids.Count > 0)
                {
                    List<YB_BannerEqu> list = new List<YB_BannerEqu>();
                    foreach (var item in model.equids)
                    {
                        list.Add(new YB_BannerEqu
                        {
                            EquId = item,
                            BannerId = id
                        });
                    }
                    await dbClient.Insertable(list).ExecuteCommandAsync();
                }
                return new ResultInfo(ResultState.SUCCESS, "添加成功");
            }
        }


    }
}
