using LogoForceTestApp.Modules.MainModule.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using Repository;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;

namespace LogoForceTestApp.Modules.MainModule.ViewModels
{
    public class SopPageViewModel : BindableBase
    {
        IDialogService dialogService;//弹窗
        private readonly IRepository repository;
        private readonly IEventAggregator eventAggregator;

        public string ProName { get; set; }

        public DelegateCommand AddCommand1 { get; set; }
        public DelegateCommand AddCommand2 { get; set; }
        public DelegateCommand AddCommand3 { get; set; }
        public DelegateCommand SaveSopCmm { get; set; }
        public DelegateCommand ClearChart { get; set; }
        public ObservableCollection<LocalFile> FileInfos { get; set; }
        public ObservableCollection<LocalFile2> FileInfos2 { get; set; }
        public ObservableCollection<LocalFile3> FileInfos3 { get; set; }

        public DelegateCommand AddPic { get; set; }

        public SopPageViewModel(IDialogService dialogService, IRepository repository, IEventAggregator eventAggregator)
        {
            FileInfos = new ObservableCollection<LocalFile>();
            FileInfos2 = new ObservableCollection<LocalFile2>();
            FileInfos3 = new ObservableCollection<LocalFile3>();
            AddCommand1 = new DelegateCommand(Add1);
            AddCommand2 = new DelegateCommand(Add2);
            AddCommand3 = new DelegateCommand(Add3);
            ClearChart = new DelegateCommand(ClearCha);
            AddPic = new DelegateCommand(OpenPicFile);
            this.dialogService = dialogService;
            this.repository = repository;
            this.eventAggregator = eventAggregator;
            SaveSopCmm = new DelegateCommand(SaveSop);
        }

        public void ClearCha()
        {
            FileInfos.Clear();
            FileInfos2.Clear();
            FileInfos3.Clear();
            System.Windows.Controls.DataGrid dataGrid = new System.Windows.Controls.DataGrid();
            dataGrid.Items.Clear();
        }
        private void SaveSop()
        {
            Task.Run(() =>
            {
                #region 数据库之间的关联
                //SopFile sopFile = new SopFile();

                //sopFile.ProductName = ProName;
                //sopFile.ID = Guid.NewGuid();
                //repository.Add(sopFile);
                ////sopFile.LocalFile3Db = localFile3Dbs;
                ////sopFile.LocalFile2Db = localFile2Dbs;
                ////sopFile.LocalFileDb = localFileDbs;
                //foreach (var item in localFile3Dbs)
                //{
                //    item.SopFile=sopFile;
                //    repository.Update(item);
                //}
                //foreach (var item in localFile2Dbs)
                //{
                //    item.SopFile = sopFile;
                //    repository.Update(item);
                //}
                //foreach (var item in localFileDbs)
                //{
                //    item.SopFile = sopFile;
                //    repository.Update(item);
                //}
                #endregion

                GenaralFile genaralFile = new GenaralFile();
                genaralFile.FileInfos = FileInfos.ToList();
                genaralFile.FileInfos2 = FileInfos2.ToList();
                genaralFile.FileInfos3 = FileInfos3.ToList();
                genaralFile.ProductName = ProName;

                var json = JsonConvert.SerializeObject(genaralFile, Formatting.Indented);
                string sPath = @"D:\作业指导书\";
                if (!Directory.Exists(sPath))
                {
                    Directory.CreateDirectory(sPath);
                }
                var path = sPath + $"{ProName}.json";
                using (var sw = new StreamWriter(path))
                {
                    sw.Write(json);
                    sw.Close();
                }

                System.Windows.Forms.MessageBox.Show("保存成功:" + ProName);
                eventAggregator.GetEvent<FileChangedEvent>().Publish();

                //CopyFolder(sPath, "//192.168.1.11/作业指导书/");
            });
        }

        #region 添加表格

