using AI.Platform.Core;
using AI.Platform.Core.Entity.Media;
using AI.Platform.Page.Pages.Media.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.Media;

public partial class Media
{
    /// <summary>
    /// 
    /// </summary>
    [Inject] NavigationManager NavigationManager { get; set; }
    /// <summary>
    /// 数据库仓储
    /// </summary>
    [Inject] SqlSugarRepository<MediaEntity> _Repository { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] IJSRuntime IJSRuntime { get; set; }
    /// <summary>
    ///
    /// </summary>
    private ITable _Table;
    /// <summary>
    ///
    /// </summary>
    private IEnumerable<SystemMenu> _SelectedRows = [];
    /// <summary>
    /// 广告列表信息
    /// </summary>
    private List<MediaEntity> _DataSource;
    /// <summary>
    ///
    /// </summary>
    private int Pi = 1;
    /// <summary>
    ///
    /// </summary>
    private int Ps = 20;

    /// <summary>
    /// 总条数
    /// </summary>
    private int Total = 0;
    /// <summary>
    /// 加载
    /// </summary>
    private bool Loading = false;

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

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

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

    private MediaDialogModel model = new MediaDialogModel();

    /// <summary>
    /// 打开编辑弹窗
    /// </summary>
    /// <param name="type">类型：1：新增；2：编辑；3：删除</param>
    /// <param name="media">广告信息</param>
    /// <returns></returns>
    private async Task ShowDialog(int type,MediaEntity? media)
    {
        model = new MediaDialogModel();
        model.Type = type;
        if(type == 2 || type == 3)
        {
            model.Id = media?.Id;
            model.GroupID = media?.GroupID ?? "";
            model.BusinessUnitID = media?.BusinessUnitID ?? "";
            model.FileName = media?.FileName ?? "";
            model.GuidFileName = media?.GuidFileName ?? "";
            model.FileExtension = media?.FileExtension ?? "";
            model.SavePath = media?.LocalPath ?? "";
            model.MediaUploader = media?.Uploader ?? "";
            model.StartTime = media?.StartTime;
            model.EndTime = media?.EndTime;
            model.EffecitiveTime = media?.EffectiveTime;
            model.FailureTime = media?.FailureTime;
            model.MediaState = media?.MediaState ?? 0;
            model.MachineStateList = JsonSerializer.Deserialize<List<string>>(media?.MachineState ?? "[]");
            model.Remark = media?.Remark ?? "";
        }

        isOpen = true;
    }
    
