using AI.Platform.Core;
using AI.Platform.Core.Entity.Device;
using AI.Platform.Core.Entity.Site;
using AI.Platform.Page.Pages.Site.Model;
using AntDesign;
using AntDesign.TableModels;
using Dm.util;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using SqlSugar;
using System.Data.Common;
using System.Text.Json;
using System.Threading.Tasks;

namespace AI.Platform.Page.Pages.Site;

public partial class Screen
{
    /// <summary>
    /// 
    /// </summary>
    [Inject] NavigationManager NavigationManager { get; set; }
    /// <summary>
    /// 数据库仓储
    /// </summary>
    [Inject] SqlSugarRepository<ScreentEntity> _Repository { get; set; }

    /// <summary>
    /// 站点
    /// </summary>
    [Inject] SqlSugarRepository<SiteEntity> _SiteRepository { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] IJSRuntime IJSRuntime { get; set; }
    /// <summary>
    ///
    /// </summary>
    private ITable _Table;
    
    /// <summary>
    /// 站点列表信息
    /// </summary>
    private List<SnInfo> _DataSource;
    
    /// <summary>
    /// 总条数
    /// </summary>
    private int Total = 0;
    /// <summary>
    /// 加载
    /// </summary>
    private bool Loading = false;

    /// <summary>
    /// 查询过滤条件
    /// </summary>
    private FilterData filterData { set; get; } = new();

    /// <summary>
    /// 编辑弹窗
    /// </summary>
    private UpdateScreenDialog updateMediaDialog { set; get; } = new();

    /// <summary>
    /// 标识弹窗是否显示
    /// </summary>
    private bool isOpen { set; get; } = false;

    private ScrrenDialogModel model = new ScrrenDialogModel();

    // <summary>
    /// 站点
    /// </summary>
    private List<SiteInfo> Sites;

    /// <summary>
    /// 打开编辑弹窗
    /// </summary>
    /// <param name="type">类型：1：新增；2：编辑；3：删除</param>
    /// <param name="snInfo">大屏信息</param>
    /// <returns></returns>
    private async Task ShowDialog(int type, SnInfo? snInfo)
    {
        await searchSitesAsync();
        model = new ScrrenDialogModel();
        model.Type = type;
        model.Sites = Sites;
        if(type == 2 || type == 3)
        {
            model.sn = snInfo?.sn?? "";
            model.SiteId = snInfo?.SiteId ?? -1;
            model.siteName = snInfo?.siteName ?? "";
            model.Id = snInfo?.Id;
            model.Remark = snInfo?.Remark ?? "";
        }

        isOpen = true;
    }
    
    /// <summary>
    /// 编辑弹窗信息回调
    /// </summary>
    /// <param name="model"></param>
    private async Task OnDialogCallback(ScrrenDialogModel model)
    {
        switch (model.Type)
        {
            case 1:
                await _Repository.InsertAsync(model.ToCompany());
                break;
            case 2:
                ScreentEntity siteEntity = model.ToCompany();
                await _Repository.Context.Updateable(siteEntity).
                    UpdateColumns(it => new { it.sn,it.SiteId, it.Remark})
                    .ExecuteCommandAsync();
                break;
            case 3:
                await _Repository.DeleteByIdAsync(model.Id);
                break;
        }
        await Query();
    }

    /// <summary>
    /// 编辑弹窗是否显示回调
    /// </summary>
    /// <param name="isOpen"></param>
    private void OnDialogVisibleCallback(bool isOpen)
    {
        this.isOpen = isOpen;
    }

    /// <summary>
    /// 表格查询
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    private async Task OnChange(QueryModel<SnInfo> query)
        => await Query();

    /// <summary>
    /// 查
    /// </summary>
    /// <returns></returns>
    private async Task Query()
    {
        Loading = true;

        var query = _Repository.AsQueryable()
            .LeftJoin<SiteEntity>((screen, site) => screen.SiteId == site.Id);

        query = query
            .WhereIF(filterData.siteName.IsNotNullOrEmpty(),(screen, site) => site.Name.Contains(filterData.siteName))
            .WhereIF(filterData.sn.IsNotNullOrEmpty(), (screen, site) => screen.sn.Contains(filterData.sn));

        Total = await query.CountAsync();

        _DataSource = await query
            .Select((screen,site) => new SnInfo() 
            {
                Id = screen.Id,
                sn = screen.sn,
                SiteId = screen.SiteId,
                siteName = site.Name,
                CreateTime = screen.CreateTime,
                EditTime = screen.EditTime,
                Remark = screen.Remark,
            })
            .Skip((filterData.currentPage - 1) * filterData.pageSize)
            .Take(filterData.pageSize)
            .ToListAsync();

        await searchSitesAsync();
        Loading = false;
    }

    Func<PaginationTotalContext, string> showTotal = ctx => $"总数 {ctx.Total} ";

    private async Task OnPageChange(PaginationEventArgs args)
    {
        filterData.pageSize = args.PageSize;
        filterData.currentPage = args.Page;
        await Query();
    }

    /// <summary>
    /// 清空查询条件
    /// </summary>
    private void HandleReset()
    {
        filterData = new();
    }

    private async Task searchSitesAsync()
    {
        if (Global.CurrentUser.Account == "admin")
        {
            Sites = await _SiteRepository.AsQueryable()
                .Select<SiteInfo>()
                .ToListAsync();
        }
        else
        {
            Sites = await _SiteRepository.AsQueryable()
                .Where(it => it.Id == Global.CurrentUser.SiteId || it.ParentId == Global.CurrentUser.SiteId)
                .Select<SiteInfo>()
                .ToListAsync();
        }
    }

    protected override async void OnInitialized()
    {

    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await NavigationManager.RedirectLogin(IJSRuntime);
            await Query();
            
        }
    }

    private async Task OnChange(QueryModel<SystemMenu> query)
        => await Query();


    /// <summary>
    /// 查找条件
    /// </summary>
    public class FilterData
    {
        /// <summary>
        /// 页码
        /// </summary>
        public int currentPage { set; get; } = 1;

        /// <summary>
        /// 页数
        /// </summary>
        public int pageSize { set; get; } = 10;

        /// <summary>
        /// 要查找的站名
        /// </summary>
        public string? siteName { set; get; }

        /// <summary>
        /// 要查找的SN
        /// </summary>
        public string? sn{ set; get; }
    }
}