        //private List<LocalFile3Db> localFile3Dbs = new();
        //private List<LocalFile2Db> localFile2Dbs = new();
        //private List<LocalFileDb> localFileDbs = new();
        private void Add3()
        {
            dialogService.ShowDialog("ChartPage3", c =>
            {
                var param = c.Parameters;
                var equipment = param.GetValue<string>("c1");
                var before = param.GetValue<string>("c2");
                var inn = param.GetValue<string>("c3");
                var after = param.GetValue<string>("c4");
                var lookOut = param.GetValue<string>("c5");
                if (c.Result.ToString() == "OK")
                {
                    FileInfos3.Add(new LocalFile3
                    {
                        Equipment = equipment,
                        Before = before,
                        Inn = inn,
                        After = after,
                        LookOut = lookOut
                    });

                    //var sopFile = repository.GetFirstDefault<SopFile>(c => c.ProductName == ProName);
                    //var cha3 = new LocalFile3Db()
                    //{
                    //    Id = Guid.NewGuid(),
                    //    Equipment = equipment,
                    //    Before = before,
                    //    Inn = inn,
                    //    After = after,
                    //    LookOut = lookOut,
                    //};
                    //localFile3Dbs.Add(cha3);
                    //repository.Add(cha3);
                }
            });
        }
        private void Add2()
        {
            dialogService.ShowDialog("ChartPage2", c =>
            {
                var param = c.Parameters;
                var num = param.GetValue<string>("c1");
                var materialNum = param.GetValue<string>("c2");
                var materialName = param.GetValue<string>("c3");
                var count = param.GetValue<string>("c4");
                var unit = param.GetValue<string>("c5");
                if (c.Result.ToString() == "OK")
                {
                    FileInfos2.Add(new LocalFile2
                    {
                        Num = num,
                        MaterialNum = materialNum,
                        MaterialName = materialName,
                        Count = count,
                        Unit = unit
                    });

                    //var cha2 = new LocalFile2Db()
                    //{
                    //    Id = Guid.NewGuid(),
                    //    Num = num,
                    //    MaterialNum = materialNum,
                    //    MaterialName = materialName,
                    //    Count = count,
                    //    Unit = unit
                    //};
                    //localFile2Dbs.Add(cha2);
                    //repository.Add(cha2);
                }
            });
        }
        private void Add1()
        {
            dialogService.ShowDialog("ChartPage1", c =>
            {
                var param = c.Parameters;
                var fileNum = param.GetValue<string>("c1");
                var edition = param.GetValue<string>("c2");
                var date = param.GetValue<string>("c3");
                var type = param.GetValue<string>("c4");
                var people = param.GetValue<string>("c5");
                var name = param.GetValue<string>("c6");
                var process = param.GetValue<string>("c7");
                var workTime = param.GetValue<string>("c8");
                if (c.Result.ToString() == "OK")
                {
                    FileInfos.Add(new LocalFile
                    {
                        FileNum = fileNum,
                        Edition = edition,
                        Date = date,
                        Type = type,
                        People = people,
                        Name = name,
                        Process = process,
                        WorkTime = workTime
                    });

                    //var cha1 = new LocalFileDb()
                    //{
                    //    Id = Guid.NewGuid(),
                    //    FileNum = fileNum,
                    //    Edition = edition,
                    //    Date = date,
                    //    Type = type,
                    //    People = people,
                    //    Name = name,
                    //    Process = process,
                    //    WorkTime = workTime
                    //};
                    //localFileDbs.Add(cha1);
                    //repository.Add(cha1);
                }
            });
        }
        #endregion

        #region 显示图片
        public void OpenPicFile()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            string imgPath = "";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                imgPath = dialog.SelectedPath + @"\";
                LoadPicture(imgPath);
            }
        }

        private ObservableCollection<PictureInfo> imageList = new ObservableCollection<PictureInfo>();
        public ObservableCollection<PictureInfo> ImageList
        {
            get { return imageList; }
            set { imageList = value; }
        }


        object lockobj = new object();

        /// <summary>
        /// 加载缺陷图片
        /// </summary>
        /// <param name="strPath"></param>
        public void LoadPicture(string strPath)
        {
            ImageList.Clear();


            BindingOperations.EnableCollectionSynchronization(ImageList, lockobj);

            string folderFullName = strPath;//图片文件夹路径

            Task.Run(() =>
            {
                DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);
                var res = TheFolder.GetFiles();

                for (int i = 0; i < res.Length; i++)
                {
                    PictureInfo pictureInfo = new PictureInfo();
                    pictureInfo.PicturePath = res[i].DirectoryName + @"\" + res[i].Name;
                    Uri uri = new Uri(pictureInfo.PicturePath, UriKind.Absolute);
                    //BitmapImage myimg =ImageProcess.GetBitImage(uri);
                    pictureInfo.Info = res[i].Name;
                    ImageList.Add(pictureInfo);
                }
            });
        }
        #endregion

        /// <summary>
        /// 复制文件夹中内容
        /// </summary>
        /// <param name="sourceFolder">源文件夹</param>
        /// <param name="destFolder">目标文件夹</param>
        public static void CopyFolder(string sourceFolder, string destFolder)
        {
            // 检查目标文件夹是否存在,如果不存在则创建
            if (!Directory.Exists(destFolder))
            {
                Directory.CreateDirectory(destFolder);
            }

            // 获取源文件夹中的所有文件的完整路径
            string[] files = Directory.GetFiles(sourceFolder);

            // 遍历所有文件
            foreach (string file in files)
            {
                // 获取文件信息
                FileInfo fileInfo = new FileInfo(file);

                // 构造目标文件的路径
                string newPath = Path.Combine(destFolder, fileInfo.Name);

                // 将文件复制到目标文件夹,如果目标文件已存在则覆盖
                File.Copy(file, newPath, true);
            }

            // 获取源文件夹中的所有子文件夹
            string[] dirs = Directory.GetDirectories(sourceFolder);

            // 递归复制所有子文件夹
            foreach (string dir in dirs)
            {
                // 获取子文件夹的名称
                string dirName = Path.GetFileName(dir);

                // 构造目标子文件夹的路径
                string newDirPath = Path.Combine(destFolder, dirName);

                // 递归调用自身来复制子文件夹
                CopyFolder(dir, newDirPath);
            }
        }


    }

    public class LocalFile : BindableBase
    {
        public string FileNum { get; set; }
        public string Edition { get; set; }
        public string Date { get; set; }
        public string Type { get; set; }
        public string People { get; set; }
        public string Name { get; set; }
        public string Process { get; set; }
        public string WorkTime { get; set; }

    }
    public class LocalFile2 : BindableBase
    {
        public string Num { get; set; }
        public string MaterialNum { get; set; }
        public string MaterialName { get; set; }
        public string Count { get; set; }
        public string Unit { get; set; }

    }
    public class LocalFile3 : BindableBase
    {
        public string Equipment { get; set; }
        public string Before { get; set; }
        public string Inn { get; set; }
        public string After { get; set; }
        public string LookOut { get; set; }

    }


    public class GenaralFile
    {
        public string ProductName { get; set; }
        public List<LocalFile> FileInfos { get; set; }
        public List<LocalFile2> FileInfos2 { get; set; }
        public List<LocalFile3> FileInfos3 { get; set; }

    }
}