    /// <summary>
    /// 编辑弹窗信息回调
    /// </summary>
    /// <param name="model"></param>
    private async Task OnDialogCallback(MediaDialogModel model)
    {
        Console.WriteLine(model);
        switch (model.Type)
        {
            case 1:
                await _Repository.InsertAsync(model.ToCompany());
                break;
            case 2:
                MediaEntity mediaEntity = model.ToCompany();
                await _Repository.Context.Updateable(mediaEntity).
                    UpdateColumns(it => new { it.MediaState,it.MachineState, it.StartTime, it.EndTime ,it.EffectiveTime,it.FailureTime,it.Remark })
                    .ExecuteCommandAsync();
                break;
            case 3:
                await _Repository.DeleteByIdAsync(model.Id);
                if(model.SavePath.IsNotNullOrEmpty())
                {
                    File.Delete(model.SavePath);
                }
                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<MediaEntity> query)
        => await Query();

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

        var query =  _Repository.AsQueryable()
            .WhereIF(filterData.searchFileName != null, it => it.FileName.Contains(filterData.searchFileName))
            .WhereIF(filterData.searchMediaUploader != null, it => it.Uploader.Contains(filterData.searchMediaUploader))
            .WhereIF(filterData.searchMediaState != null && filterData.searchMediaState != -1, it => it.MediaState == filterData.searchMediaState)
            .WhereIF(filterData.searchStartTime != null && filterData.searchEndTime != null, it => it.StartTime >= filterData.searchStartTime && it.EndTime <= filterData.searchEndTime)
            .WhereIF(filterData.searchEffecitiveTime != null && filterData.searchFailureTime != null, it => it.EffectiveTime >= filterData.searchEffecitiveTime && it.FailureTime <= filterData.searchFailureTime)
            .WhereIF(filterData.searchStartEditTime != null && filterData.searchEndEditTime != null, it => it.EditTime >= filterData.searchStartEditTime && it.EditTime <= filterData.searchEndEditTime);

        if (filterData.searchMachineStateList.IsNotNullOrEmpty())
        {
            Expressionable<MediaEntity> expressionable = Expressionable.Create<MediaEntity>();
            foreach (var state in filterData.searchMachineStateList)
            {
                var jsonQuoted = $"\"{state}\"";
                expressionable.Or(m => m.MachineState.Contains(jsonQuoted));
            }
            query = query.Where(expressionable.ToExpression());
        }

        Total = await query.CountAsync();
        _DataSource = await query
            .OrderByDescending(it => it.EditTime)
            .Skip((filterData.currentPage - 1) * filterData.pageSize)
            .Take(filterData.pageSize)
            .ToListAsync();

        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()
    {

    }

    /// <summary>
    /// 单选选择器选择事件
    /// </summary>
    /// <param name="value">选择的值</param>
    private void OnSelectItemChange(string value)
    {
        Console.WriteLine(value);
        int state = -1;
        int.TryParse(value, out state);
        filterData.searchMediaState = state;
    }

    /// <summary>
    /// 多选选择器选择事件
    /// </summary>
    /// <param name="values">选择的值</param>
    private void OnSelectItemsChange(IEnumerable<string> values)
    {
        Console.WriteLine(values);
        filterData.searchMachineStateList = values.ToList();
    }

    /// <summary>
    /// 日期选择器选择回调
    /// </summary>
    /// <param name="value">选择的日期</param>
    /// <param name="type">1：有效时间段；2：更新时间；3：播放时段</param>
    private void onDateChage(DateRangeChangedEventArgs<DateTime?[]> value,int type)
    {
        switch (type)
        {
            case 1:
                filterData.searchEffecitiveTime = value.Dates[0];
                filterData.searchFailureTime = value.Dates[1];
                break;
            case 2:
                filterData.searchStartEditTime = value.Dates[0];
                filterData.searchEndEditTime = value.Dates[1];
                break;
            case 3:
                DateTime? startTime = value.Dates[0];
                DateTime? endTime = value.Dates[1];
                filterData.searchStartTime = startTime?.Hour;
                filterData.searchEndTime = endTime?.Hour;
                break;
        }
        
    }

    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? searchFileName { set; get; }

        /// <summary>
        /// 要查找文件开始播放时间
        /// </summary>
        public int? searchStartTime { set; get; }

        /// <summary>
        /// 要查找文件结束播放时间
        /// </summary>
        public int? searchEndTime { set; get; }

        /// <summary>
        /// 要查找文件生效时间
        /// </summary>
        public DateTime? searchEffecitiveTime { set; get; }

        /// <summary>
        /// 要查找文件失效时间
        /// </summary>
        public DateTime? searchFailureTime { set; get; }

        /// <summary>
        /// 要查找文件油机状态
        /// </summary>
        public List<string>? searchMachineStateList { set; get; }

        /// <summary>
        /// 要查找文件广告状态 0:禁用；1：可用
        /// </summary>
        public int? searchMediaState { set; get; }

        /// <summary>
        /// 要查找文件上传人
        /// </summary>
        public string? searchMediaUploader { set; get; }

        /// <summary>
        /// 根据文件修改时间范围查找（开始时间）
        /// </summary>
        public DateTime? searchStartEditTime { set; get; }

        /// <summary>
        /// 根据文件修改时间范围查找（结束时间）
        /// </summary>
        public DateTime? searchEndEditTime { set; get; }

    }
}
