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 InfoApp : Repository<YB_SecInfo>
    {
        /// <summary>
        /// 资讯列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<SecInfoListModel>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                var temquery = dbClient.Queryable<YB_SecInfo>();
                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.BusienssId == currentUser.BusinessId);
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                    .Select(x=>new SecInfoListModel
                    {
                        Id=x.Id,
                        Title=x.Title,
                        HeadImg=x.HeadImg,
                        CreateTime=x.CreateTime,
                        TagId=x.TagId,
                        Status=x.Status
                    })
                    .Mapper((it, cache) =>
                    {
                        var alltag = cache.Get(list => {
                            var ids = list.Select(x => x.TagId).ToList();
                            return dbClient.Queryable<YB_SecInfoType>().Where(x => ids.Contains(x.Id)).ToList();
                        });
                        it.tagname = alltag.FirstOrDefault(x => x.Id == it.TagId)?.Name;
                    })
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<SecInfoListModel>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(SecInfoSubmitModel model)
        {
            if (string.IsNullOrEmpty(model.content))
            {
                return new ResultInfo(ResultState.FAIL, "内容不可为空");
            }
            if(model.Title.Length > 50)
            {
                return new ResultInfo(ResultState.FAIL, "标题过长");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (model.Id > 0)
                {
                    await dbClient.Updateable<YB_SecInfo>().SetColumns(x => new YB_SecInfo
                    {
                        HeadImg = model.HeadImg,
                        TagId = model.TagId,
                        Title = model.Title
                    }).Where(x => x.Id == model.Id).ExecuteCommandAsync();

                    await dbClient.Updateable<YB_SecInfoContent>().SetColumns(x => new YB_SecInfoContent
                    {
                        Content = model.content
                    }).Where(x => x.InfoId == model.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "修改成功");
                }
                else
                {
                    var info = new YB_SecInfo
                    {
                        CreateTime = DateTime.Now,
                        Status = (int)AdStatus.Wait,
                        BusienssId = currentUser.BusinessId,
                        ClickCount = 0,
                        HeadImg = model.HeadImg,
                        StatusRemark = "",
                        TagId = model.TagId,
                        Title = model.Title,
                        Type = (int)AdType.Text
                    };
                    var id = await dbClient.Insertable<YB_SecInfo>(info).ExecuteReturnIdentityAsync();
                    var data = new YB_SecInfoContent
                    {
                        Content = model.content,
                        InfoId = id
                    };
                    await dbClient.Insertable<YB_SecInfoContent>(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_SecInfo>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "记录未找到");
                }
                //更新状态
                await dbClient.Updateable<YB_SecInfo>().SetColumns(x => new YB_SecInfo
                {
                    Status = status
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "状态更新成功");
            }
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SecInfoSubmitModel> DetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var info = await dbClient.Queryable<YB_SecInfo>().Select(x => new SecInfoSubmitModel
                {
                    Title = x.Title,
                    HeadImg = x.HeadImg,
                    TagId = x.TagId,
                    Type = x.Type,
                    Id = x.Id
                }).Where(x => x.Id == id).FirstAsync();
                var content = await dbClient.Queryable<YB_SecInfoContent>().Where(x => x.InfoId == id).FirstAsync();
                info.content = content?.Content;
                return info;
            }
        }
        /// <summary>
        /// 类型列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_SecInfoType>> GetTypeListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var currentUser = OperatorProvider.Provider.GetCurrent();
                var temquery = dbClient.Queryable<YB_SecInfoType>();
                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);
                    }
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<YB_SecInfoType>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }
        /// <summary>
        /// 所有类型列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<YB_SecInfoType>> GetAllTypeAsync()
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_SecInfoType>()
                    .Where(x => x.Status == 1)
                    .OrderBy(x => x.SortCode, OrderByType.Asc)
                    .ToListAsync();
            }
        }
        /// <summary>
        /// 类型信息修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitTypeAsync(YB_SecInfoType model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                model.Remark = model.Remark.ToStr();
                if (model.Id > 0)
                {
                    if (!await dbClient.Queryable<YB_SecInfoType>().AnyAsync(x => x.Id == model.Id))
                    {
                        return new ResultInfo(ResultState.FAIL, "记录未找到");
                    }
                    await dbClient.Updateable<YB_SecInfoType>().SetColumns(x => new YB_SecInfoType
                    {
                        Name = model.Name,
                        SortCode = model.SortCode,
                        Remark = model.Remark
                    }).Where(x => x.Id == model.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "修改成功");
                }
                else
                {
                    await dbClient.Insertable<YB_SecInfoType>(new YB_SecInfoType
                    {
                        Name = model.Name,
                        CreateTime = DateTime.Now,
                        Status = (int)StatusType.Enabled,
                        SortCode = model.SortCode,
                        Remark = model.Remark
                    }).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }

        /// <summary>
        /// 类型状态修改
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public async Task<ResultInfo> SetTypeStatusAsync(int id, int status)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (!await dbClient.Queryable<YB_SecInfoType>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "记录未找到");
                }
                //更新状态
                await dbClient.Updateable<YB_SecInfoType>().SetColumns(x => new YB_SecInfoType
                {
                    Status = status
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "状态更新成功");
            }
        }
        /// <summary>
        /// 类型详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_SecInfoType> DetailTypeAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_SecInfoType>().Where(x => x.Id == id).FirstAsync();
            }
        }
    }
}
