using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using SouthSmart.GISService.Infrastructure.Module;
using SouthSmart.GISService.Infrastructure.WebGIS;
using SouthSmart.GISService.Models;
using Path = System.IO.Path;

namespace SouthSmart.GISService.Areas.TopoAnalyse.Controllers
{
    public class TopoOperateController : Controller
    {
        // GET: TopoAnalyse/TopoOperate
        public ActionResult UpLoadCADFile()
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                string path = CreatePath();
                var files = Request.Files;
                if (files != null)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        var file = files[i];
                        Stream stream = file.InputStream;
                        if (stream.Length > 0)
                        {
                            string fileName = Common.GuId();
                            fileName += ".dwg";
                            var savePath = Path.Combine(path, fileName);
                            file.SaveAs(savePath);
                            LicenseProduct.InitialLincese();
                            var featureDataSet = FeatureClassHelper.OpenCAD(path).Find(t => t.Name == fileName);
                            var featureClassList = FeatureClassHelper.GetAllFeatureClass(featureDataSet);
                            for (int j = 0; j < featureClassList.Count; j++)
                            {
                                var featureClass = featureClassList[j];
                                var features = FeatureClassHelper.GetAllFeature(featureClass);
                                if (features.Count > 0 &&
                                    features[0].Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                {
                                    successMessage.Data = ArcgisJsonHelper.FeaturesConvert2WebGISPolygon(features);
                                    successMessage.Mess = "操作成功！";
                                    successMessage.Count = successMessage.ID = 1;
                                }
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            //读取DWG文件，获取几何图形GEOJSON
            return new JsonResult() { Data = successMessage };
        }
        public ActionResult SearchByCaseNum(string caseNum, string cads = "") //正常.DWG|%%jobfiles%/201810/201810160012/overlap.dwg::重叠.DWG|%%jobfiles%/201810/201810160012/notoverlap.dwg
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                string path = ConfigurationManager.AppSettings["CADTempFilePath"];
                string month = caseNum.Substring(0, 6);
                path = Path.Combine(path, month);
                path = Path.Combine(path, caseNum);
                if (cads != "")
                {
                    cads = HttpUtility.UrlDecode(cads);
                }
                //删除多余文件
                string[] filterArr = cads.Split(':');
                var listFilter = new List<string>();
                for (int i = 0; i < filterArr.Length; i++)
                {
                    if (filterArr[i] != "")
                        listFilter.Add(filterArr[i].Substring(filterArr[i].LastIndexOf('/') + 1));
                }
                if (listFilter.Count > 0)
                {
                    DirectoryInfo root = new DirectoryInfo(path);
                    FileInfo[] files = root.GetFiles();
                    for (int i = 0; i < files.Length; i++)
                    {
                        if (!listFilter.Contains(files[i].Name))
                            System.IO.File.Delete(files[i].FullName);
                    }
                }

                LicenseProduct.InitialLincese();
                var featureDataSet = FeatureClassHelper.OpenCAD(path);
                var listGeoCollection = new List<List<WebGISPolygon>>();
                for (int i = 0; i < featureDataSet.Count; i++)
                {
                    var featureClassList = FeatureClassHelper.GetAllFeatureClass(featureDataSet[i]);
                    for (int j = 0; j < featureClassList.Count; j++)
                    {
                        var featureClass = featureClassList[j];
                        if (featureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            var features = FeatureClassHelper.GetAllFeature(featureClass);
                            if (features.Count > 0)
                            {
                                listGeoCollection.Add(ArcgisJsonHelper.FeaturesConvert2WebGISPolygon(features));
                            }
                        }
                    }
                }
                successMessage.Data = listGeoCollection;
                successMessage.Mess = "操作成功！";
                successMessage.Count = successMessage.ID = 1;
                return successMessage.NewJson();
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            //读取DWG文件，获取几何图形GEOJSON
        }
        //重叠部分
        public ActionResult OverLapAnalyse(string caseNum)
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                LicenseProduct.InitialLincese();


                SDEHelper helper = new SDEHelper();
                helper.OpenData();
                var featureclass = helper.OpenFeatureClassByName(ConfigurationManager.AppSettings["OverLapAnalyseLayer"]);

                var listGeometry = new List<IGeometry>();
                //依据传入的实例编号加载所有图形数据到Geometry
                var geomtrys = LoadAllGeometryByCaseNum(caseNum);
                //判断他交
                foreach (var geometry in geomtrys)
                {
                    var features = featureclass.FeatureSearch(geometry, esriSpatialRelEnum.esriSpatialRelIntersects).Except(featureclass.FeatureSearch(geometry, esriSpatialRelEnum.esriSpatialRelTouches)).ToList();

                    foreach (var feature in features)
                    {
                        var polygon = geometry.IntersectResult(feature.Shape);
                        listGeometry.Add(polygon);
                    }
                }

                var listGeoCollection = new List<List<WebGISPolygon>>();
                var listGeoItem = listGeometry.GeometryConvert2WebGISPolygon();
                if (listGeoItem.Count > 0)
                {
                    listGeoCollection.Add(listGeoItem);
                }

                successMessage.Data = listGeoCollection;
                successMessage.Mess = listGeoItem.Count == 0 ? "分析成功，未发现重叠部分" : "分析成功,与目标图层中相交【" + listGeoItem.Count + "】";
                successMessage.Count = successMessage.ID = 1;
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            return successMessage.NewJson();
        }
        //超出部分
        public ActionResult ExceedAnalyse(string caseNum)
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                LicenseProduct.InitialLincese();
                //依据传入的实例编号加载所有图形数据到Geometry
                var geomtrys = LoadAllGeometryByCaseNum(caseNum);

