using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Domain;

namespace Waste.Application
{
    public class BusinessApiService : BaseInfoService, IBusinessApiService, ITransient
    {
        private readonly ISqlSugarRepository<W_BusinessAppApi> repository;
        private readonly SqlSugarClient dbClient;

        public BusinessApiService(ISqlSugarRepository<W_BusinessAppApi> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteFormAsync(Guid keyValue)
        {
            if (!await dbClient.Queryable<W_BusinessAppApi>().AnyAsync(x => x.Id == keyValue))
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            await dbClient.Deleteable<W_BusinessAppApi>().Where(x => x.Id == keyValue).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<W_BusinessAppApi> DetailAsync(Guid id)
        {
            return await dbClient.Queryable<W_BusinessAppApi>().FirstAsync(x => x.Id == id);
        }
        /// <summary>
        /// 授权列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<BusinessApiInfo>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<W_BusinessAppApi>();
            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)
                .Select(x => new BusinessApiInfo
                {
                    Id = x.Id,
                    AppId = x.AppId,
                    Status = x.Status,
                    AppSecret = x.AppSecret,
                    CreateTime = x.CreateTime,
                    IPList = x.IPList,
                    PushUrl = x.PushUrl
                })
                .Mapper((it, cache) =>
                {
                    var allbus = cache.Get(list =>
                    {
                        var ids = list.Select(x => x.Id).ToList();
                        return repository.Change<W_Business>().Context.Queryable<W_Business>().Where(x => ids.Contains(x.Id)).ToList();
                    });
                    var bus = allbus.FirstOrDefault(x => x.Id == it.Id);
                    it.BusinessName = bus != null ? bus.Name : "";
                })
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<BusinessApiInfo>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitFormAsync(W_BusinessAppApi role)
        {
            role.IPList = role.IPList.ToStr();
            role.PushUrl = role.PushUrl.ToStr();
            if (string.IsNullOrEmpty(role.PushUrl))
            {
                return new ResultInfo(ResultState.FAIL, "推送地址不可为空");
            }
            if (!role.PushUrl.ToLower().StartsWith("http"))
            {
                return new ResultInfo(ResultState.FAIL, "推送地址格式不正确");
            }
            if (await dbClient.Queryable<W_BusinessAppApi>().AnyAsync(x => x.Id == role.Id))
            {
                await dbClient.Updateable<W_BusinessAppApi>().SetColumns(x => new W_BusinessAppApi
                {
                    PushUrl = role.PushUrl,
                    IPList = role.IPList
                }).Where(x => x.Id == role.Id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "授权更新成功");
            }
            else
            {
                role.AppId = $"jt_{IDGen.NextID().ToString("N")}";
                string secret = Md5.md5(role.AppId, 32);
                role.AppSecret = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));
                role.Status = (int)StatusType.Enabled;
                role.CreateTime = DateTime.Now;
                await dbClient.Insertable<W_BusinessAppApi>(role).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "授权分配成功");
            }
        }
        /// <summary>
        /// 检查是否在IP白名单中
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public async Task<ResultInfo> IsWhiteIP(string appid, string ip)
        {
            var data = await dbClient.Queryable<W_BusinessAppApi>().FirstAsync(x => x.AppId == appid);
            if (data == null)
            {
                return new ResultInfo(ApiResultState.NONAPPID, "appid无效");
            }
            if (!string.IsNullOrEmpty(data.IPList) && !data.IPList.Contains(ip))
            {
                return new ResultInfo(ApiResultState.IPNOALLOW, "IP不合法");
            }
            return new ResultInfo(ApiResultState.SUCCESS, "success");
        }
        /// <summary>
        /// 根据商户ID获取详情
        /// </summary>
        /// <returns></returns>
        public async Task<List<W_BusinessPush>> GetPushListAsync()
        {
            var query = await dbClient.Ado.UseStoredProcedure().GetDataTableAsync("proc_getthirdpush", new { });
            var list = query.ToList<W_BusinessPush>();
            return list;
        }
        /// <summary>
        /// 增加推送消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task InsertPushInfoAsync(W_BusinessPush data)
        {
            await dbClient.Insertable<W_BusinessPush>(data).ExecuteCommandAsync();
        }
    }
}
