//selector設定selected
$(document).on("change", "select", function () {
    $("option[value=" + this.value + "]", this)
        .attr("selected", true).siblings()
        .removeAttr("selected");

});

var wHeight = $("#viewDiv").height();
var dHeight = wHeight * 0.5;
var wWidth = $("#viewDiv").width();

var dialogPara1 = {
    autoOpen: false,
    dialogClass: 'dialogTitleClass',
    show: {
        effect: "blind",
        duration: 300
    },
    position: {
        my: "left top",
        at: "left+110px top+10px",
        of: "#viewDiv"
    },
    width: 800,
    height: dHeight,
    resizeStop: function (event, ui) {
        var content = $(".ui-dialog-content");
        content.css("width", "100%");
        content.css("height", "100%");
    }
};

// dialog-extend options
var dialogExtendOptions = {
    "maximizable": true,
    "minimizable": true,
    "collapsable": true
};
//巡查管理
$("#dialog_inspectMa_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//統計報表
$("#dialog_statisticReport_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//設備管理
$("#dialog_equipments_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);
//設備維修資料管理
dialogPara1.width = wWidth * 0.5;
dialogPara1.height = wHeight * 0.5;
$("#dialog_equipMTMain_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//設備詳細資料管理
dialogPara1.width = wWidth * 0.5;
dialogPara1.height = wHeight * 0.7;
$("#dialog_equipInspect_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//巡查管理-共管外部巡檢編輯
dialogPara1.width = wWidth * 0.6;
dialogPara1.height = wHeight * 0.75;
$("#dialog_outPipeInspect_Edit").dialog(dialogPara1).dialogExtend(dialogExtendOptions);
$("#dialog_inPipeInspect_Edit").dialog(dialogPara1).dialogExtend(dialogExtendOptions);
$("#dialog_equipInspect_Edit").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//設備異常巡檢資料視窗
$("#dialog_equipNewUnusual_query").dialog(dialogPara1).dialogExtend(dialogExtendOptions);


//設備維修單新增
$("#dialog_equipInspect_NewMTCase").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//設備維修完成登錄
$("#dialog_equipRepair_Complete").dialog(dialogPara1).dialogExtend(dialogExtendOptions);

//共同管道管理辦法
dialogPara1.position.my = "center";
dialogPara1.position.at = "center";
dialogPara1.width = 600;
dialogPara1.height = 400;
$("#dialog_PipeManageRule").dialog(dialogPara1);
//最新消息
$("#dialog_News").dialog(dialogPara1);


//判斷是否已經開啟
$(".a_jDialog").click(function () {
    var dialogID = $(this).data("dialogid");
    openDialogByID(dialogID);
});

function openDialogByID(dialogID) {
    var isOpen = $("#" + dialogID).dialog("isOpen");
    if (isOpen)
        $("#" + dialogID).dialog("close");
    else {
        $("#" + dialogID).dialog("open").dialog('moveToTop');

    }
}




require(["esri/config",
    "esri/WebMap",
    "esri/WebScene",
    "esri/views/MapView",
    "esri/views/SceneView",
    "esri/core/urlUtils",
    "esri/identity/OAuthInfo",
    "esri/identity/IdentityManager",
    "esri/widgets/Legend",
    "esri/widgets/Home",
    "esri/widgets/Fullscreen",
    "esri/widgets/Slider",
    "esri/widgets/BasemapGallery",
    "esri/widgets/LayerList",
    "esri/layers/GroupLayer",
    "esri/layers/FeatureLayer",
    "esri/widgets/FeatureTable",
    "esri/tasks/support/Query",
    "esri/layers/SceneLayer",
    "esri/widgets/Zoom",
    "esri/widgets/Compass",
    "esri/widgets/NavigationToggle",
    "esri/widgets/Slice",
    "esri/widgets/Search",
    "esri/geometry/Point",
    "esri/geometry/Polyline",
    "esri/webscene/Slide",
    "esri/symbols/WebStyleSymbol",
    "esri/widgets/DirectLineMeasurement3D",
    "esri/Graphic",
    "esri/core/watchUtils",
    "esri/widgets/Search/LocatorSearchSource",
    "esri/renderers/UniqueValueRenderer",
    "esri/geometry/geometryEngine",
    "esri/widgets/Expand",
    'dojo/text!./Scripts/CustomJson/DashboardServiceUrl.json',
    'dojo/text!./Scripts/CustomJson/DashboardLayerDefs.json',
    'dojo/text!./Scripts/CustomJson/DashboardGLayers.json',
    'dojo/text!./config.json'
], function (esriConfig, WebMap, WebScene, MapView, SceneView, urlUtils, OAuthInfo, esriId,
    Legend,
    Home,
    Fullscreen,
    Slider,
    BasemapGallery,
    LayerList,
    GroupLayer,
    FeatureLayer,
    FeatureTable,
    Query,
    SceneLayer,
    Zoom,
    Compass,
    NavigationToggle,
    Slice,
    Search,
    Point,
    Polyline,
    Slide,
    WebStyleSymbol,
    DirectLineMeasurement3D,
    Graphic,
    watchUtils,
    LocatorSearchSource,
    UniqueValueRenderer,
    geometryEngine,
    Expand,
    LayersJSON,
    DashboardLayerDefs,
    GroupLayersJSON,
    configJSON) {

        var pConfigJSON = $.parseJSON(configJSON);
        //設定portal網址
        esriConfig.portalUrl = pConfigJSON.portalUrl;


        pConfigJSON.httpProxy.rules.forEach(function (rule) {

            urlUtils.addProxyRule({
                urlPrefix: rule.urlPrefix,
                proxyUrl: rule.proxyUrl
            });

        });

        if (pConfigJSON.UseNTPCITCServer) {
            //資訊中心server驗證token
            esriId.registerToken({
                expires: 720000,
                server: pConfigJSON.NTPCITCServer,
                ssl: true,
                token: gtoken,
            });
        }

        //載入群組圖層JSON
        var pGroupLayersJSON = $.parseJSON(GroupLayersJSON);
    var pGroupLayers = pGroupLayersJSON.GLayers;
    var pDashboardLayerDefs = $.parseJSON(DashboardLayerDefs);
    var pLayerDefs = pDashboardLayerDefs.LayerDefs;
    var pEquipGLayer = pDashboardLayerDefs.GLayers;

   


        //取得圖層清單
        const fLayerList = [];
        const AddAllLayerList = [];
        var pLayersJSON = $.parseJSON(LayersJSON);
        var pDomainsJSON = pLayersJSON.domains;
        var pServiceUrlJSON = pLayersJSON.portallayers;

        var pITCServiceUrlJSON = pLayersJSON.itclayers;
        var pCFieldNames = pLayersJSON.fieldNames;


        //衝突分析變數
        const crossAnalysisSelectedFeatures = [];
        var roadExtentLayer = null;
        var roadExtentGraphics = null;
        var crossAnalysisHighlight = null;
        var pCrossAnalysisTable = null;

        for (let index = 0; index < pServiceUrlJSON.length; index++) {
            const element = pServiceUrlJSON[index];
            // const element = pServiceUrlJSON[0];

            $.getJSON(pConfigJSON.proxyUrl + "?" + element.serviceUrl + "?f=pjson", function (data) {


                data.layers.forEach(layerPara => {

                    var featureLayer = new FeatureLayer({
                        // URL to the service 電力配電管線
                        url: element.serviceUrl + "/" + layerPara.id,
                        id: element.groupID + "_" + layerPara.id
                    });

                    var foundRD = $(element.layerRenderers).filter(function (i, n) {
                        return n.id === layerPara.id
                    });
                    var LayerItem = {
                        groupID: element.groupID,
                        groupName: element.groupName,
                        groupVisible: element.groupVisible == false ? element.groupVisible : true,
                        id: layerPara.id,
                        name: layerPara.name,
                        fLayer: featureLayer
                    }

                    if (foundRD.length > 0) {
                        LayerItem.renderer = foundRD[0].renderer;
                        LayerItem.ElevationInfo = foundRD[0].ElevationInfo;
                        LayerItem.popupEnabled = foundRD[0].popupEnabled;

                        //區分哪些圖層是一開始就加入，哪些是需要範圍查詢的
                        if (foundRD[0].isAddAllLayer) {
                            AddAllLayerList.push(LayerItem);
                        } else {
                            fLayerList.push(LayerItem);
                        }
                    } else {
                        LayerItem.renderer = undefined;
                        LayerItem.ElevationInfo = undefined;
                        fLayerList.push(LayerItem);
                    }

                });

            })
        }


        for (let index = 0; index < pITCServiceUrlJSON.length; index++) {
            const element = pITCServiceUrlJSON[index];
            // const element = pServiceUrlJSON[0];

            $.getJSON(element.serviceUrl + "?f=pjson&token=" + gtoken, function (data) {

                //console.log(data);
                //console.log(JSON.stringify(data));
                var layeridlist = element.layerRenderers.map(obj => {
                    return obj.id
                })

                data.layers.forEach(layerPara => {

                    if (layeridlist.includes(layerPara.id)) {
                        var foundRD = $(element.layerRenderers).filter(function (i, n) {
                            return n.id === layerPara.id
                        });

                        var featureLayer = new FeatureLayer({
                            // URL to the service 電力配電管線
                            url: element.serviceUrl + "/" + layerPara.id,
                            id: foundRD[0].groupID + "_" + layerPara.id
                        });


                        var LayerItem = {
                            groupID: foundRD[0].groupID,
                            groupName: foundRD[0].groupName,
                            groupVisible: foundRD[0].groupVisible,
                            id: layerPara.id,
                            name: layerPara.name,
                            fLayer: featureLayer,
                            layerID: foundRD[0].groupID + "_" + layerPara.id
                        }

                        if (foundRD.length > 0) {
                            LayerItem.renderer = foundRD[0].renderer;
                            LayerItem.ElevationInfo = foundRD[0].ElevationInfo;
                            LayerItem.popupEnabled = foundRD[0].popupEnabled;

                            //區分哪些圖層是一開始就加入，哪些是需要範圍查詢的
                            if (foundRD[0].isAddAllLayer) {
                                AddAllLayerList.push(LayerItem);
                            } else {
                                fLayerList.push(LayerItem);
                            }
                        } else {
                            LayerItem.renderer = undefined;
                            LayerItem.ElevationInfo = undefined;
                            fLayerList.push(LayerItem);
                        }
                    }

                });

            })
        }




        //載入地圖
        displayItems();
        //初始化鳥瞰圖
        loadoverviewMap();

    function displayItems() {


        //MTXinBanAreaPipeScene
        var scene = new WebScene({
            portalItem: { // autocasts as new PortalItem()
                id: pConfigJSON.dashboardmap.itemId // ID of the WebScene on the on-premise portal
            }
        });

        var view = new SceneView({
            map: scene, // The WebScene instance created above
            container: "dashboardMapDiv"
        });


        window.view = view;


        view.ui.empty("top-left");


        view.ui.add(
            new Expand({
                view: view,
                content: new BasemapGallery({
                    view: view
                })
            }),
            "top-left"
        );



        function defineActions(event) {
            var item = event.item;

            if (item.layer.type !== "group") {
                item.actionsSections = [
                    [{
                        title: "縮放至圖層",
                        className: "esri-icon-zoom-out-fixed",
                        id: "full-extent"
                    }]
                ];
            }

        }


        var layerList = new LayerList({
            view: view,
            // executes for each ListItem in the LayerList
            listItemCreatedFunction: defineActions
        });

        layerList.on("trigger-action", function (event) {


            // Capture the action id.
            var id = event.action.id;

            if (id === "full-extent") {
                view.goTo(event.item.layer.fullExtent);
            }
        });

        view.ui.add(
            new Expand({
                view: view,
                content: layerList
            }),
            "top-left"
        );

        view.ui.add(
            new Expand({
                view: view,
                content: new Legend({
                    view: view
                })
            }),
            "top-left"
        );

        

        view.ui.add(
            new Home({
                view: view
            }),
            "top-left"
        );


        //view.ui.add(
        //    new Fullscreen({
        //        view: view
        //    }),
        //    "top-left"
        //);



        //新增量測工具
        var activeMeasureWidget = new DirectLineMeasurement3D({
            view: view
        });

        var pMeasureExpand = new Expand({
            view: view,
            container: document.getElementById("measureExpendDiv"),
            content: activeMeasureWidget
        });




        view.ui.add(
            pMeasureExpand,
            "top-left"
        );

        //量測工具開關控制
        $("#measureExpendDiv .esri-widget--button").click(function () {
            if (pMeasureExpand.expanded) {
                activeMeasureWidget.viewModel.newMeasurement();
            } else {
                activeMeasureWidget.viewModel.clearMeasurement();
            }
        });

        //pMeasureExpand.on("click", function () {

        //});
        
        

        view.when(function () {

            AddAllLayerList.forEach(eLayerPara => {

                var findedGroupLayer = view.map.findLayerById(eLayerPara.groupID);

                if (!findedGroupLayer) {

                    findedGroupLayer = new GroupLayer({
                        id: eLayerPara.groupID,
                        title: eLayerPara.groupName,
                        visible: eLayerPara.groupVisible == false ? eLayerPara.groupVisible : true,
                        visibilityMode: "independent"
                        //,layers: [USALayer, censusLayer]
                        //,opacity: 0.75
                    });

                    view.map.add(findedGroupLayer);
                }

                $.getJSON(pConfigJSON.proxyUrl + "?" + eLayerPara.fLayer.url + "/" + eLayerPara.fLayer.layerId + "?f=pjson", function (layerdef) {

                    layerdef = modifyLayerdef(layerdef);
                    if (layerdef.error) {
                        return;
                    }
                    var featureLayerPara = {
                        url: eLayerPara.fLayer.url + "/" + eLayerPara.fLayer.layerId,
                        id: eLayerPara.groupID + "_" + eLayerPara.id,
                        title: eLayerPara.name,
                        objectIdField: layerdef.objectIdField,
                        popupEnabled: eLayerPara.popupEnabled,
                        fields: layerdef.fields,
                        //popupTemplate: layerdef.defaultPopupTemplate,
                        geometryType: layerdef.geometryType,
                        renderer: eLayerPara.renderer
                    };

                    if (!featureLayerPara.renderer) {
                        if (layerdef.drawingInfo) {
                            featureLayerPara.renderer = layerdef.drawingInfo.renderer;
                        }
                    }

                    if (eLayerPara.popupEnabled) {

                        featureLayerPara.popupTemplate = {
                            title: "{" + layerdef.displayField + "}",
                            content: [
                                {
                                    type: "fields",
                                    fieldInfos: layerdef.fields.map(function (elem) { return { fieldName: elem.name, label: elem.alias } })
                                }
                            ]
                        };
                    }
                    var pAddAllLayer = new FeatureLayer(featureLayerPara);
                    pAddAllLayer = updateLayerSymbol(pAddAllLayer);
                    findedGroupLayer.layers.add(pAddAllLayer);
                });
            });


           
        }, function (error) {
            console.log("error:", error);
        });


        function modifyLayerdef(layerdef) {
            if (layerdef.fields) {
                layerdef.fields.forEach(fd => {
                    if (fd.type == "esriFieldTypeString") {
                        fd.type = "string";
                    } else if (fd.type == "esriFieldTypeOID") {
                        fd.type = "oid";
                    } else if (fd.type == "esriFieldTypeSmallInteger") {
                        fd.type = "small-integer";
                    } else if (fd.type == "esriFieldTypeDouble") {
                        fd.type = "double";
                    } else if (fd.type == "esriFieldTypeDate") {
                        fd.type = "date";
                    } else if (fd.type == "esriFieldTypeInteger") {
                        fd.type = "integer";
                    }


                    if (fd.domain) {
                        if (fd.domain.type == "codedValue") {
                            fd.domain.type = "coded-value";
                        }
                    }
                });

                if (layerdef.geometryType == "esriGeometryPolyline") {
                    layerdef.geometryType = "polyline";
                } else if (layerdef.geometryType == "esriGeometryPoint") {
                    layerdef.geometryType = "point";
                }
            }

            if (layerdef.drawingInfo) {
                if (layerdef.drawingInfo.renderer) {
                    if (layerdef.drawingInfo.renderer.symbol) {
                        if (layerdef.geometryType == "polyline") {
                            layerdef.drawingInfo.renderer.symbol.type = "simple-line";
                            layerdef.drawingInfo.renderer.symbol.style = "solid";
                        }
                    }
                }
            }

            return layerdef;
        }



        view.ui.add(
            new Zoom({
                view: view
            }),
            "top-right"
        );

        view.ui.add(
            new NavigationToggle({
                view: view
            }),
            "top-right"
        );

        view.ui.add(
            new Compass({
                view: view
            }),
            "top-right"
        );





        view.ui.add(document.getElementById("slidecontainerid"), "bottom-right");

        var slider = document.getElementById("mapOpacityRange");

        slider.oninput = function () {
            view.map.ground.opacity = Number(this.value).toFixed(2);
        }


        view.when(function () {


            // allow navigation above and below the ground
            scene.ground.navigationConstraint = {
                type: "none"
            };
            //預設地表透明0.6
            view.map.ground.opacity = 0.6;
            //加入切剖功能
            const sliceButton = document.getElementById("slice");
            view.ui.add(sliceButton, "top-left");
            let sliceWidget = null;

            sliceButton.addEventListener("click", function () {
                if (sliceWidget) {
                    sliceWidget.destroy();
                    sliceWidget = null;
                    sliceButton.classList.remove("active");
                } else {
                    sliceWidget = new Slice({
                        view: view
                    });
                    sliceWidget.viewModel.newSlice();
                    // programmatically add layers that should be excluded from slicing
                    //sliceWidget.viewModel.excludedLayers.addMany(excludedLayers);
                    view.ui.add(sliceWidget, "top-left");
                    sliceButton.classList.add("active");
                }
            });

            //console.log(view.center);

        });
  
        //地圖上click事件
        //view.on("click", function (event) {

        //});

        //地圖上pointer-up事件
        //view.on("pointer-up", function (event) {

        //});

        //載入預設設定的群組圖層
        pGroupLayers.forEach(eGlayer => {

            if (eGlayer.isAddToMap) {

                var pGLayer = CreateGroupLayer(eGlayer.groupID, eGlayer.groupName, eGlayer.groupVisible);
                view.map.add(pGLayer);

                eGlayer.sublayers.forEach(sublayer => {

                    if (sublayer.type == "scene") {
                        var scenelayer = new SceneLayer({
                            id: sublayer.id,
                            title: sublayer.title,
                            url: sublayer.serviceUrl
                        });

                        if (sublayer.elevationInfo) {
                            scenelayer.elevationInfo = sublayer.elevationInfo;
                        }

                        if (sublayer.opacity) {
                            scenelayer.opacity = sublayer.opacity;
                        }

                        if (sublayer.visible == false) {
                            scenelayer.visible = sublayer.visible;
                        }

                        pGLayer.layers.add(scenelayer);
                    }
                });
            }

        });

        //載入設備圖層
        pEquipGLayer.forEach(eGlayer => {
            if (eGlayer.isAddToMap) {

                var pGLayer = CreateGroupLayer(eGlayer.groupID, eGlayer.groupName, eGlayer.groupVisible);
                view.map.add(pGLayer);


                //載入sql讀入的point 圖層
                equipLayerDatas.forEach(equipL => {
                   
                    var layerDef = pLayerDefs.filter(function (obj) {
                        return obj.id === equipL.name;
                    });
                    if (layerDef.length > 0) {
                        var d1_doorGraphics = CreateGraphics(equipL.rows);
                        layerDef[0].source = d1_doorGraphics;
                        layerDef[0].refreshInterval = 0.1;
                        var dFL = new FeatureLayer(layerDef[0]);

                        var inGroupLaeyr = eGlayer.sublayers.filter(function (obj) {
                            return (obj.id === equipL.name) ? true : false;
                        });
                        if (inGroupLaeyr) {
                            pGLayer.layers.add(dFL);
                        } else {
                            view.map.add(dFL);
                        }

                        //CreateFeatureTable(layerDef[0].id+"_tbl",dFL);
                    }
                });

            }
        });


        window.view = view;

    }

        function loadoverviewMap() {

            //MTXinBanAreaPipeScene
            var overviewMap = new WebMap({
                portalItem: { // autocasts as new PortalItem()
                    id: pConfigJSON.dashboardoverviewmap.itemId // ID of the WebScene on the on-premise portal
                }
            });

            var mapView = new MapView({
                container: "overviewDiv",
                map: overviewMap,
                constraints: {
                    rotationEnabled: false
                }
            });

            // Remove the default widgets
            mapView.ui.components = [];

            mapView.when(function () {
                window.view.when(function () {
                    overviewMapSetup();
                });
            });

            function overviewMapSetup() {
                const extent3Dgraphic = new Graphic({
                    geometry: null,
                    symbol: {
                        type: "simple-fill",
                        color: [0, 0, 0, 0.5],
                        outline: null
                    }
                });
                mapView.graphics.add(extent3Dgraphic);

                watchUtils.init(view, "extent", function (extent) {
                    // Sync the overview map location
                    // whenever the 3d view is stationary
                    if (view.stationary) {
                        mapView.goTo({
                                center: view.center,
                                scale:
                                    view.scale *
                                    2 *
                                    Math.max(
                                        view.width / mapView.width,
                                        view.height / mapView.height
                                    )
                            })
                            .catch(function (error) {
                                // ignore goto-interrupted errors
                                if (error.name != "view:goto-interrupted") {
                                    console.error(error);
                                }
                            });
                    }

                    extent3Dgraphic.geometry = extent;
                });
            }
        }

        function CreateGroupLayer(strGroupID, strGroupName, isVisible) {
            var findedGroupLayer = view.map.findLayerById(strGroupID);

            if (!findedGroupLayer) {
                findedGroupLayer = new GroupLayer({
                    id: strGroupID,
                    title: strGroupName,
                    visibilityMode: "independent"
                    //,layers: [USALayer, censusLayer]
                    //,opacity: 0.75
                });

                if (isVisible == false) {
                    findedGroupLayer.visible = isVisible;
                }
            }
            return findedGroupLayer;
        }

        //批次更新空間查詢
        function updateSQueryFL(eLayerPara, centerPoint) {

            var featureLayer = eLayerPara.fLayer;
            var layerID = eLayerPara.groupID + "_" + eLayerPara.id;
            var query = featureLayer.createQuery();
            query.geometry = centerPoint; //view.toMap(event); // the point location of the pointer
            query.distance = 100;
            query.units = "meters";
            query.spatialRelationship = "intersects"; // this is the default
            query.returnGeometry = true;
            query.outFields = ["*"];

            featureLayer.queryFeatures(query)
                .then(function (response) {

                    if (response.features.length <= 0)
                        return;


                    var findedGroupLayer = view.map.findLayerById(eLayerPara.groupID);

                    if (!findedGroupLayer) {
                        findedGroupLayer = new GroupLayer({
                            id: eLayerPara.groupID,
                            title: eLayerPara.groupName,
                            visible: eLayerPara.groupVisible == false ? eLayerPara.groupVisible : true,
                            visibilityMode: "independent"
                            //,layers: [USALayer, censusLayer]
                            //,opacity: 0.75
                        });

                        view.map.add(findedGroupLayer);
                    }

                    var findedLayer = view.map.findLayerById(layerID);

                    if (!findedLayer) {
                        var pfS = response.features;
                        //設定feature z value
                        if (eLayerPara.fLayer.geometryType == "polyline") {
                            pfS = ResetFeatureZ(response.features);
                        }

                        var featureCollection = {
                            layerDefinition: eLayerPara.fLayer,
                            featureSet: pfS,
                            customRender: eLayerPara.renderer,
                            ElevationInfo: eLayerPara.ElevationInfo
                        };

                        if (pLayersJSON.sysFieldNames) {
                            featureCollection.layerDefinition.fields = featureCollection.layerDefinition.fields.filter(el => !pLayersJSON.sysFieldNames.includes(el.name));
                        }

                        //更新domain
                        featureCollection.layerDefinition.fields.forEach(function (part, index) {

                            if (this[index].domain) {
                                //有domain的服務欄位用dmain名稱對應
                                var customDomain = pDomainsJSON.filter(el => el.name == this[index].domain.name);

                                if (customDomain.length > 0) {
                                    this[index].domain = customDomain[0];
                                }
                            } else {
                                var cfieldname = this[index].name;
                                //直接用欄位名稱對應
                                var customDomain = pDomainsJSON.filter(function (el) {
                                    if (cfieldname == "SetType") {
                                        if (featureCollection.layerDefinition.geometryType == "polyline") {
                                            return el.name == "SetTypeLine"
                                        } else if (featureCollection.layerDefinition.geometryType == "point") {
                                            return el.name == "SetType"
                                        }
                                    } else {
                                        if (el.tfieldnames) {
                                            return el.tfieldnames.includes(cfieldname);
                                        }
                                    }

                                });

                                if (customDomain.length > 0) {
                                    this[index].domain = customDomain[0];
                                }
                            }
                        }, featureCollection.layerDefinition.fields);


                        pResultLayer = CreateFeatureLayer(layerID, eLayerPara.name, featureCollection)

                        pResult3DSymbolLayer = updateLayerSymbol(pResultLayer);
                        findedGroupLayer.layers.add(pResult3DSymbolLayer);
                    } else {
                        var pfS = response.features;
                        if (eLayerPara.fLayer.geometryType == "polyline") {
                            pfS = ResetFeatureZ(response.features);
                        }
                        findedLayer.queryFeatures().then(function (results) {
                            const updateEdits = {
                                deleteFeatures: results.features,
                                addFeatures: pfS
                            };
                            applyEditsToLayer(findedLayer, updateEdits);
                        });

                    }

                });
        }

        function ResetFeatureZ(fs) {

            if (fs.length > 0) {

                fs.forEach(function (feature) {
                    if (feature.attributes) {
                        if (feature.attributes.startdepth & feature.attributes.enddepth) {
                            //前後高程相同時z value直接填0(代表前後高度無變化)
                            if (feature.attributes.startdepth == feature.attributes.enddepth) {

                                var paths = feature.geometry.paths;
                                paths.forEach(function (pth) {
                                    pth.forEach(function (vertex) {
                                        vertex.push(0);
                                    }, pth);
                                }, paths);

                                var line = new Polyline({
                                    hasZ: true,
                                    hasM: false,
                                    paths: paths,
                                    spatialReference: { wkid: 4326 }
                                });
                                feature.geometry = line;
                            } else {
                                var mv = (feature.attributes.startdepth + feature.attributes.enddepth) / 2;//平均埋深
                                var newsx = mv - feature.attributes.startdepth; //平均埋深到起點埋深距離
                                var newsy = mv - feature.attributes.enddepth;//平均埋深到終點埋深距離
                                var pathsCount = feature.geometry.paths.concat().flat().length;

                                var xyd = newsx - newsy;//起終點埋深高度差

                                var vd = xyd / (pathsCount - 1);//各節點差植

                                var loopCount = 0;
                                var paths = feature.geometry.paths;
                                paths.forEach(function (pth) {
                                    pth.forEach(function (vertex) {
                                        //設定每個節點高程
                                        vertex.push(newsx - (vd * loopCount));
                                        loopCount += 1;
                                    }, pth);
                                }, paths);

                                var line = new Polyline({
                                    hasZ: true,
                                    hasM: false,
                                    paths: paths,
                                    spatialReference: { wkid: 4326 }
                                });
                                feature.geometry = line;
                            }

                        }
                    }

                }, fs);

            }

            return fs;
        }

        //建立client-side FeatureLayer
        function CreateFeatureLayer(pLayerID, pTitle, featureCollection) {


            var filteredFields = featureCollection.layerDefinition.fields.filter(function (el) { return !["SHAPE.STLength()"].includes(el.name); });

            filteredFields.forEach(function (field) {
                //設定中文別名  
                var objField = pCFieldNames.find((obj => obj.Name == field.name));

                if (objField) {
                    field.alias = objField.Alias;
                }

            });


            var featureLayerPara = {
                id: pLayerID,
                title: pTitle,
                source: featureCollection.featureSet,
                objectIdField: featureCollection.layerDefinition.objectIdField,
                popupEnabled: featureCollection.layerDefinition.popupEnabled,
                fields: filteredFields,
                popupTemplate: featureCollection.layerDefinition.defaultPopupTemplate,
                geometryType: featureCollection.layerDefinition.geometryType,
                renderer: featureCollection.layerDefinition.renderer
            };

            //console.log(JSON.stringify(featureLayerPara));

            if (featureCollection.customRender) {
                featureLayerPara.renderer = featureCollection.customRender;
            }


            if (featureCollection.ElevationInfo) {
                featureLayerPara.elevationInfo = featureCollection.ElevationInfo;
            }


            pLayer = new FeatureLayer(featureLayerPara);

            pLayer.popupTemplate.title = pTitle;

            return pLayer;
        }

        //新增圖層屬性表
        function CreateFeatureTable(elementID, fLayer) {
            var strTableID = "body_"+elementID;
            $("#" + strTableID).remove();

            var container = $('#' + elementID);
            var divCTable = $(document.createElement('div'));
            $(divCTable).attr('id', strTableID);
            container.append(divCTable);
            // create the FeatureTable from the provided FeatureLayer
            pCrossAnalysisTable = new FeatureTable({
                layer: fLayer,
                highlightOnRowSelectEnabled: true,
                menuConfig: {
                    items: [
                        {
                            label: "縮放至選取衝突點",
                            iconClass: "esri-icon-zoom-in-magnifying-glass",
                            clickFunction: function (event) {
                                zoomToCrossAnalysisSF(fLayer, crossAnalysisSelectedFeatures);
                            }
                        }
                    ]
                },
                fieldConfigs: [
                    {
                        name: "fvalue",
                        label: "fvalue"
                    }, {
                        name: "dvid",
                        label: "dvid"
                    }],
                container: document.getElementById(strTableID)
            });
            // Get the FeatureLayer's layerView and listen for the table's selection-change event
            pCrossAnalysisTable.on("selection-change", function (changes) {
                // If the selection is removed, remove the feature from the array
                changes.removed.forEach(function (item) {
                    const data = crossAnalysisSelectedFeatures.find(function (data) {
                        return data.feature === item.feature;
                    });
                    if (data) {
                        crossAnalysisSelectedFeatures.splice(crossAnalysisSelectedFeatures.indexOf(data), 1);
                    }
                });

                // If the selection is added, push all added selections to array
                changes.added.forEach(function (item) {
                    const feature = item.feature;
                    crossAnalysisSelectedFeatures.push({
                        feature: feature
                    });
                });
            });
        }

        //縮放至衝突點
        function zoomToCrossAnalysisSF(featureLayer, features) {
            // Create a query off of the feature layer
            const query = featureLayer.createQuery();
            // Iterate through the features and grab the feature's objectID
            const featureIds = features.map(function (result) {
                return result.feature.getAttribute(featureLayer.objectIdField);
            });
            // Set the query's objectId
            query.objectIds = featureIds;
            // Make sure to return the geometry to zoom to
            query.returnGeometry = true;
            // Call queryFeatures on the feature layer and zoom to the resulting features
            featureLayer.queryFeatures(query).then(function (results) {
                view.goTo({
                    target: results.features,
                    zoom: 23
                }).catch(function (error) {
                    if (error.name != "AbortError") {
                        console.error(error);
                    }
                });

                var objectIdArray = [];
                results.features.forEach(function (feature) {
                    var objectId = feature.attributes.objectid;
                    objectIdArray.push(objectId);
                });

                view.whenLayerView(featureLayer).then(function (officeLayerView) {

                    if (!officeLayerView.visible) {
                        alert("請先開啟衝突分析圖層。");
                        return;
                    }

                    if (crossAnalysisHighlight) {
                        crossAnalysisHighlight.remove();
                    }
                    // Highlight the feature passing the objectId to the method
                    crossAnalysisHighlight = officeLayerView.highlight(objectIdArray);

                });

            });
        }

        //"Add Features"
        function addFeatures(targetLayer, featureSet) {
            // addEdits object tells applyEdits that you want to add the features
            const addEdits = {
                addFeatures: featureSet
            };

            // apply the edits to the layer
            applyEditsToLayer(targetLayer, addEdits);
        }

        //刪除featureLayer圖徵
        function removeFeatures(targetLayer) {
            // query for the features you want to remove
            targetLayer.queryFeatures().then(function (results) {
                // edits object tells apply edits that you want to delete the features
                const deleteEdits = {
                    deleteFeatures: results.features
                };
                // apply edits to the layer
                applyEditsToLayer(targetLayer, deleteEdits);
            });
        }

        //更新featureLayer圖徵
        function applyEditsToLayer(targetLayer, edits) {
            targetLayer
                .applyEdits(edits)
                //.then(function (results) {
                // if edits were removed
                //if (results.deleteFeatureResults.length > 0) {
                //    //console.log(results.deleteFeatureResults.length,"features have been removed");
                //}
                //// if features were added - call queryFeatures to return
                ////    newly added graphics
                //if (results.addFeatureResults.length > 0) {
                //    var objectIds = [];
                //    results.addFeatureResults.forEach(function (item) {
                //        objectIds.push(item.objectId);
                //    });
                //    // query the newly added features from the layer
                //    targetLayer
                //        .queryFeatures({
                //            objectIds: objectIds
                //        })
                //        .then(function (results) {
                //            //console.log( results.features.length,"features have been added.");
                //        });
                //}
                //})
                .catch(function (error) {
                    console.log(error);
                });
        }

        //更新圖層樣式
        function updateLayerSymbol(layer) {
            if (layer.title !== "共管設備") {
                layer.labelingInfo = [];
            }


            if (layer.fields) {
                var findOpcode = layer.fields.find(function (item, index, array) {
                    return item.name === "opcode";
                });
                if (findOpcode) {
                    layer.definitionExpression = "opcode not in ('2','9')";
                }

            }


            if (layer.geometryType === "polyline") {


                if (layer.fields) {

                    if (layer.renderer) {
                        const uvRenderer = new UniqueValueRenderer({
                            field: layer.renderer.field
                        });
                        for (var i = 0; i < layer.renderer.uniqueValueInfos.length; i++) {

                            uvRenderer.addUniqueValueInfo({
                                value: layer.renderer.uniqueValueInfos[i].value,
                                symbol: {
                                    type: "line-3d",
                                    symbolLayers: [{
                                        type: "path",
                                        profile: "circle",
                                        material: {
                                            color: layer.renderer.uniqueValueInfos[i].symbol.color
                                        },
                                        width: 1,
                                        height: 1,
                                        join: "round",
                                        cap: "round",
                                        anchor: "center",
                                        profileRotation: "all"
                                    }]
                                }
                            });


                        }


                        layer.renderer = uvRenderer;

                        var currentElevationInfo = {
                            mode: "relative-to-ground",
                            offset: 0,
                            unit: "meters"
                        };

                        layer.elevationInfo = currentElevationInfo;

                    }


                }

            } else if (layer.geometryType === "point") {


                var currentElevationInfo2 = {
                    mode: "on-the-ground",
                    offset: 0,
                    // featureExpressionInfo: {
                    //     expression: "if($feature.holedepth>0){-$feature.holedepth}else{$feature.holedepth}"
                    // },
                    unit: "meters"
                };

                layer.elevationInfo = currentElevationInfo2;

            } else {
                //其他不需套3D樣式圖層
                //console.log(layer.title);
            }
            return layer;
        }

        function updateRenderer(layer) {
            renderer = layer.renderer.clone();
            const sizeVariable = renderer.visualVariables[0];
            const colorVariable = renderer.visualVariables[1];
            sizeVariable.valueExpression = getSizeValueExpression(value);
            colorVariable.valueExpression = getColorValueExpression(value);
            renderer.visualVariables = [sizeVariable, colorVariable];
            layer.renderer = renderer;
        }

        // update the filter geometry depending on bufferSize
        let filterGeometry = null;

        function updateFilterGeometry(sketchGeometry) {
            var bufferSize = 100;
            // add a polygon graphic for the bufferSize
            if (sketchGeometry) {
                if (bufferSize > 0) {

                    var bufferGeometry = geometryEngine.geodesicBuffer(
                        sketchGeometry,
                        bufferSize,
                        "meters"
                    );
                    filterGeometry = bufferGeometry;
                } else {
                    filterGeometry = sketchGeometry;
                }
            }
        }

        function CalculatePipeWidth(pSizeUnit, pPipeWidth) {
            var rwidth = 0.4;
            if (pPipeWidth == 0) {
                rwidth = 0.4;
            } else {
                if (pSizeUnit == '0') {
                    rwidth = pPipeWidth / 1000;
                } else if (pSizeUnit == '1') {
                    rwidth = pPipeWidth * 2.54 / 100;
                } else if (pSizeUnit == '2') {
                    rwidth = pPipeWidth / 100;
                } else if (pSizeUnit == '3') {
                    rwidth = pPipeWidth;
                } else {
                    rwidth = pPipeWidth;
                }
            }
            return rwidth;
        }

        function CalculatePipeDepth(SizeUnit, PipeWidth, PipeHeight, startdepth, enddepth) {

            if (PipeHeight == 0) {
                if (SizeUnit == '0') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeWidth / 1000;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeWidth / 1000;
                    }
                } else if (SizeUnit == '1') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeWidth * 2.54 / 100;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeWidth * 2.54 / 100;
                    }
                } else if (SizeUnit == '2') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeWidth / 100;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeWidth / 100;
                    }
                } else if (SizeUnit == '3') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeWidth;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeWidth;
                    }
                } else {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeWidth;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeWidth;
                    }
                }
            } else {
                if (SizeUnit == '0') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeHeight / 1000;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeHeight / 1000;
                    }
                } else if (SizeUnit == '1') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeHeight * 2.54 / 100;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeHeight * 2.54 / 100;
                    }
                } else if (SizeUnit == '2') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeHeight / 100;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeHeight / 100;
                    }
                } else if (SizeUnit == '3') {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeHeight;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeHeight;
                    }
                } else {
                    if ((startdepth + enddepth) / 2 > 0) {
                        return (-(startdepth + enddepth) / 2) - PipeHeight;
                    } else {
                        return ((startdepth + enddepth) / 2) - PipeHeight;
                    }
                }
            }

        }


        function ReloadEquipLayers(newDatas) {

            //更新設備圖層資料來源
            newDatas.forEach(equipL => {

                //測試資料變更
                if (equipL.name == "d1_door") {
                    //equipL.rows.forEach(f => {
                    //    f.fvalue = 1;
                    //});

                    //console.log(equipL);
                }

                var findedEquipLayer = view.map.findLayerById(equipL.name);
                if (findedEquipLayer) {
                    var dGraphics = CreateGraphics(equipL.rows);
                    findedEquipLayer.source = dGraphics;
                }
            });

        };

        function RefreshDashBoard(updateTime) {

            //console.log(window.cDashboardSetting);

            $.ajax({ //更新設備圖層資料
                type: 'GET',
                url: updatedataUrl,
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg, status, jqXHR) {
                    equipLayerDatas = msg;
                    ReloadEquipLayers(equipLayerDatas);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                }
            });

            $.get(CategoryListPartailUrl, window.cDashboardSetting, function (data) {
                $('#CategoryListPartail').html(data);
            });

            $.get(EquipFeatureListPartailUrl, window.cDashboardSetting, function (data) {
                $('#EquipFeatureListPartail').html(data);
            });

            if (updateTime) {
                $('#DataUpdateDT').html(updateTime);
               
            } else {
                $.get(DataUpdateDTPartailUrl, {}, function (data) {
                    $('#DataUpdateDT').html(data);
                });
            }
        
    };

    function RefreshStatus() {

        $.ajax({ //更新設備圖層資料
            type: 'GET',
            url: UpdateStatusUrl,
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg, status, jqXHR) {
                console.log(msg);
                if (msg) {
                    RefreshDashBoard(msg.Time);
                } else {
                    RefreshDashBoard();
                }
               
              
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
        
    };

        //重新載入地圖
        $('.ReloadData').click(function () {
            RefreshStatus();
        });

        //30秒更新一次
        setInterval(RefreshStatus, 30000);

    });