                SDEHelper helper = new SDEHelper();
                helper.OpenData();
                var featureclass = helper.OpenFeatureClassByName(ConfigurationManager.AppSettings["ExceedAnalyseLayer"]);

                var listGeometry = new List<IGeometry>();

                //判断他交
                foreach (var geometry in geomtrys)
                {
                    //判断是否有相交
                    var featuresRelOverlaps = featureclass.FeatureSearch(geometry, esriSpatialRelEnum.esriSpatialRelIntersects);
                    if (featuresRelOverlaps.Count == 0)
                    {
                        //判断是否在图层内
                        var featuresRelWithin = featureclass.FeatureSearch(geometry, esriSpatialRelEnum.esriSpatialRelWithin);
                        //#todo:esriSpatialRelWithin
                        //Returns a feature if its shape wholly contains the search geometry.Valid for all shape type combinations. 
                        if (featuresRelWithin.Count == 0)
                        {
                            listGeometry.Add(geometry);
                        }
                    }
                    else
                    {
                        foreach (var feature in featuresRelOverlaps)
                        {
                            var polygon = geometry.DifferenceResult(feature.Shape);
                            listGeometry.Add(polygon);
                        }
                    }
                }

                var listGeoCollection = new List<List<WebGISPolygon>>();
                var listGeoItem = listGeometry.GeometryConvert2WebGISPolygon();
                if (listGeoItem.Count > 0)
                {
                    listGeoCollection.Add(listGeoItem);
                }

                successMessage.Data = listGeoCollection;
                successMessage.Mess = listGeoItem.Count == 0 ? "未发现超出部分" : "分析成功！与目标图层中超出部分【" + listGeoItem.Count + "】";
                successMessage.Count = successMessage.ID = 1;
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            return successMessage.NewJson();
        }
        //缝隙分析
        public ActionResult GapAnalyse(string caseNum)
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                LicenseProduct.InitialLincese();

                //依据传入的实例编号加载所有图形数据到Geometry
                var geomtrys = LoadAllGeometryByCaseNum(caseNum);

                SDEHelper helper = new SDEHelper();
                helper.OpenData();
                var featureclass = helper.OpenFeatureClassByName(ConfigurationManager.AppSettings["OverLapAnalyseLayer"]);

                var listGeometry = new List<IGeometry>();  //用于记录没有缝隙的几何图形
                var unionList = new List<IGeometry>(); //已经分析过的图形

                //判断他交
                for (int i = 0; i < geomtrys.Count; i++)
                {
                    bool hasGap = false;
                    var geometry = geomtrys[i];
                    if (unionList.Contains(geometry)) continue;
                    //判断自交
                    for (int j = 0; j < geomtrys.Count; j++)
                    {
                        if (i == j) continue;
                        var isTouch = geometry.TouchResult(geomtrys[j]);
                        if (isTouch)
                        {
                            unionList.Add(geomtrys[j]);
                            geometry = geometry.UnionResult(geomtrys[j]);
                        }
                    }
                    var features = featureclass.FeatureSearch(geometry, esriSpatialRelEnum.esriSpatialRelTouches); //衔接关系
                    if (features.Count == 0)  //有衔接
                    {
                        //判断缓冲
                        var bufferDistance = Convert.ToDouble(ConfigurationManager.AppSettings["BufferDistance"]);
                        var gapGeom = geometry.BufferResult(bufferDistance);
                        var features2 = featureclass.FeatureSearch(gapGeom, esriSpatialRelEnum.esriSpatialRelIntersects); //衔接关系
                        if (features2.Count > 0) hasGap = true;
                    }
                    if (hasGap)
                    {
                        listGeometry.Add(geometry);
                    }
                }
                var listGeoCollection = new List<List<WebGISPolygon>>();
                var listGeoItem = listGeometry.GeometryConvert2WebGISPolygon();
                if (listGeoItem.Count > 0)
                {
                    listGeoCollection.Add(listGeoItem);
                }

