using Hotline.Caching.Interfaces;
using Hotline.CallCenter.BlackLists;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Ivrs;
using Hotline.CallCenter.Tels;
using Hotline.Configurations;
using Hotline.KnowledgeBase;
using Hotline.Orders;
using Hotline.Repository.SqlSugar;
using Hotline.Settings;
using Hotline.Share.Dtos.Home;
using Hotline.Share.Dtos.Identity;
using Hotline.Users;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SqlSugar;
using StackExchange.Redis;
using XF.Domain.Authentications;
using XF.Domain.Constants;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers;

/// <summary>
/// 主页相关接口
/// </summary>
public class HomeController : BaseController
{
    private readonly ISugarUnitOfWork<HotlineDbContext> _uow;
    private readonly ISessionContext _sessionContext;
    private readonly ISystemAuthorityRepository _systemAuthorityRepository;
    private readonly ISystemMenuRepository _systemMenuRepository;
    private readonly IMapper _mapper;
    private readonly IRepository<UserFastMenu> _userFastMenuRepository;
    private readonly IRepository<User> _userRepository;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    private readonly IOptionsSnapshot<AppConfiguration> _appOptions;

    public HomeController(
        ISugarUnitOfWork<HotlineDbContext> uow,
        ISessionContext sessionContext,
        ISystemAuthorityRepository systemAuthorityRepository,
        ISystemMenuRepository systemMenuRepository,
        IMapper mapper,
        IRepository<UserFastMenu> userFastMenuRepository,
        IRepository<User> userRepository,
        ISystemSettingCacheManager systemSettingCacheManager,
        IOptionsSnapshot<AppConfiguration> appOptions)
    {
        _uow = uow;
        _sessionContext = sessionContext;
        _systemAuthorityRepository = systemAuthorityRepository;
        _systemMenuRepository = systemMenuRepository;
        _mapper = mapper;
        _userFastMenuRepository = userFastMenuRepository;
        _userRepository = userRepository;
        _systemSettingCacheManager = systemSettingCacheManager;
        _appOptions = appOptions;
    }

    #region 开放请求接口

    /// <summary>
    /// 获取当前用户信息
    /// </summary>
    /// <returns></returns>
    [HttpGet("myinfo")]
    public async Task<Object> GetMyInfo()
    {
        if (!string.IsNullOrEmpty(_sessionContext.UserId))
        {
            var monitor = false;
            var setting = _systemSettingCacheManager.GetSetting(SettingConstants.SeatsMonitor);
            var settingStr = setting?.SettingValue;
            var roles = _sessionContext.Roles;
            foreach (var item in settingStr)
            {
                if (roles != null && roles.Contains(item)) monitor = true;
            }

            var user = await _userRepository.Queryable()
                .Includes(x => x.Organization)
                .Includes(x => x.Account)
                .Includes(x => x.Roles)
                .FirstAsync(x => x.Id == _sessionContext.UserId);
            //return await _userRepository.GetAsync(_sessionContext.UserId);
            return new { User = user, Monitor = monitor };
        }
        throw UserFriendlyException.SameMessage("无效登录信息");
    }

    //[AllowAnonymous]
    //[HttpGet("createdb")]
    //public Task CreateDb()
    //{
    //    var db = _uow.Db;
    //    db.DbMaintenance.CreateDatabase();
    //    //db.CodeFirst.InitTables<Blacklist,Call,CallDetail,CallRecord,TelHold>();
    //    //db.CodeFirst.InitTables<Ivr, IvrCategory, Tel, TelGroup, TelRest>();
    //    db.CodeFirst.InitTables<KnowledgeType>();
    //    //db.CodeFirst.InitTables<KnowledgeType, Orders.Order, OrderTemporary, OrgUser>();
    //    //db.CodeFirst.InitTables<SystemAuthority, SystemButton, SystemDataAuthority, SystemDataTable, SystemMenu>();
    //    //db.CodeFirst.InitTables<SystemOrganize, SystemSetting, SystemSettingGroup, UserFastMenu>();
    //    //db.CodeFirst.InitTables<User, Work,SysDicType,SysDicData, TrunkIvrManager>();
    //    return Task.CompletedTask;
    //}

    /// <summary>
    /// 获取可选快捷入口
    /// </summary>
    /// <returns></returns>
    [HttpPost("get-fastmenu")]
    public async Task<IReadOnlyList<SystemMenu>> GetFastMenuByToken([FromBody] GetFastMenuByTokenDto dto)
    {
        if (!string.IsNullOrEmpty(_sessionContext.UserId))
        {
            var roles = _sessionContext.Roles;
            return await _systemMenuRepository.GetFastMenu(roles, _sessionContext.UserId, dto.name);
        }
        throw UserFriendlyException.SameMessage("无效登录信息");
    }

    /// <summary>
    /// 设置快捷入口
    /// </summary>
    /// <returns></returns>
    [HttpPost("set-fastmenu")]
    public async Task SetFastMenu([FromBody] SetFastMenuDto dto)
    {
        if (!string.IsNullOrEmpty(_sessionContext.UserId))
        {
            string userId = _sessionContext.UserId;
            var model = await _userFastMenuRepository.GetAsync(x => x.UserId == userId);
            if (model is null)
            {
                var fastmenu = _mapper.Map<UserFastMenu>(dto);
                fastmenu.UserId = userId;
                await _userFastMenuRepository.AddAsync(fastmenu);
            }
            else
            {
                _mapper.Map(dto, model);
                await _userFastMenuRepository.UpdateAsync(model);
            }
        }
        else
        {
            throw UserFriendlyException.SameMessage("无效登录信息");
        }

    }

