EquipmentProptery_Index.razor 8.34 KB
@using AntDesign.TableModels
@using DataAcquisition.Common.Utils
@using DataAcquisition.DataAccess
@using DataAcquisition.Models
@using DataAcquisition.Services
@using LinqKit
@using Microsoft.EntityFrameworkCore
@using System.Linq.Expressions
@inject IDbContextFactory<DataContext> dbContextFactory;
@inject DataCacheService dataCacheService;
@inject ModalService _modalService
@inject IMessageService _message

<Flex Justify="space-between" Align="center">
    <Flex Justify="flex-start" Align="center" Gap="small">
        <AntDesign.Input DefaultValue="@string.Empty" @bind-Value="code">
            <AddOnBefore>编号</AddOnBefore>
        </AntDesign.Input>
        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Search" @onclick="SearchEvent">搜索</Button>
        <Button Type="@ButtonType.Default" Icon="@IconType.Outline.Redo" @onclick="ResetEvent">重置</Button>
    </Flex>
    <Flex Justify="flex-end" Align="center" Gap="small">
        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Plus" @onclick="AddEvent">新增</Button>
        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Delete" Danger @onclick="BatchDeleteEvent">批量删除</Button>
    </Flex>
</Flex>

<Table @ref="detailTable"
       TItem="EquipmentProperty"
       DataSource="@equipmentProperties"
       Total="_total"
       @bind-PageIndex="_pageIndex"
       @bind-PageSize="_pageSize"
       @bind-SelectedRows="selectedRows"
       OnChange="EquipmentPropertyOnChange"
       Size="TableSize.Small"
       RowKey="x=>x.Id">
    <Selection Key="@(context.Id.ToString())" />
    <PropertyColumn Property="c=>c.Id" Hidden />
    <PropertyColumn Title="编号" Property="c=>c.Code" />
    <PropertyColumn Title="名称" Property="c=>c.Name" />
    <PropertyColumn Title="数据地址" Property="c=>c.DataAddress" />
    <PropertyColumn Title="数据类型" Property="c=>c.DataType" />
    <PropertyColumn Title="值" Property="c=>c.Value" />
    <PropertyColumn Title="是否启用" Property="c=>c.Enable">
        <Switch @bind-Value="@context.Enable" Disabled="true"></Switch>
    </PropertyColumn>
    <PropertyColumn Title="备注" Property="c=>c.Remark" />
    <PropertyColumn Title="创建时间" Property="c=>c.CreateTime" />
    <PropertyColumn Title="更新时间" Property="c=>c.UpdateTime" />
    <ActionColumn Title="操作">
        <Space>
            <SpaceItem>
                <Button Icon="@IconType.Outline.Edit" Size="@ButtonSize.Small" @onclick="()=>EditEvent(context.Id)">修改</Button>
                <Button Icon="@IconType.Outline.Delete" Size="@ButtonSize.Small" Danger @onclick="()=>DeleteEvent(context.Id)">删除</Button>
            </SpaceItem>
        </Space>
    </ActionColumn>
</Table>


<EquipmentProperty_Add @bind-Visible="@visible_add" EquipmentId="@EquipmentId" OnSubmitSuccess="AddEventSuccessCallback" />

<EquipmentProperty_Edit @bind-Visible="@visible_edit" EquipmentPropertyId="@equipmentPropteryId" OnSubmitSuccess="EditEventSuccessCallback" />

