using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Org;
using BPA.SAAS.Manage.Core;
using NPOI.Util.ArrayExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BPA.SAAS.KitChenManage.Core;
using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.Manage.Core.System;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.CheckService.Services
{
    public class CheckServices : ICheckServices, ITransient
    {
        /// <summary>
        ///检查Sign
        /// </summary>
        public async Task CheckSign(string key,string signStr,string signMd5)
        {

          
            //检查key
            await CheckKey(key);

            //var thisSign = signStr + "&key=" + key;
            //var vvv = MD5Encryption.Encrypt(thisSign.ToUpper()).ToUpper();

            //var vvvvv = thisSign.ToUpper();

            //if (MD5Encryption.Encrypt(thisSign.ToUpper()).ToUpper() != signMd5.ToUpper())
            //{
            //    throw Oops.Oh(ErrorCodeEnum.Code1005);
            //}
        }

        
        /// <summary>
        /// 检查平key验证
        /// </summary>
        /// <param name="key"></param>
        private async Task CheckKey(string key)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_PlatformAuthorization>()
                .ClearFilter()
                .FirstAsync(x => x.Key == key);
            if (data == null)
            {
                throw Oops.Oh(ErrorCodeEnum.Code1004);
            }

            if (data.PeriodValidity!=null)
            {
                if (data.PeriodValidity.Value.Date<DateTime.Now.Date)
                {
                    throw Oops.Oh(ErrorCodeEnum.Code10014);
                }
            }
            await CheckTenant(data.GroupId);

        }

        /// <summary>
        /// 检查租户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task CheckTenant(string tenantId)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_Company>().FirstAsync(x => x.Id == tenantId);

            if (data == null)
            {
                throw Oops.Oh(ErrorCodeEnum.Code1000);
            }

            CurrentUser.GroupId = tenantId;
        }
    }
}
