using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
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.Entity;

namespace YBDevice.NApi.Application.MessageInfo
{
    /// <summary>
    /// 消息管理
    /// </summary>
    public class MessageService : BaseService, IMessageService, ITransient
    {
        private readonly ISqlSugarRepository<YB_nMeasureResult> repository;
        private readonly SqlSugarClient dbClient;
        private readonly IDistributedIDGenerator _idGenerator;
        public MessageService(ISqlSugarRepository<YB_nMeasureResult> sqlSugarRepository, IDistributedIDGenerator idGenerator)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _idGenerator = idGenerator;
        }
        /// <summary>
        /// 获取客服配置信息
        /// </summary>
        /// <param name="appid">小程序appid</param>
        /// <returns></returns>
        public async Task<ResultInfo> GetServiceInfoAsync(string appid)
        {
            var data = await dbClient.Queryable<YB_WXCustomService>()
                .Where(x => x.AppId == appid)
                .Select(x => new CustomServiceC2SDto
                {
                    QyAppId = x.QyAppId,
                    Url = x.Url
                })
                .FirstAsync();
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "小程序还未配置微信客服");
            }
            return new ResultInfo(ResultState.SUCCESS, "success", data);
        }
        /// <summary>
        /// 获取订阅状态
        /// </summary>
        /// <param name="appid">小程序appid</param>
        /// <returns></returns>
        public async Task<ResultInfo> GetSubscribeInfoAsync(string appid)
        {
            var data = await dbClient.Queryable<YB_UserSubscribeMessage>().Where(x => x.AppId == appid && x.OpenId == authInfo.OpenId).Select(x => new UserSubscribeS2CDto
            {
                Type = x.Type
            }).FirstAsync();
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "未订阅消息");
            }
            return new ResultInfo(ResultState.SUCCESS, "订阅消息", data);
        }

        /// <summary>
        /// 获取消息模板列表
        /// </summary>
        /// <param name="appid">小程序appid</param>
        /// <returns></returns>
        public async Task<ResultInfo> GetTplListAsync(string appid)
        {
            var list = await dbClient.Queryable<YB_MiniProgramSubscribeMessageTpl>().Where(x => x.AppId == appid && x.IsSelected)
                .Select(x => new SubscribeTplS2CDto
                {
                    Id = x.PriTmplId
                })
                .ToListAsync();
            return new ResultInfo(ResultState.SUCCESS, "success", list);
        }

        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubscribeAsync(SubscribeC2SDto data)
        {
            var datalist = await dbClient.Queryable<YB_UserSubscribeMessage>()
                .Where(x => x.OpenId == authInfo.OpenId)
                .Select(x => new YB_UserSubscribeMessage
                {
                    TplId = x.TplId,
                    Id = x.Id,
                    AppId = x.AppId,
                    OpenId = x.OpenId,
                    UserId = x.UserId
                })
                .ToListAsync();
            List<YB_UserSubscribeMessage> insertlist = new List<YB_UserSubscribeMessage>();
            List<YB_UserSubscribeMessage> updatelist = new List<YB_UserSubscribeMessage>();
            List<Guid> deletelist = new List<Guid>();
            bool IsSuccess = false;//是否订阅成功
            data.List.ForEach(x =>
            {
                var currentData = datalist.FirstOrDefault(e => e.TplId == x.TplId);
                if (currentData != null)
                {
                    //如果是接受
                    if (x.Status.ToUpper() == SubscribeStatusConst.Accept)
                    {
                        updatelist.Add(new YB_UserSubscribeMessage
                        {
                            CreateTime = DateTime.Now,
                            IsAlWays = false,
                            Id = currentData.Id,
                            Type = data.Type,
                            AppId = currentData.AppId,
                            OpenId = currentData.OpenId,
                            TplId = x.TplId,
                            UserId = currentData.UserId
                        });
                        IsSuccess = true;
                    }
                    //其他情况删除
                    else
                    {
                        deletelist.Add(currentData.Id);
                    }
                }
                //如果是接受
                else if (x.Status.ToUpper() == SubscribeStatusConst.Accept)
                {
                    insertlist.Add(new YB_UserSubscribeMessage
                    {
                        Id = _idGenerator.Create().ToGuid(),
                        CreateTime = DateTime.Now,
                        IsAlWays = false,
                        OpenId = authInfo.OpenId,
                        TplId = x.TplId,
                        Type = data.Type,
                        UserId = authInfo.UserId,
                        AppId = data.AppId
                    });
                    IsSuccess = true;
                }
            });
            if (updatelist.Count > 0)
            {
                await dbClient.Updateable(updatelist).ExecuteCommandAsync();
            }
            if (insertlist.Count > 0)
            {
                await dbClient.Insertable(insertlist).ExecuteCommandAsync();
            }
            if (deletelist.Count > 0)
            {
                await dbClient.Deleteable<YB_UserSubscribeMessage>().Where(x => deletelist.Contains(x.Id)).ExecuteCommandAsync();
            }
            if (IsSuccess)
            {
                return new ResultInfo(ResultState.SUCCESS, "消息订阅成功");
            }
            else
            {
                return new ResultInfo(ResultState.FAIL, "消息订阅失败");
            }
        }

        /// <summary>
        /// 消息取消订阅
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> UnSubscribeAsync(UnSubscribeC2SDto data)
        {
            // 清除原先的
            await dbClient.Deleteable<YB_UserSubscribeMessage>().Where(x => x.OpenId == authInfo.OpenId && x.Type == data.Type).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "消息取消订阅成功");
        }
    }
}
