using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uBIMEarthTools.Utils;
using LocationPoint = Autodesk.Revit.DB.LocationPoint;

namespace uBIMEarthTools.Commands
{
    [Transaction(TransactionMode.Manual)]
    public class PileCheckCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uIDocument = commandData.Application.ActiveUIDocument;
            Document document = uIDocument.Document;
            if (!(document.ActiveView is View3D))
            {
                MessageBox.Show($"请在三维视图下操作");
                return Result.Failed;
            }

            //Document linkDocument = new FilteredElementCollector(document, document.ActiveView.Id).OfClass(typeof(RevitLinkInstance)).Cast<RevitLinkInstance>().FirstOrDefault().GetLinkDocument();

            //List<ElementId> bearingStratum = new FilteredElementCollector(document).OfClass(typeof(FamilyInstance)).Where(x => x.Name.Contains("强风化")).Select(x => x.Id).ToList();


            //ReferenceIntersector referenceIntersector = new ReferenceIntersector(document.ActiveView as View3D);
            //referenceIntersector.FindReferencesInRevitLinks = true;
            //referenceIntersector.SetTargetElementIds(bearingStratum);

            Transaction trans = new Transaction(document);
            trans.Start("Create Instance");


            //var els = new FilteredElementCollector(document, document.ActiveView.Id).OfClass(typeof(FamilyInstance)).Cast<FamilyInstance>().Where(x => x.Symbol.FamilyName.Contains("桩"));
            string txt = File.ReadAllText(@"C:\OneDrive\项目\xxx\data\lengths.txt");
            var pts = txt.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string a = string.Empty;

            foreach (var pt in pts)
            {
                var elpt = pt.Split(':', ',');
                var fi = document.GetElement(new ElementId(int.Parse(elpt[0]))) as FamilyInstance;
                if (fi.Symbol.FamilyName == "桩 - 混凝土圆形桩")
                {
                    var length = double.Parse(elpt[1]) + fi.LookupParameter("直径").AsDouble() * 1.5;
                    fi.LookupParameter("深度").Set(length);
                }
            }

            //foreach (FamilyInstance item in els)
            //{
            //    LocationPoint point = item.Location as LocationPoint;
            //    a += item.Id.IntegerValue + ":" + point.Point.X + "," + point.Point.Y + "," + point.Point.Z + "\r\n";
            //    //var referenceWithContexts = referenceIntersector.Find(point.Point, -XYZ.BasisZ);
            //    //var el = referenceWithContexts.Select(x => document.GetElement(x.GetReference())).ToList();
            //    //var length = referenceWithContexts.Proximity + item.LookupParameter("直径").AsDouble() * 1.5;

            //    //item.LookupParameter("深度").Set(length);
            //}
            //File.WriteAllText(@"C:\OneDrive\项目\xxx\data\lengths.txt", a);
            trans.Commit();

            return Result.Succeeded;
        }

        /// <summary>
        /// 创建模型线圆
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="centerPoint"></param>
        /// <returns></returns>
        public static ElementId CreateModelArc(Document doc, XYZ centerPoint, double r)
        {
            XYZ normal = new XYZ(0, 0, 1);
            double radius = r / 304.8;
            double startAngle = 0;
            double endAngle = 2 * Math.PI;

            Plane geomPlane = Plane.CreateByNormalAndOrigin(normal, XYZ.Zero);
            Arc arc = Arc.Create(geomPlane, radius, startAngle, endAngle);
            SketchPlane sketch = SketchPlane.Create(doc, geomPlane);
            ModelArc modelArc = doc.Create.NewModelCurve(arc, sketch) as ModelArc;
            ElementTransformUtils.MoveElement(doc, modelArc.Id, centerPoint);
            return modelArc.Id;
        }
    }
}
