using AntDesign;
using DFS.Infrastructure.Extension.SM;
using AI.Platform.Service.Common;
using AI.Platform.Core;
using AI.Platform.Core.Dto.CardManagement;
using AI.Platform.Core.Entity;
using AI.Platform.Core.Entity.System.VehicleTerminal.CardInfo;
using AI.Platform.Core.Entity.System.VehicleTerminal.Company;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Reflection.Emit;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Company;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.ElectronicAccount;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;
using static AI.Platform.Core.Entity.PublicEnum;

namespace AI.Platform.Service;

[AllowAnonymous]
[ApiGroup(ApiGroupNames.Auth)]
public class AuthService : BaseService
{
    /// <summary>
    /// 注意，非blazor环境，不能使用[Inject]方式注入
    /// </summary>
    private readonly SqlSugarRepository<SystemUser> _user;
   private SqlSugarRepository<CardInfoEntity> _CardInforepository { get; set; }
   private SqlSugarRepository<CompanyEntity> _Companyrepository { get; set; }
   private SqlSugarRepository<ElectronicAccountEntity> _Accountrepository { get; set; }
   private SqlSugarRepository<UserInfoEntity> _UserInforepository { get; set; }
   private SqlSugarRepository<UserCardRelationEntity> _UserCardRelationrepository { get; set; }
    private SqlSugarRepository<CompanyCardRuleEntity> _CompanyCardRuleRepository { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private readonly IHttpContextAccessor _contextAccessor;

    public AuthService(IHttpContextAccessor contextAccessor, 
        SqlSugarRepository<SystemUser> user, 
        SqlSugarRepository<CardInfoEntity> CardInforepository,
        SqlSugarRepository<CompanyEntity> Companyrepository,
        SqlSugarRepository<ElectronicAccountEntity> Accountrepository,
        SqlSugarRepository<UserInfoEntity> UserInforepository,
        SqlSugarRepository<CompanyCardRuleEntity> CompanyCardRuleRepository)
    {
        _contextAccessor = contextAccessor;
        _user = user;
        _CardInforepository = CardInforepository;
        _Companyrepository = Companyrepository;
        _Accountrepository = Accountrepository;
        _UserInforepository = UserInforepository;
        _CompanyCardRuleRepository = CompanyCardRuleRepository;
    }

    /// <summary>
    /// 登录
    /// {"username":"admin","password":"123456"}
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> Login(LoginInput input)
    {
        try
        {
            var Password = Crypto.MD5Encrypt(input.Password);
            var user = await _user.AsQueryable()
                .Where(x => x.Account.Equals(input.Account) && x.Password.Equals(Password))
                .FirstAsync();
            _ = user ?? throw Oops.Oh(ErrorCode.E1000);

            //生成Token令牌
            var token = Jwt.Serialize(new TokenModelJwt
            {
                UserId = user.Id,
                Name = user.Account,
                UserType = PublicEnum.UserType.Admin,
            });
            string Buid = "c75b2e74-d51e-42ae-bc89-2d39312c9c30";
            _contextAccessor.HttpContext.Response.Headers["access-token"] = token;
            return new { token , Buid };
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 获取企业密钥
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> GetEnterpriseSecretKey()
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var EnterpriseSecretKey = "1234234532345234".SM4Encrypt_ECB("54CD806F28AF7FAF61A48DF82DF17C96");
            return  EnterpriseSecretKey;
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 开卡or销卡
    /// </summary>
    /// <param name="CardNo"></param>
    /// <param name="AccountID"></param>
    /// <param name="operatetype">开卡：“newcard”；销卡“cancelcard”</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<object> IssueCard(string CardNo, string operatetype)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                 .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                 .LeftJoin<UserInfoEntity>((a, b, c) => c.Id == b.UserId)
                .Where((a, b, c) => a.CardNo == CardNo)
                .Select((a, b, c) => new CardInfoDto
                {
                    Type = a.CardType,
                    UserName = c.UserName
                }).FirstAsync();
            if (CardInfo == null)
            {
                return new
                {
                    result = false,
                    message = "卡不存在",
                    cardtype = 0,
                    accountname = ""
                }; ;
            }
            if (operatetype == "newcard")
            {
                return new
                {
                    result = true,
                    message = "开卡成功",
                    cardtype = CardInfo.CardType,
                    accountname = CardInfo.UserName
                }; ;
            }
            else if(operatetype == "cancelcard")
            {
                return new
                {
                    result = true,
                    message = "销卡成功",
                    cardtype = CardInfo.CardType,
                    accountname = CardInfo.UserName
                }; ;
            }
            return null;
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 获取卡信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> GetCardInfo(string CardNo)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                 .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                 .LeftJoin<UserInfoEntity>((a, b,c) => c.Id == b.UserId)
                .Where((a, b, c) => a.CardNo == CardNo)
                .Select((a, b, c) => new CardInfoDto
                {
                    Type = a.CardType,
                    UserName = c.UserName
                }).FirstAsync();
            var result = new {
                code = CardInfo != null ? 200 : 201,
                message = "",
                cardtype = CardInfo.Type,
                accountname = CardInfo.UserName
            };
            return result;
        }
        catch (Exception ex)
        {   
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 查询是否可以发卡
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> CanIssueCard(string CardNo, string PhyNo)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                 .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                 .LeftJoin<UserInfoEntity>((a, b, c) => c.Id == b.UserId)
                .Where((a, b, c) => a.CardNo == CardNo)
                .Select((a, b, c) => new CardInfoDto
                {
                    Type = a.CardType,
                    UserName = c.UserName
                }).FirstAsync();
            if (CardInfo == null)
            {
                return new
                {
                    result = false,
                    code = 201,
                    message = "账户没有该卡",
                    cardtype = 0,
                    accountname = ""
                };
            }
            var resultJson = new
            {
                result = true,
                code = 200,
                message = "",
                cardtype = CardInfo.Type,
                accountname = CardInfo.UserName
            };
            return resultJson;
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }
    /// <summary>
    /// 申请发卡
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> ApplyForCard(string CardNo,string PhyNo)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                           .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                           .LeftJoin<UserInfoEntity>((a, b, c) => c.Id == b.UserId)
                          .Where((a, b, c) => a.CardNo == CardNo)
                          .Select((a, b, c) => new CardInfoDto
                          {
                              Type = a.CardType,
                              UserName = c.UserName
                          }).FirstAsync();
            if (CardInfo == null)
            {
                return new
                {
                    result = false,
                    code = 201,
                    message = "卡不存在",
                    cardtype = 0,
                    accountname = ""
                }; ;
            }
            return new
            {
                result = true,
                code = 200,
                message = "开卡成功",
                cardtype = CardInfo.Type,
                accountname = CardInfo.UserName
            };
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 查询是否可以销卡
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> CanCancelCard(string CardNo, string PhyNo)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                 .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                 .LeftJoin<UserInfoEntity>((a, b, c) => c.Id == b.UserId)
                .Where((a, b, c) => a.CardNo == CardNo)
                .Select((a, b, c) => new CardInfoDto
                {
                    Type = a.CardType,
                    UserName = c.UserName,
                    AccountBalance = b.Balance
                }).FirstAsync();
            if (CardInfo == null)
            {
                return new
                {
                    result = false,
                    code = 201,
                    message = "卡不存在",
                    cardtype = 0,
                    accountname = ""
                }; 
            }
            if (CardInfo.AccountBalance > 0)
            {
                return new
                {
                    result = false,
                    code = 203,
                    message = "账户余额大于0",
                    cardtype = 0,
                    accountname = ""
                };
            }
            var result = new
            {
                result = true,
                code = 200,
                message = "",
                cardtype = CardInfo.Type,
                accountname = CardInfo.UserName
            };
            return result;
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 申请销卡
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks><code>{"username":"admin","password":"123456"}</code></remarks>
    [HttpPost]
    public async Task<object> ApplyForCardCancellation(string CardNo, string PhyNo)
    {
        try
        {
            var CurrentBuId = _contextAccessor.HttpContext.Response.Headers["CurrentBuId"];
            var CardInfo = await _CardInforepository.AsQueryable()
                 .LeftJoin<ElectronicAccountEntity>((a, b) => b.Id == a.AccountId)
                 .LeftJoin<UserInfoEntity>((a, b, c) => c.Id == b.UserId)
                .Where((a, b, c) => a.CardNo == CardNo)
                .Select((a, b, c) => new CardInfoDto
                {
                    Type = a.CardType,
                    UserName = c.UserName
                }).FirstAsync();
            return new
            {
                result = true,
                coo = "200",
                message = "销卡成功",
                cardtype = CardInfo.Type,
                accountname = CardInfo.UserName
            }; ;
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }
    /// <summary>
    /// 刷新Token
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<object> Refresh(string token)
    {
        try
        {
            return new { token };
        }
        catch (Exception ex)
        {
            throw Oops.Oh(ex.Message);
        }
    }
}
