using AI.Platform.Core;
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 Site
{
    /// <summary>
    /// 
    /// </summary>
    [Inject] NavigationManager NavigationManager { get; set; }
    /// <summary>
    /// 数据库仓储
    /// </summary>
    [Inject] SqlSugarRepository<SiteEntity> _Repository { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] IJSRuntime IJSRuntime { get; set; }
    /// <summary>
    ///
    /// </summary>
    private ITable _Table;
    
    /// <summary>
    /// 站点列表信息
    /// </summary>
    private List<SiteOutput> _DataSource;
    
    /// <summary>
    /// 总条数
    /// </summary>
    private int Total = 0;
    /// <summary>
    /// 加载
    /// </summary>
    private bool Loading = false;

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

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

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

    private StateDialogModel model = new StateDialogModel();

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

    /// <summary>
    /// 打开编辑弹窗
    /// </summary>
    /// <param name="type">类型：1：新增；2：编辑；3：删除</param>
    /// <param name="media">广告信息</param>
    /// <returns></returns>
    private async Task ShowDialog(int type, SiteOutput? media)
    {
        await searchSitesAsync();
        model = new StateDialogModel();
        model.Type = type;
        model.Sites = Sites;
        if(type == 2 || type == 3)
        {
            model.Address = media?.Address ?? "";
            model.Name = media?.Name ?? "";
            model.Contact = media?.Contact ?? "";
            model.Id = media?.Id;
        }

        isOpen = true;
    }
    
    /// <summary>
    /// 编辑弹窗信息回调
    /// </summary>
    /// <param name="model"></param>
    private async Task OnDialogCallback(StateDialogModel model)
    {
        switch (model.Type)
        {
            case 1:
                await _Repository.InsertAsync(model.ToCompany());
                break;
            case 2:
                SiteEntity siteEntity = model.ToCompany();
                await _Repository.Context.Updateable(siteEntity).
                    UpdateColumns(it => new { it.Name,it.Address, it.Contact,it.ParentId})
                    .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<SiteOutput> query)
        => await Query();

    /// <summary>
    /// 查
    /// </summary>
    /// <returns></returns>
    private async Task Query()
    {
        Loading = true;
        string? searchName = filterData.siteName;
        int pageSize = filterData.pageSize;
        int offset = (filterData.currentPage - 1) * pageSize;
        string whereClause = string.IsNullOrEmpty(searchName)
                    ? ""
                     : "WHERE st.name LIKE CONCAT('%', @searchName, '%')";

        if (Global.CurrentUser.Account != "admin")
        {
            long siteID = Global.CurrentUser.SiteId;
            //string countSql = $@"
            //        WITH RECURSIVE site_tree AS(
            //                   SELECT id,parent_id
            //                   FROM site_entity
            //                   WHERE id = @siteID
            //                   UNION ALL
            //                   SELECT s.id,s.parent_id
            //                   FROM site_entity s
            //                   INNER JOIN site_tree t ON s.parent_id = t.id
            //        )
            //        SELECT 
            //            st.id  AS Id,st.parent_id AS ParentID,
            //            p.name AS ParentName
            //        FROM site_tree st
            //        LEFT JOIN site_entity p ON st.parent_id = p.id
            //        {whereClause};
            //";
            //Total = await _Repository.Context.Ado.GetIntAsync(countSql, new { siteID, searchName });
            Total = await _Repository.AsQueryable()
                .Where(it => it.Id == siteID || it.ParentId == siteID)
                .WhereIF(filterData.siteName.IsNotNullOrEmpty(), it => it.Name.Contains(filterData.siteName))
                .CountAsync();

            string dataSql = $@"
                    WITH RECURSIVE site_tree AS(
                               SELECT id,parent_id,name,address,contact,create_time
                               FROM site_entity
                               WHERE id = @siteID
                               UNION ALL
                               SELECT s.id,s.parent_id,s.name,s.address,s.contact,s.create_time
                               FROM site_entity s
                               INNER JOIN site_tree t ON s.parent_id = t.id
                    )
                    SELECT 
                        st.id AS Id,st.parent_id AS ParentID,st.name AS Name ,st.address AS Address,st.contact AS Contact,st.create_time AS CreateTime,
                        p.name AS ParentName
                    FROM site_tree st
                    LEFT JOIN site_entity p ON st.parent_id = p.id
                    {whereClause}
                    ORDER BY st.create_time DESC
                    LIMIT @pageSize OFFSET @offset;
            ";
            _DataSource = await _Repository.Context.Ado.SqlQueryAsync<SiteOutput>(dataSql, new { siteID, searchName, pageSize, offset });
        } 
        else
        {
            //,st.name,st.address,st.contact,st.create_time
            //string countSql = $@"
            //        SELECT 
            //            st.id,st.parent_id,
            //            p.name AS ParentName
            //        FROM site_entity st
            //        LEFT JOIN site_entity p ON st.parent_id = p.id
            //        {whereClause};
            //";

            //Total = await _Repository.Context.Ado.GetIntAsync(countSql, new {  searchName });
            Total = await _Repository.AsQueryable()
                .WhereIF(filterData.siteName.IsNotNullOrEmpty(), it => it.Name.Contains(filterData.siteName))
                .CountAsync();

            string dataSql = $@"
                    SELECT 
                        st.id AS Id,st.parent_id AS ParentID,st.name AS Name ,st.address AS Address,st.contact AS Contact,st.create_time AS CreateTime,
                        p.name AS ParentName
                    FROM site_entity st
                    LEFT JOIN site_entity p ON st.parent_id = p.id
                    {whereClause}
                    ORDER BY st.create_time DESC
                    LIMIT @pageSize OFFSET @offset;
            ";
            _DataSource = await _Repository.Context.Ado.SqlQueryAsync<SiteOutput>(dataSql, new { searchName, pageSize, offset });
        }

        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 _Repository.AsQueryable()
                .Where(it => it.ParentId == 0)
                .Select<SiteInfo>()
                .ToListAsync();
        }
        else
        {
            Sites = await _Repository.AsQueryable()
                .Where(it => it.Id == 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; }
    }
}
