using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Service.DBServices
{
    /// <summary>
    /// 轮播图、开屏广告管理
    /// </summary>
    public partial class BannerApp : Repository<YB_Business>
    {
        /// <summary>
        /// 获取轮播图、开屏广告列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<BannerListModel>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                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 != (int)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,
                        PositionType=x.PositionType,
                        Type=x.Type
                    })
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<BannerListModel>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(BannerSubmitModel model)
        {
            if (string.IsNullOrEmpty(model.content))
            {
                return new ResultInfo(ResultState.FAIL, "内容不可为空");
            }
            if(model.Type == (int)AdType.URL && !model.content.ToLower().StartsWith("http"))
            {
                return new ResultInfo(ResultState.FAIL, "链接格式不正确");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (model.Id > 0)
                {
                    await dbClient.Updateable<YB_Banner>().SetColumns(x => new YB_Banner
                    {
                        HeadImg = model.HeadImg,
                        EndTime=model.EndTime,
                        Name=model.Name,
                        PositionType=model.PositionType,
                        StartTime=model.StartTime,
                        Type=model.Type
                    }).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();
                    return new ResultInfo(ResultState.SUCCESS, "修改成功");
                }
                else
                {
                    var info = new YB_Banner
                    {
                        Createtime = DateTime.Now,
                        Status = (int)AdStatus.Wait,
                        BusinessId = currentUser.BusinessId,
                        ClickCount = 0,
                        HeadImg = model.HeadImg,
                        StatusRemark = "",
                        EndTime=model.EndTime,
                        Name=model.Name,
                        PositionType=model.PositionType,
                        StartTime=model.StartTime,
                        Type = model.Type
                    };
                    var id = await dbClient.Insertable<YB_Banner>(info).ExecuteReturnIdentityAsync();
                    var data = new YB_BannerContent
                    {
                        Content = model.content,
                        BannerId = id
                    };
                    await dbClient.Insertable<YB_BannerContent>(data).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }

        /// <summary>
        /// 状态修改
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="status">状态</param>
        /// <param name="remark">状态描述</param>
        /// <returns></returns>
        public async Task<ResultInfo> SetStatusAsync(int id, int status, string remark)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                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="id"></param>
        /// <returns></returns>
        public async Task<BannerSubmitModel> DetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var info = await dbClient.Queryable<YB_Banner>().Select(x => new BannerSubmitModel
                {
                    Name = x.Name,
                    HeadImg = x.HeadImg,
                    Type = x.Type,
                    Id = x.Id,
                    StartTime=x.StartTime,
                    EndTime=x.EndTime,
                    PositionType=x.PositionType
                }).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;
            }
        }
    }
}