                successMessage.Data = listGeoCollection;
                successMessage.Mess = "分析成功！";
                successMessage.Mess += listGeometry.Count > 0 ? "存在缝隙" : "未存在缝隙";
                successMessage.Count = successMessage.ID = 1;
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            return successMessage.NewJson();
        }
        //数据入库
        public ActionResult DataPush(string caseNum, CHXX chxx)
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                LicenseProduct.InitialLincese();
                SDEHelper helper = new SDEHelper();
                helper.OpenData();
                var featureclass = helper.OpenFeatureClassByName(ConfigurationManager.AppSettings["DataPushLayer"]);
                //删除现有要素
                featureclass.DeleteFeatures("YWH='" + (chxx.YWH ?? caseNum) + "'");
                //插入要素
                Hashtable param = new Hashtable
                {
                    {"YWH", chxx.YWH??caseNum},
                    {"GHWH", chxx.GHWH},
                    {"TJH", chxx.TJH},
                    {"SQR", chxx.SQR},
                    {"ZL", chxx.ZL},
                    {"WYCLCG", chxx.WYCLCG},
                    {"CHCGT", chxx.CHCGT},
                    {"DJT", chxx.DJT},
                    {"ZDT", chxx.ZDT},
                    {"DDB", chxx.DDB},
                    {"MJTZD", chxx.MJTZD},
                    {"QTCG", chxx.QTCG},
                };
                //依据传入的实例编号加载所有图形数据到Geometry
                var geomtrys = LoadAllGeometryByCaseNum(chxx.YWH ?? caseNum);
                for (int i = 0; i < geomtrys.Count; i++)
                {
                    featureclass.InsertFeature(geomtrys[i], param);
                }
                successMessage.Mess = "数据入库成功！";
                successMessage.Count = successMessage.ID = 1;
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            return successMessage.NewJson();
        }
        //
        public ActionResult DataDelete(string caseNum)
        {
            SuccessMessage successMessage = new SuccessMessage();
            successMessage.Count = -1;
            successMessage.ID = -1;
            successMessage.Mess = "操作失败！";
            try
            {
                LicenseProduct.InitialLincese();
                SDEHelper helper = new SDEHelper();
                helper.OpenData();
                var featureclass = helper.OpenFeatureClassByName(ConfigurationManager.AppSettings["DataPushLayer"]);
                //删除现有要素
                featureclass.DeleteFeatures("YWH='" + caseNum + "'");

                successMessage.Mess = "数据删除成功！";
                successMessage.Count = successMessage.ID = 1;
            }
            catch (Exception ex)
            {
                successMessage.Mess = ex.ToString();
                return successMessage.NewJson();
            }
            return successMessage.NewJson();
        }

        #region 私有方法

        private string CreatePath()
        {
            StringBuilder path = new StringBuilder();

            path.Append(Server.MapPath("~/App_Data/uploads") + @"\");
            return path.ToString();
        }

        //依据传入的实例编号加载所有图形数据到Geometry
        private List<IGeometry> LoadAllGeometryByCaseNum(string caseNum)
        {
            var geomtrys = new List<IGeometry>();

            string path = ConfigurationManager.AppSettings["CADTempFilePath"];
            string month = caseNum.Substring(0, 6);
            path = Path.Combine(path, month);
            path = Path.Combine(path, caseNum);
            var featureDataSet = FeatureClassHelper.OpenCAD(path);

            for (int i = 0; i < featureDataSet.Count; i++)
            {
                var featureClassList = FeatureClassHelper.GetAllFeatureClass(featureDataSet[i]);
                for (int j = 0; j < featureClassList.Count; j++)
                {
                    var featureClass = featureClassList[j];
                    if (featureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        string name = featureClass.AliasName;
                        if (name != "Polygon") continue; //默认不区分图层加载所有的多边形
                        var features = FeatureClassHelper.GetAllFeature(featureClass);
                        if (features.Count > 0)
                        {
                            for (int k = 0; k < features.Count; k++)
                            {
                                geomtrys.Add(features[k].Shape);
                            }
                        }
                    }
                }
            }
            return geomtrys;
        }
        //基于递归的缝隙分析

        #endregion
    }
}