using BPA.Model;
using BPA.SingleDevice.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

        public MaterialBindingViewModel(ILogService logService)
        {
            this.logService = logService;

            GetMaterialBindInfos();

            #region 修改物料绑定对话框之前的。
            //AddCommand = new(async () =>
            //    {
            //        var content = new SetBindingMaterialView();
            //        var para = await Dialog.Show(content, new Parameters(), "绑定物料", (d) => { }, async (d, o) =>
            //        {
            //            if (o is MaterialBindTB rm)
            //            {
            //                if (!IsEmploy(rm.DeviceNum, rm.WarehouseNum))
            //                {
            //                    string id = Guid.NewGuid().ToString();
            //                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //                    var materialName = await GetMaterialNameAsync(rm.MaterialCode);
            //                    if (materialName is not null)
            //                    {
            //                        var materialbd = new MaterialBindTB()
            //                        {
            //                            Id = id,
            //                            MaterialName = materialName,
            //                            MaterialCode = rm.MaterialCode,
            //                            DeviceNum = rm.DeviceNum,
            //                            WarehouseNum = rm.WarehouseNum,
            //                            LastModified = time
            //                        };
            //                        SqlHelper.GetInstance.AddAsync(materialbd).Result.OnSuccess(() =>
            //                        {
            //                            GetMaterialBindInfos();
            //                            Message.Success("MaterialBindingView", $"绑定物料【{materialName}】成功。");
            //                            logService.LogUserInfo($"成功绑定物料【{materialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】。");
            //                        }).OnFail(s =>
            //                        {
            //                            logService.LogDebugInfo($"绑定物料【{materialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败，信息【{s}】");
            //                            Message.Error("MaterialBindingView", $"绑定物料【{materialName}】失败。");
            //                        });
            //                    }
            //                    else
            //                    {
            //                        Message.Error("MaterialBindingView", $"绑定物料失败，未找到【{rm.MaterialCode}】对应的物料。");
            //                    }
            //                }
            //                else
            //                {
            //                    Message.Error("MaterialBindingView", $"绑定物料失败，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】已经被占用。");
            //                }
            //            }
            //        });
            //    }); 



            //EditCommand = new(async (o) =>
            //{
            //    if (o != null && !string.IsNullOrEmpty(o.ToString()))
            //    {
            //        var index = MaterialBindInfos.ToList().FindIndex(p => p.Id == o.ToString());
            //        if (index >= 0)
            //        {
            //            var para = await Dialog.Show(new SetBindingMaterialView(), new MaterialBindTB()
            //            {
            //                MaterialName = MaterialBindInfos[index].MaterialName,
            //                MaterialCode = MaterialBindInfos[index].MaterialCode,
            //                DeviceNum = MaterialBindInfos[index].DeviceNum,
            //                WarehouseNum = MaterialBindInfos[index].WarehouseNum,
            //                Id = MaterialBindInfos[index].Id,
            //            }, "物料绑定编辑", (d) => { }, async (d, o) =>
            //            {
            //                if (o is MaterialBindTB rm)
            //                {
            //                    var list = MaterialBindInfos.Where(m => m.DeviceNum == rm.DeviceNum && m.WarehouseNum == rm.WarehouseNum);
            //                    foreach (var item in list)
            //                    {
            //                        if (item.Id != rm.Id)
            //                        {
            //                            Message.Error("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】失败，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】已被占用。");
            //                            return;
            //                        }
            //                    }
            //                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //                    var mbtb = new MaterialBindTB()
            //                    {
            //                        Id = MaterialBindInfos[index].Id,
            //                        MaterialName = await GetMaterialNameAsync(rm.MaterialCode),
            //                        MaterialCode = rm.MaterialCode,
            //                        DeviceNum = rm.DeviceNum,
            //                        WarehouseNum = rm.WarehouseNum,
            //                        LastModified = time
            //                    };
            //                    SqlHelper.GetInstance.UpdateAsync(mbtb).Result.OnSuccess(() =>
            //                    {
            //                        GetMaterialBindInfos();
            //                        Message.Success("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】成功。");
            //                        logService.LogUserInfo($"成功修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】。");
            //                    }).OnFail(s => {
            //                        logService.LogDebugInfo($"修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败，信息:【{s}】。");
            //                        Message.Error("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败。");
            //                    });
            //                }
            //            });
            //        }
            //    }
            //});
            #endregion

            #region 修改物料绑定对话框之后的。
            AddCommand = new(async () =>
            {
                var content = new SetBindMaterialView();
                var para = await Dialog.Show(content, new Parameters(),
                    "绑定物料", (d) => { },
                    (d, o) =>
                {
                    if (o is MaterialBindTB rm)
                    {
                        if (!IsEmploy(rm.DeviceNum, rm.WarehouseNum))
                        {
                            string id = Guid.NewGuid().ToString();
                            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                            var materialName = rm.MaterialName;
                            var materialbd = new MaterialBindTB()
                            {
                                Id = id,
                                MaterialName = materialName,
                                MaterialCode = rm.MaterialCode,
                                DeviceNum = rm.DeviceNum,
                                WarehouseNum = rm.WarehouseNum,
                                LastModified = time
                            };
                            SqlHelper.GetInstance.AddAsync(materialbd).Result.OnSuccess(() =>
                            {
                                GetMaterialBindInfos();
                                Message.Success("MaterialBindingView", $"绑定物料【{materialName}】成功。");
                                logService.LogUserInfo($"成功绑定物料【{materialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】。");
                            }).OnFail(s =>
                            {
                                logService.LogDebugInfo($"绑定物料【{materialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败，信息【{s}】");
                                Message.Error("MaterialBindingView", $"绑定物料【{materialName}】失败。");
                            });
                        }
                        else
                        {
                            Message.Error("MaterialBindingView", $"绑定物料失败，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】已经被占用。");
                        }
                    }
                });
            });

            EditCommand = new(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = MaterialBindInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var para = await Dialog.Show(new SetBindMaterialView(), new MaterialBindTB()
                        {
                            MaterialName = MaterialBindInfos[index].MaterialName,
                            MaterialCode = MaterialBindInfos[index].MaterialCode,
                            DeviceNum = MaterialBindInfos[index].DeviceNum,
                            WarehouseNum = MaterialBindInfos[index].WarehouseNum,
                            Id = MaterialBindInfos[index].Id,
                        }, "物料绑定编辑", (d) => { },  (d, o) =>
                        {
                            if (o is MaterialBindTB rm)
                            {
                                var list = MaterialBindInfos.Where(m => m.DeviceNum == rm.DeviceNum && m.WarehouseNum == rm.WarehouseNum);
                                foreach (var item in list)
                                {
                                    if (item.Id != rm.Id)
                                    {
                                        Message.Error("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】失败，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】已被占用。");
                                        return;
                                    }
                                }
                                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                var mbtb = new MaterialBindTB()
                                {
                                    Id = MaterialBindInfos[index].Id,
                                    MaterialName =rm.MaterialName,
                                    MaterialCode = rm.MaterialCode,
                                    DeviceNum = rm.DeviceNum,
                                    WarehouseNum = rm.WarehouseNum,
                                    LastModified = time
                                };
                                SqlHelper.GetInstance.UpdateAsync(mbtb).Result.OnSuccess(() =>
                                {
                                    GetMaterialBindInfos();
                                    Message.Success("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】成功。");
                                    logService.LogUserInfo($"成功修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】。");
                                }).OnFail(s => {
                                    logService.LogDebugInfo($"修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败，信息:【{s}】。");
                                    Message.Error("MaterialBindingView", $"修改绑定物料【{rm.MaterialName}】，设备号【{rm.DeviceNum}】，通道号【{rm.WarehouseNum}】失败。");
                                });
                            }
                        });
                    }
                }
            });
            #endregion




            RemoveCommand = new(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = MaterialBindInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var result = await MessageBoxR.Confirm("是否删除该数据?");
                        if (result == System.Windows.MessageBoxResult.Yes)
                        {
                            SqlHelper.GetInstance.DeleteAsync<MaterialBindTB>(o.ToString()).OnSuccess(() =>
                            {
                                var code = MaterialBindInfos[index].MaterialCode;
                                GetMaterialBindInfos();
                                Message.Success("MaterialBindingView", $"删除物料【{code}】成功。");
                                logService.LogUserInfo($"成功移除物料【{code}】。");
                            }).OnFail(s => {
                                logService.LogDebugInfo($"删除物料失败，信息:【{s}】");
                                Message.Error("MaterialBindingView", $"删除物料失败。"); });
                        }
                    }
                }
            });

            RefreshCommand = new(() => GetMaterialBindInfos());
        }

        private async Task<string> GetMaterialNameAsync(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException(code, "MaterialCode为null");
            }
            var result = await SqlHelper.GetInstance.GetListAsync<MaterialTB>();
            if (result.IsSuccess)
            {
                var b= result.Content.FirstOrDefault(m => m.MaterialCode == code);
                if (b is not null)
                {
                    return b.Name;
                }
            }
            return null;
            
        }

        private async void GetMaterialBindInfos()
        {
            var result=  await SqlHelper.GetInstance.GetListAsync<MaterialBindTB>();
            result.OnSuccess((s) =>
            {
                MaterialBindInfos.Clear();
                var list = s.OrderBy(m => m.DeviceNum).ThenBy(m => m.WarehouseNum);
                foreach (var item in list)
                {
                    MaterialBindInfos.Add(item);
                }
            });
        }

        private bool IsEmploy(int deviceNum,int chNum)
        {
            return MaterialBindInfos.Any(m => m.DeviceNum == deviceNum && m.WarehouseNum == chNum);
        }

        public ObservableCollection<MaterialBindTB> MaterialBindInfos { get; set; } = new();

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

        public BPARelayCommand RefreshCommand { get; set; }
    }
}
