/* ==============================================================================
 * 功能描述：ElementExtend  
 * 创 建 者：Garrett
 * 创建日期：2018/5/28 16:41:22
 * ==============================================================================*/

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using SAGA.DotNetUtils;
using SAGA.DotNetUtils.Extend;
using SAGA.RevitUtils.Extends;
using ServiceRevitLib.Common;

namespace ServiceRevitLib.Extend
{
    /// <summary>
    /// ElementExtend
    /// </summary>
    public static class ElementExtend
    {
        /// <summary>
        /// 判断元素是否是开始元素
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static bool IsStart(this Element element)
        {
            return (element.GetParameterString(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS) ?? string.Empty).StartsWith(MBIConst.StartFlag);
        }
        /// <summary>
        /// 判断是否为设备 设备族为4位
        /// ATVR - 多联机 - 室内机 - 双向气流 - 天花板嵌入式
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        public static bool IsEquipment(this Element element)
        {
            bool result = false;
            //if (element is Wall wall)
            //{//添加幕墙识别
            //    result = wall.WallType.Kind == WallKind.Curtain;

            //}
            //else
            if (element is FamilyInstance fi)
            {
                var family = fi.GetFamilyName();
                result = Regex.IsMatch(family, $"{RegexConstPattern.IsEquip}");
            }

            return result;
        }
        /// <summary>
        /// 判断是否为设备部件 设备族为6位
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        public static bool IsEquipmentPart(this Element element)
        {
            bool result = false;
            if (element is FamilyInstance fi)
            {
                var family = fi.GetFamilyName();
                result = Regex.IsMatch(family, $"{RegexConstPattern.IsEquipPart}");
            }

            return result;
        }
        /// <summary>
        /// 广义mbi设备包含设备和部件
        /// </summary>
        /// <param name="family"></param>
        /// <returns></returns>
        public static bool IsMbiEquipment(this Element element)
        {
            return element.IsEquipment()||element.IsEquipmentPart();
        }
        /// <summary>
        /// 判断是否为信标
        /// </summary>
        /// <param name="elem"></param>
        /// <returns></returns>
        public static bool IsBeacon(this Element elem)
        {
            var family = elem.GetFamilyName();
            return family != null && (Regex.IsMatch(family, RegexConstPattern.IsBeacon));
        }

        /// <summary>
        /// 判断是否为空间，判断周长是否为零
        /// 如果周长为零，是删除的空间
        /// </summary>
        /// <param name="elem"></param>
        /// <param name="ischeckzero">是否检查周长为零</param>
        /// <returns></returns>
        public static bool IsSpace(this Element elem, bool ischeckzero = true)
        {
            var isspace = false;
            if (elem is Space space)
            {
                //空间比较特殊，周长为零就相当于删除
                isspace = !ischeckzero || !(space.IsDeleteSpace());
                //限制所用空间的阶段
                //isspace = isspace && space.IsPhase1Space();
            }

            return isspace;
        }
        /// <summary>
        /// 获取MBI的定位点
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static XYZ GetLocationPointMBIXYZ(this Element element)
        {
            ////定位点不可靠，未来可能会更改为Box的中心点
            //XYZ bimXyz = element.GetLocationPoint();
            //if (element is FamilyInstance fi)
            //{
            //    var family = fi.GetFamily();
            //    if (family.IsInPlace)
            //    {
            //        bimXyz = fi.GetBoxCenter();
            //    }
            //}
            //定位点改为Box中心点 
            XYZ bimXyz = element.GetBoxCenter();

            return bimXyz;
        }
        /// <summary>
        /// 获取MBI存储的位置信息
        /// </summary>
        /// <returns></returns>
        public static string GetLocationPointMBI(this Element element)
        {
            string str = ",,";
            XYZ bimXyz = element.GetLocationPointMBIXYZ();
            if (bimXyz != null)
            {
                str = bimXyz.FromApi().ToString(null);
            };
            //JObject jObject = new JObject();
            //jObject.Add("X", bimXyz.X);
            //jObject.Add("Y", bimXyz.Y);
            //jObject.Add("Z", bimXyz.Z);
            //return (new JArray(jObject)).ToString();
            return str;
        }
        /// <summary>
        /// 获取MBI存储的位置信息
        /// </summary>
        /// <returns></returns>
        public static XYZ ToXyz(this string xyzstr)
        {
            XYZ xyz = null;
            var strs = xyzstr.Split(',');
            if (strs.Length == 3)
            {
                xyz = new XYZ(strs[0].ToDouble(), strs[1].ToDouble(), strs[2].ToDouble());
            }
            //JObject jObject = new JObject();
            //jObject.Add("X", bimXyz.X);
            //jObject.Add("Y", bimXyz.Y);
            //jObject.Add("Z", bimXyz.Z);
            //return (new JArray(jObject)).ToString();
            return xyz;
        }

        /// <summary>
        /// 获取设备的种族类型编码 ATFC
        /// 族名称的命名规则：ATFC-风机盘管
        /// </summary>
        /// <returns></returns>
        public static string GetFamilyCode(this Element element)
        {          
            string code = "";
            if (element is FamilyInstance fi)
            {
                string familyName = fi.GetFamilyName();
                if (familyName == null) return code;
                //族名称的命名规则：ATFC-风机盘管
                int index = familyName.IndexOf('-');
                if (index != -1 && index + 1 != familyName.Length)
                    code = familyName.Substring(0, familyName.IndexOf('-'));
                //移除前面和后面的空格
                code = code.Trim();
            }

            return code;
        }

        public static string GetFamilyName(this Element element)
        {
            return element.GetFamily()?.Name;
        }
        /// <summary>
        /// 获取关联的空间
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        public static Space GetReferenceSpace(this Element element, List<Space> spaces = null)
        {
            Space space = null;
            if (element is FamilyInstance fi)
            {
                space = fi.Space;
                if (space != null) return space;
                if (spaces == null)
                    spaces = fi.Document.GetSpaces().Where(t => t.IsValidObject).ToList();
                var origin1 = fi.GetLocationPointMBIXYZ();
                foreach (Space tempSpace in spaces)
                {
                    //没有Space属性，取定位点，判断定位点所在空间
                    if (tempSpace.IsPointInSpace(origin1))
                    {
                        space = tempSpace;
                        break;
                    }
                }
            }

            return space;
        }

        /// <summary>
        /// 获取部件所关联的设备
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        public static Element GetPartParent(this Element element)
        {
            string code = element?.GetFamily().Name.Substring(0, 4); ;
            if (code.IsNullOrEmpty()) return null;
            //构件所关联的设备
            var parentInst = element?.Document.GetElements(new ElementIntersectsElementFilter(element))
                .FirstOrDefault(t => !t.Id.IsEqual(element.Id) && t.GetFamilyCode() == code);
            return parentInst;
        }
    }
}
