using BPA.Kitchen.Core.Common.RequestAnalysis;
using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.Application.Service.Authorization.Dtos;
using BPA.KitChen.GroupMeal.Core.Common;
using BPA.KitChen.GroupMeal.Core.Entity;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BPA.KitChen.GroupMeal.Application.Service.Authorization.Services
{
    public class AuthorizationService: UserAnalysis,IAuthorizationService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public AuthorizationService(ISqlSugarClient db)
        {
            _db = db;
        }

        


        /// <summary>
        /// 分页店铺授权码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageUtil> PageStoreAuthorization(PageInputBase input)
        {
            RefAsync<int> total = 0;
            var res = await _db.Queryable<BPA_StoreAuthorization, ShopEntity>((a,b) => new JoinQueryInfos(
                    JoinType.Left,a.StoreId==b.Id))
                .Select((a, b)  =>new StoreAuthorizationDto
                {
                    Id = a.Id,
                    Key = a.Key,
                    StoreId = a.StoreId,
                    StoreName = b.Name,
                    UpdateAt = a.UpdateAt,
                    PeriodValidity = a.PeriodValidity,
                    GroupId = a.GroupId,

                })
                .ToPageListAsync(input.Current, input.PageSize, total);
            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = res
            };
            return util;
        }

        /// <summary>
        /// 添加店铺授权码
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AddStoreAuthorization(CreateOrUpDateStoreAuthorizationDto input)
        {
            var data = _db.Queryable<BPA_StoreAuthorization>().Where(x=>x.StoreId== input.StoreId).ToList();
            if (data.Count > 0)
            {
                throw Oops.Oh("店铺授权码已存在");
            }

            var res = await _db.Insertable(new BPA_StoreAuthorization()
            {
                StoreId = input.StoreId,
                Key = Guid.NewGuid().ToString(),
                PeriodValidity = input.PeriodValidity,
                UpdateAt=DateTime.Now,
                GroupId= CurrentUser.TenantId

            }).ExecuteCommandAsync();

            return res > 0;
        }

        /// <summary>
        /// 修改店铺授权码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> UpdateStoreAuthorization(string id)
        {
            var data = await _db.Queryable<BPA_StoreAuthorization>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }
            data.Key = Guid.NewGuid().ToString();
            data.UpdateAt = DateTime.Now;

            return await _db.Updateable(data).ExecuteCommandHasChangeAsync();
        }


        /// <summary>
        /// 修改店铺授权码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> UpdateStoreAuthTime(CreateOrUpDateStoreAuthorizationDto input)
        {
            var data1 = await _db.Queryable<BPA_StoreAuthorization>().FirstAsync(x => x.StoreId == input.StoreId);
            if (data1!=null&&data1.Id!=input.Id)
            {
                throw Oops.Oh("店铺授权信息已存在");
            }
            var data = await _db.Queryable<BPA_StoreAuthorization>().FirstAsync(x => x.Id == input.Id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }
            data.Key = Guid.NewGuid().ToString();
            data.PeriodValidity = input.PeriodValidity;
            data.UpdateAt = DateTime.Now;

            return await _db.Updateable(data).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 删除店铺权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DelStoreAuthorization(string id)
        {
            var data = await _db.Queryable<BPA_StoreAuthorization>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }

            return await _db.Deleteable(data).ExecuteCommandHasChangeAsync();
        }


        /// <summary>
        /// 查询店铺授权信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BPA_StoreAuthorization> GetStoreAuthorizationById(string id)
        {
            var data = await _db.Queryable<BPA_StoreAuthorization>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }

            return data;
        }

        /// <summary>
        /// 查询店铺授权信息 更具KEY
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<BPA_StoreAuthorization> GetStoreAuthorizationByKey(string key)
        {
            var data = await _db.Queryable<BPA_StoreAuthorization>()
                .ClearFilter()
                .FirstAsync(x => x.Key == key);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }

            return data;
        }

        /// <summary>
        /// CodeFirst
        /// </summary>
        /// <param name="tableNames"></param>
        public void CodeFirst()
        {
            try
            {
                var list = new List<string>()
                {
                    "BPA_PlatformAuthorization",
                    "BPA_StoreAuthorization"

                };
                var types = Assembly.Load("BPA.SAAS.KitChenManage.Core").GetTypes()
                    .Where(x => x.Namespace != null
                                && x.GetCustomAttribute<SugarTable>() != null
                                && x.Namespace.Contains("BPA.SAAS.KitChenManage.Core.Model")
                                && list.Contains(x.Name))
                    .ToArray();

                _db.CodeFirst.InitTables(types);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }


        }
    }
}