@code {
    [Parameter]
    public int EquipmentId { get; set; } = 0;

    int equipmentPropteryId = 0;

    ITable detailTable = null!;

    List<EquipmentProperty> equipmentProperties = new List<EquipmentProperty>();

    #region 搜索条件

    string code = string.Empty;

    #endregion

    IEnumerable<EquipmentProperty> selectedRows = null!;
    int _pageIndex = 1;
    int _pageSize = 10;
    int _total = 0;

    SystemLog log = SystemLog.Instance;

    bool visible_add = false;

    bool visible_edit = false;

    CancellationTokenSource Cancellation = new CancellationTokenSource();

    protected override Task OnParametersSetAsync()
    {
        Cancellation = new CancellationTokenSource();
        _pageIndex = 1;
        LoadData(_pageIndex, _pageSize);
        _ = InvokeAsync(async () =>
         {
     try
     {
         do
         {
             if (visible_add || visible_edit)
             {
                 await Task.Delay(1000);
                 continue;
             }
             var equipmentPropertiesCache = dataCacheService.Equipments.Find(x => x.Id == EquipmentId)?.EquipmentProperties.ToList() ?? new List<EquipmentProperty>();
             foreach (var item in equipmentProperties)
             {
                 var newItem = equipmentPropertiesCache.Find(x => x.Id == item.Id);
                 if (newItem is null) continue;
                 item.Value = newItem.Value ?? string.Empty;
                 item.UpdateTime = newItem.UpdateTime;
             }
             StateHasChanged();
             await Task.Delay(1000);
         } while (!Cancellation.IsCancellationRequested);
     }
     catch (Exception ex)
     {
         _ = _message.Error($"设备详细页面数据刷新异常:{ex.Message}");
     }
         });
        return base.OnParametersSetAsync();
    }

    public void EquipmentPropertyOnChange(QueryModel<EquipmentProperty> queryModel)
    {
        LoadData(queryModel.PageIndex, queryModel.PageSize, queryModel.SortModel);
    }

    public void SearchEvent()
    {
        LoadData(_pageIndex, _pageSize);
    }

    public void ResetEvent()
    {
        code = string.Empty;
    }

    private void LoadData(int index, int size, IList<ITableSortModel>? sortModels = null)
    {
        try
        {
            using var dbContext = dbContextFactory.CreateDbContext();
            var query = dbContext.EquipmentProperties.Where(QueryExpression());
            equipmentProperties = query.OrderBy(x => x.Id).Skip(((index - 1) * size)).Take(size).AsNoTracking().ToList();
            _total = query.Count();
        }
        catch (Exception ex)
        {
            _message.Error($"加载数据失败:{ex.Message}");
        }
    }

    private Expression<Func<EquipmentProperty, bool>> QueryExpression()
    {
        var filter = PredicateBuilder.New<EquipmentProperty>(x => x.EquipmentId == EquipmentId);
        if (!string.IsNullOrWhiteSpace(code))
        {
            filter = filter.And(x => x.Code.Contains(code));
        }
        return filter;
    }

    public void AddEvent()
    {
        visible_add = true;
    }

    public void AddEventSuccessCallback()
    {
        visible_add = false;
        LoadData(_pageIndex, _pageSize);
    }

    public void EditEvent(int id)
    {
        equipmentPropteryId = id;
        visible_edit = true;
    }

    public void EditEventSuccessCallback()
    {
        visible_edit = false;
        LoadData(_pageIndex, _pageSize);
    }

    RenderFragment icon = @<Icon Type="exclamation-circle" Theme="outline" />;

    public void DeleteEvent(int id)
    {
        _modalService.Confirm(new ConfirmOptions
            {
                Title = "确认删除选中的数据?",
                Icon = icon,
                OnOk = (e) =>
                {
                    try
                    {
                        using var context = dbContextFactory.CreateDbContext();
                        context.EquipmentProperties.Where(x => x.Id == id).ExecuteDelete();
                        _message.Success($"操作成功");
                        LoadData(_pageIndex, _pageSize);
                        StateHasChanged();
                    }
                    catch (Exception ex)
                    {
                        _message.Error($"操作出现异常:{ex.Message}");
                    }
                    return Task.CompletedTask;
                }
            });
    }

    public void BatchDeleteEvent()
    {
        if (selectedRows?.Any() != true)
        {
            _message.Warning($"未选中任何数据!");
            return;
        }
        _modalService.Confirm(new ConfirmOptions
            {
                Title = "确认删除选中的数据?",
                Icon = icon,
                OnOk = (e) =>
                {
                    try
                    {
                        using var context = dbContextFactory.CreateDbContext();
                        context.EquipmentProperties.Where(x => selectedRows.Select(e => e.Id).Contains(x.Id)).ExecuteDelete();
                        _message.Success($"操作成功");
                        LoadData(_pageIndex, _pageSize);
                        StateHasChanged();
                    }
                    catch (Exception ex)
                    {
                        _message.Error($"操作出现异常:{ex.Message}");
                    }
                    return Task.CompletedTask;
                }
            });
    }
}