    /// <summary>
    /// 获取我的快捷入口
    /// </summary>
    /// <returns></returns>
    [HttpGet("get-myfastmenu")]
    public async Task<IReadOnlyList<SystemMenu>> GetMyFastMenu()
    {
        if (!string.IsNullOrEmpty(_sessionContext.UserId))
        {
            var roles = _sessionContext.Roles;
            return await _systemMenuRepository.GetMyFastMenu(roles, _sessionContext.UserId);
        }
        throw UserFriendlyException.SameMessage("无效登录信息");
    }

    /// <summary>
    /// 首页系统配置
    /// </summary>
    /// <returns>
    /// IsRestApproval : 小休是否需要审核
    /// IsNeedTelNo : 是否需要分机
    /// IsTelNeedVerify : 分机是否需要验证
    /// </returns>
    [HttpGet("home-page-info")]
    public async Task<object> HomePageInfo()
    {
        double[] locationCenter = new double[2];
        try
        {
            locationCenter = _systemSettingCacheManager
                .GetSetting(SettingConstants.LocationCenter)
                .SettingValue?
                .FirstOrDefault()
                .Split(',')
                .Select(double.Parse)
                .ToArray();
        }
        catch (Exception e)
        {
            // ignore
        }

        var rsp = new
        {
            IsRestApproval = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsRestApproval).SettingValue[0]),
            IsNeedTelNo = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsNeedTelNo).SettingValue[0]),
            IsTelNeedVerify = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsTelNeedVerify).SettingValue[0]),
            TalkingDealTime = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.TalkingDealTime).SettingValue[0]),
            IsCustomEvent = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsCustomEvent).SettingValue[0]),
            IsTranspondCity = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.TranspondCity).SettingValue[0]),
            IsAverageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]),
            IsOpenJudicialManagement = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsOpenJudicialManagement).SettingValue[0]),
            NoSignOrgCode = _systemSettingCacheManager.GetSetting(SettingConstants.NoSignOrgCode).SettingValue,
            ApplyDelayTime = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.ApplyDelayTime).SettingValue[0]),
            IsOpenRepeatedWorkOrders = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsOpenRepeatedWorkOrders).SettingValue[0]),
            OldHotlineUrl = _systemSettingCacheManager.GetSetting(SettingConstants.OldHotlineUrl).SettingValue[0],
            OldHotlineOrderState = _systemSettingCacheManager.GetSetting(SettingConstants.OldHotlineOrderState).SettingValue[0],
            FileExt = _systemSettingCacheManager.GetSetting(SettingConstants.FileExt).SettingValue[0],
            NationalPlatformWordLimit = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.NationalPlatformWordLimit).SettingValue[0]),
            HandleOpinionWordLimit = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.HandleOpinionWordLimit).SettingValue[0]),
            CallInOpenType = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.CallInOpenType).SettingValue[0]),
            Snapshot = _systemSettingCacheManager.Snapshot,
            IsTelRest = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsTelRest).SettingValue[0]),
            TelRestNum = int.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.TelRestNum).SettingValue[0]),
            IsOpenSpecialPhone = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsOpenSpecialPhone).SettingValue[0]),
            CallCenterType = _appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType,
            CallCenterSocketUrl = _systemSettingCacheManager.GetSetting(SettingConstants.CallCenterSocketUrl).SettingValue?.FirstOrDefault(),
            RecordPrefix = _systemSettingCacheManager.GetSetting(SettingConstants.RecordPrefix).SettingValue?.FirstOrDefault(),
            RecordDownLoadPrefix = _systemSettingCacheManager.GetSetting(SettingConstants.RecordDownLoadPrefix).SettingValue?.FirstOrDefault(),
            Luzhouhcp = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.LuZhouHaoChaPing).SettingValue[0]),
            LocationCenter = locationCenter,
            IsEarly = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsEarly).SettingValue[0]),
            IsOpenWhiteList = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsOpenWhiteList).SettingValue[0])

        };
        return rsp;
    }


    #endregion

    #region 菜单权限

    /// <summary>
    /// 获取当前用户所有菜单
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet("get-my-auth-menu")]
    public async Task<UserAuthorityDto> GetUserAuthorityMenuByToken()
    {
        var roles = _sessionContext.Roles;
        var menus = _mapper.Map<List<SystemMenuDto>>(await _systemAuthorityRepository.GetMyMenu(roles));
        var buttons = await _systemAuthorityRepository.GetMyButton(roles);
        return new UserAuthorityDto() { menus = menus, buttons = buttons };
    }



    ///// <summary>
    ///// 获取当前用户所有按钮
    ///// </summary>
    ///// <returns></returns>
    //[AllowAnonymous]
    //[HttpGet("get-my-auth-button")]
    //public async Task<IReadOnlyList<string>> GetUserAuthorityButtonByToken()
    //{
    //    var roles = _sessionContext.Roles;
    //    return await _systemAuthorityRepository.GetMyButton(roles);
    //}



    #endregion


}