using Autodesk.Revit.DB;
using ServiceRevitLib;
using System;
using System.IO;
using Newtonsoft.Json.Linq;
using SAGA.DotNetUtils.Extend;
using SAGA.DotNetUtils.Logger;
using System.Configuration;
using System.Diagnostics;
using System.Net;

//using RevitToJBim.Common;

namespace ExportStart
{
    class Program
    {
        static Program()
        {
            RevitCoreContext.Instance.Run();
        }
        [STAThread]
        static void Main(string[] args)
        {
            string command = null;
            string param = null;
            string path = null;
            if (args.Length > 0)
            {
                command = args[0];
            }
            if (args.Length > 1)
            {
                param = args[1];
            }
            if (args.Length > 2)
            {
                path = args[2];
            }
#if DEBUG
            if (string.IsNullOrWhiteSpace(command))
            {
                command = "DataExport";
                //command = "DataCheck";
                //path = @"E:\导出测试\testSpace.rvt";
                //path = @"E:\导出测试\系统图修改编码版\消防系统图模型第一版V1219.rvt";
                //path = @"E:\导出测试\无锡系统图1225\热源系统图模型第一版V1225.rvt";
                //path = @"D:\给排水系统图模型第一版V1225.rvt";
                //path = @"E:\1245.rvt";

                //path = @"C:\Users\SAGACLOUD\Desktop\海天中心项目_AM_T1_21F .rvt";
                //path = @"D:\1.rvt";
                //path = @"testdata\嘉明\F1.rvt";
                //path = @"testdata\万达\LGWDGC-Q-F01-ALL.rvt";

                //path = @"testdata\龙岗万达2020.12.10\LG-WDGC-B02-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LGWDGC-F01-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LG-WDGC-F03-ALL.rvt";
                //path = @"E:\LGWDGC-F01-ALL.rvt";
                path = @"E:\Develop\RevitProject\RevitPro\ServiceRevit-wanda\OutputDll\testdata\生命科学园\生命科学园2#地块201号楼B1模型文件v2.rvt";

                //path = @"testdata\龙岗万达2020.12.10\LG-WDGC-F06-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LGWDGC-Q-B01-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LGWDGC-Q-F02-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LGWDGC-Q-F05-ALL.rvt";
                //path = @"testdata\龙岗万达2020.12.10\LGWDGC-R0F-ALL.rvt";

                //path = @"testdata\万达\未通过\LG-WDGC-F03-ALL.rvt";
                //path = @"testdata\生命科学园\生命科学园2#地块201号楼B1模型文件v6.rvt";
                //path = @"testdata\亚投行\B1一期11.24.rvt";
                //path = @"testdata\前四项问题的对应模型\1#F4模型文件v5.rvt";
                //path = @"D:\安装包\CAD\测试模型\F4测试.rvt";
                JObject jObject = new JObject();
                //jObject.Add("ResultFileName", @"C:\Users\SAGACLOUD\AppData\Local\RevitService\Result_e26be2fd-2097-462b-bdd0-a2a86b616928.txt");
                jObject.Add("ResultFileName", @"D:\1.txt");
                jObject.Add("MBIName", "Pj1101051029");
                jObject.Add("ModelId", "a294b443403911eb9bae4d9eff3fa8d4");
                param = jObject.ToString();

                //path= @"E:\导出测试\延庆园-B1.rvt";
                //path = @"E:\导出测试\testR18.rvt";
                //path = @"E:\导出测试\testR16.rvt";
            }
#endif
            if (string.IsNullOrEmpty(command))
            {
                Log4Net.Debug("命令参数错误");
            }
            Log4Net.Info(command);
            Log4Net.Info(path);
            if (File.Exists(path) && Enum.TryParse(command, out CommandType commandType))
            {
                var app = RevitCoreContext.Instance.Application;
                string result = null;
                Console.WriteLine("Task StartTime:" + DateTime.Now);
                try
                {
                    var doc = app.OpenDocumentFile(path);
                    switch (commandType)
                    {
                        case CommandType.DataCheck:
                            result = Check(doc, param);
                            break;
                        case CommandType.DataExport:
                            result = Export(doc, param);
                            break;
                    }
                }
                catch (Exception e)
                {
                    JObject errorJObject = new JObject();
                    errorJObject.Add("ResultMsg", e.Message);
                    errorJObject.Add("Result", "Failure");
                    result = errorJObject.ToString();
                }
                SaveResult(param, result);
                Console.WriteLine("Task EndTime:" + DateTime.Now);
                RevitCoreContext.Instance.Stop();

                StartRevitSimplify(path, param);
            }

            //强制退出
            Environment.Exit(0);
        }
        /// <summary>
        /// 保存检查或导出的结果
        /// </summary>
        /// <param name="param"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private static void SaveResult(string param, string result)
        {
            try
            {
                JObject jObject = JObject.Parse(param);
                string key = "ResultFileName";
                string path = jObject[key].ToString();
                if (path.IsNotNullEmpty())
                {
                    var dir = Directory.GetParent(path);
                    if (!dir.Exists)
                        dir.Create();
                    File.AppendAllText(path, result);
                }
            }
            catch (Exception e)
            {
                Log4Net.Debug(e.StackTrace);
            }
        }
        static WebClient CreateDefaultClient()
        {
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json; charset=utf-8");
            return client;
        }
        static void StartRevitSimplify(string filePath, string param)
        {
            try
            {
                JObject jObject = JObject.Parse(param);
                var MBIName = jObject.GetValueEx("MBIName");//"Pj1101051029";//
                var ModelId = jObject.GetValueEx("ModelId");//"a294b443403911eb9bae4d9eff3fa8d4";//

                var url = ConfigurationManager.AppSettings["FloorServerUrl"];
                string fid = null;
                using (var client = CreateDefaultClient())
                {
                    client.Headers.Add("ProjectId", MBIName);
                    var json = "{\"Filters\":\"currentModelId = '" + ModelId + "'\"}";
                    var result = client.UploadString(url, json);
                    var jrst = JObject.Parse(result);
                    var jcontent = jrst["Content"].First;
                    var floorname = jcontent["FloorName"] + "";
                    if (string.IsNullOrEmpty(floorname)) return;
                    var folderid = jcontent["FolderId"] + "";
                    if (string.IsNullOrEmpty(folderid)) return;
                    fid = $"{MBIName}{folderid}{floorname}";
                }

                var outputDir = ConfigurationManager.AppSettings["OutputDir"];
                Console.WriteLine(DateTime.Now + " 准备执行轻量化:");
                Console.WriteLine($"filePath:{filePath}");
                Console.WriteLine($"fid:{MBIName}{ModelId}");
                string fullPath = ConfigurationManager.AppSettings["RevitSimplifyPath"];
                Process process = new Process();
                process.StartInfo.FileName = fullPath;//执行的exe路径
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(fullPath);
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.CreateNoWindow = false;
                //process.StartInfo.RedirectStandardInput = true;//打开流输入
                //process.StartInfo.RedirectStandardOutput = true;//打开流输出
                //process.StartInfo.RedirectStandardError = true;//打开错误流
                process.StartInfo.Arguments = $" InputFile={filePath} OutputDir={outputDir}/{MBIName}/{fid}";
                process.Start();//执行
                process.WaitForExit();
            }
            catch (Exception e)
            {
                Log4Net.Debug(e.StackTrace);
            }
        }
        enum CommandType
        {
            None = 0,
            DataCheck,
            DataExport
        }


        public static string Export(Document doc, string param)
        {
            string result = null;
            try
            {
                Console.WriteLine("Start Export");
                result = RevitToJBim.MbiExport.Export(doc, param);

                Console.WriteLine("End Export");
            }
            catch (Exception e)
            {
                Console.WriteLine("导出失败");
                Console.WriteLine(e.StackTrace);
            }

            return result;
        }


        public static string Check(Document doc, string param)
        {
            string result = null;
            try
            {
                Console.WriteLine("Start DataCheck");
                result = ServiceDataCheckTest.Check(doc);

                Console.WriteLine("End DataCheck");
            }
            catch (Exception e)
            {
                Console.WriteLine("导出失败");
                Console.WriteLine(e.StackTrace);
            }

            return result;
        }


    }
}
