using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BPA.SingleDevice.ViewModel
{
    public class RecipeManagementViewModel : NotifyBase
    {
        public RecipeManagementViewModel()
        {

            SqlHelper.GetInstance.GetListAsync<RecipeTB>().Result.OnSuccess(s =>
            {
                s.ForEach(item =>
                {
                    RecipeInfos.Add(new RecipeInfo() { Id = item.Id, IsEnable = item.IsEnable, Name = item.Name, LastModified = item.LastModified });
                });
            });

            AddCommand = new BPARelayCommand(async () =>
            {
                var content = new NewRecipeView();
                var para = await Dialog.Show(content, new Parameters(), "添加配方", (d) => { }, (d, o) =>
                {
                    if (o is Parameters par)
                    {
                        if (par.TryGetValue("Name", out string name) && par.TryGetValue("RawMater", out List<NewRecipeModel> rms))
                        {
                            string id = Guid.NewGuid().ToString();//配方ID
                            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                            //添加配方
                            SqlHelper.GetInstance.AddAsync(new RecipeTB()
                            {
                                Id = id,
                                Name = name,
                                LastModified = time,
                                IsEnable = true,
                            }).Result.OnSuccess(() =>
                            {
                                List<RecipeRawMaterTB> rrmtb = new List<RecipeRawMaterTB>();
                                rms.ForEach(item =>
                                {
                                    rrmtb.Add(new RecipeRawMaterTB() { Id = Guid.NewGuid().ToString(), RawMaterId = item.Id, RecipeId = id, Weight = item.Weight });
                                });
                                SqlHelper.GetInstance.AddAsync(rrmtb).Result.OnSuccess(() =>
                                {
                                    RecipeInfos.Add(new RecipeInfo() { Id = id, IsEnable = true, LastModified = time, Name = name });
                                }).OnFail(s => { Message.Error("RecipeManagementView", $"添加失败：{s}"); });
                            }).OnFail(s => { Message.Error("RecipeManagementView", $"添加失败：{s}"); });
                        }
                    }
                });
            });

            EditCommand = new BPARelayCommand<object>(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = RecipeInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var parameters = new Parameters();
                        List<NewRecipeModel> nrm = new List<NewRecipeModel>();
                        SqlHelper.GetInstance.GetRawMaterIds(RecipeInfos.ElementAt(index).Id).Result.OnSuccess((s) =>
                        {
                            s.ForEach(item =>
                            {
                                nrm.Add(new NewRecipeModel() { Id = item.RawMaterId, Weight = item.Weight });
                            });
                        });
                        parameters.Add("Name", RecipeInfos.ElementAt(index).Name);
                        parameters.Add("RawMater", nrm);
                        var para = await Dialog.Show(new NewRecipeView(), parameters, "配方编辑", (d) => { }, (d, resPar) =>
                        {
                            if (resPar is Parameters par)
                            {
                                if (par.TryGetValue("Name", out string name) && par.TryGetValue("RawMater", out List<NewRecipeModel> rms))
                                {
                                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                                    //添加配方
                                    SqlHelper.GetInstance.UpdateAsync(new RecipeTB()
                                    {
                                        Id = o.ToString(),
                                        Name = name,
                                        LastModified = time,
                                        IsEnable = RecipeInfos[index].IsEnable
                                    }).Result.OnSuccess(() =>
                                    {
                                        SqlHelper.GetInstance.DeleteRawMaterAsync(o.ToString()).Result.OnSuccess(() =>
                                        {
                                            List<RecipeRawMaterTB> rrmtb = new List<RecipeRawMaterTB>();
                                            rms.ForEach(item =>
                                            {
                                                rrmtb.Add(new RecipeRawMaterTB() { Id = Guid.NewGuid().ToString(), RawMaterId = item.Id, RecipeId = o.ToString(), Weight = item.Weight });
                                            });
                                            SqlHelper.GetInstance.AddAsync(rrmtb).Result.OnSuccess(() =>
                                            {
                                                RecipeInfos[index].Name = name;
                                                RecipeInfos[index].LastModified = time;
                                            }).OnFail(s => { Message.Error("RecipeManagementView", $"更新添加失败：{s}"); });
                                        }).OnFail(s => { Message.Error("RecipeManagementView", $"更新时删除失败：{s}"); });
                                    }).OnFail(s => { Message.Error("RecipeManagementView", $"更新失败：{s}"); });
                                }
                            }
                        });
                    }
                }
            });

            RemoveCommand = new BPARelayCommand<object>(async (o) =>
            {
                if (o != null && !string.IsNullOrEmpty(o.ToString()))
                {
                    var index = RecipeInfos.ToList().FindIndex(p => p.Id == o.ToString());
                    if (index >= 0)
                    {
                        var result = await MessageBoxR.Confirm("是否删除改数据?");
                        if (result == System.Windows.MessageBoxResult.Yes)
                        {
                            SqlHelper.GetInstance.DeleteAsync<RecipeTB>(o.ToString()).OnSuccess(() =>
                            {
                                SqlHelper.GetInstance.DeleteRawMaterAsync(o.ToString()).OnSuccess(() =>
                                {
                                    RecipeInfos.RemoveAt(index);
                                }).OnFail(s => { Message.Error("RawMaterialManagementView", $"删除失败：{s}"); });
                            }).OnFail(s => { Message.Error("RawMaterialManagementView", $"删除失败：{s}"); });
                        }
                    }
                }
            });

            RecipeInfo.EnableChange = (s =>
            {
                var index = RecipeInfos.ToList().FindIndex(p => p.Id == s);
                if (index >= 0)
                {
                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    SqlHelper.GetInstance.UpdateAsync(new RecipeTB()
                    {
                        Id = s,
                        Name = RecipeInfos[index].Name,
                        LastModified = time,
                        IsEnable = RecipeInfos[index].IsEnable
                    }).Result.OnSuccess(() =>
                    {
                        RecipeInfos[index].LastModified = time;
                    }).OnFail(s => { Message.Error("RecipeManagementView", $"更新失败：{s}"); });
                }
            });
        }

        public ObservableCollection<RecipeInfo> RecipeInfos { get; set; } = new ObservableCollection<RecipeInfo>();

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


    }
}
