using BPA.SingleDevice.Services;
using System.DirectoryServices.Protocols;

namespace BPA.SingleDevice.ViewModel
{
    public class RawMaterialManagementViewModel : NotifyBase
    {
        private readonly ILogService logService;

        public RawMaterialManagementViewModel(ILogService logService)
        {
            this.logService = logService;
            Task.Run(() =>
            {
                SqlHelper.GetInstance.GetListAsync<RawMaterTB>().Result.OnSuccess(s =>
                {
                    var result = s.OrderBy(r=>r.DeviceNum).ThenBy(r=>r.WarehouseNum);
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        foreach (var item in result)
                        {
                            RawMaterInfos.Add(new RawMaterInfo(item.Id, item.Name, item.DeviceNum, item.WarehouseNum, item.LastModified));
                        }
                    });
                });
            });
            
            AddCommand = new BPARelayCommand(async () =>
            {
                var content = new AddRawMaterialDialogView();
                var para = await Dialog.Show(content, new Parameters(), "添加原料", (d) => { }, (d, o) =>
                {
                    if (o is RawMaterResult rm)
                    {
                        string id = Guid.NewGuid().ToString();
                        string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        SqlHelper.GetInstance.AddAsync(new RawMaterTB()
                        {
                            Id = id,
                            Name = rm.Name,
                            DeviceNum = rm.DeviceNum,
                            WarehouseNum = rm.ChNum,
                            LastModified = time
                        }).Result.OnSuccess(() =>
                        {
                            RawMaterInfos.Add(new RawMaterInfo(id, rm.Name, rm.DeviceNum, rm.ChNum, time));
                            Message.Success("RawMaterialManagementView", $"添加物料【{rm.Name}】成功。");
                            logService.LogUserInfo($"成功添加物料【{rm.Name}】，设备号【{rm.DeviceNum}】，通道号【{rm.ChNum}】。");
                        }).OnFail(s => { Message.Error("RawMaterialManagementView", $"添加失败：{s}"); });
                    }
                });
            });

            EditCommand = new BPARelayCommand<object>(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = RawMaterInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var para = await Dialog.Show(new AddRawMaterialDialogView(), new RawMaterResult()
                        {
                            Name = RawMaterInfos[index].Name,
                            DeviceNum = RawMaterInfos[index].DeviceNum,
                            ChNum = RawMaterInfos[index].WarehouseNum,
                            Id = RawMaterInfos[index].Id,
                        }, "原料编辑", (d) => { }, (d, o) =>
                        {
                            if (o is RawMaterResult rm)
                            {
                                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                SqlHelper.GetInstance.UpdateAsync(new RawMaterTB()
                                {
                                    Id = RawMaterInfos[index].Id,
                                    Name = rm.Name,
                                    DeviceNum = rm.DeviceNum,
                                    WarehouseNum = rm.ChNum,
                                    LastModified = time
                                }).Result.OnSuccess(() =>
                                {
                                    RawMaterInfos[index].Name = rm.Name;
                                    RawMaterInfos[index].DeviceNum = rm.DeviceNum;
                                    RawMaterInfos[index].WarehouseNum = rm.ChNum;
                                    RawMaterInfos[index].LastModified = time;
                                    Message.Success("RawMaterialManagementView", $"修改物料【{rm.Name}】成功。");
                                    logService.LogUserInfo($"成功修改物料【{rm.Name}】，设备号【{rm.DeviceNum}】，通道号【{rm.ChNum}】。");
                                }).OnFail(s => { Message.Error("RawMaterialManagementView", $"修改失败：{s}"); });
                            }
                        });
                    }
                }
            });

            RemoveCommand = new BPARelayCommand<object>(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = RawMaterInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var result = await MessageBoxR.Confirm("是否删除该数据?");
                        if (result == System.Windows.MessageBoxResult.Yes)
                        {
                            SqlHelper.GetInstance.DeleteAsync<RawMaterTB>(o.ToString()).OnSuccess(() =>
                            {
                                var name = RawMaterInfos[index].Name;
                                RawMaterInfos.RemoveAt(index);
                                Message.Success("RawMaterialManagementView", $"删除物料【{name}】成功。");
                                logService.LogUserInfo($"成功移除物料【{name}】。");
                            }).OnFail(s => { Message.Error("RawMaterialManagementView", $"删除失败：{s}"); });
                        }
                    }
                }
            });

            RefreshCommand = new(() =>
            {
                RawMaterInfos.Clear();
                Task.Run(() =>
                {
                    SqlHelper.GetInstance.GetListAsync<RawMaterTB>().Result.OnSuccess(s =>
                    {
                        var result = s.OrderBy(r => r.DeviceNum).ThenBy(r => r.WarehouseNum);
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            foreach (var item in result)
                            {
                                RawMaterInfos.Add(new RawMaterInfo(item.Id, item.Name, item.DeviceNum, item.WarehouseNum, item.LastModified));
                            }
                        });
                    });
                });
            });
        }

        
        public ObservableCollection<RawMaterInfo> RawMaterInfos { get; set; } = new ObservableCollection<RawMaterInfo>();

        public BPARelayCommand AddCommand { get; set; }
        public BPARelayCommand SaveCommand { get; set; }
        public BPARelayCommand<object> CopyCommand { get; set; }
        public BPARelayCommand<object> EditCommand { get; set; }
        public BPARelayCommand<object> RemoveCommand { get; set; }

        public BPARelayCommand RefreshCommand { get; set; }
    }
}