angular.module('nurseApp')
// (重写)设备导航栏
.controller('sidebarCtrl',['$scope', '$rootScope', 'deviceService',
    function($scope, $rootScope, deviceService){
        $scope.isExpand = true;// 默认展开
        $scope.SidebarId = localStorage.getItem("SidebarId");
        $scope.SidebarPartId = localStorage.getItem("SidebarPartId");

        (function(){
            loadSidebar();
        })();

        function loadSidebar(){
            deviceService.GetShowConfigureMold().then(function (sidebar) {
                $scope.DeviceSidebar = sidebar;
                if($scope.SidebarId == null && sidebar){
                    $scope.SidebarId = sidebar[0].configId;
                    if($scope.SidebarPartId == null && sidebar[0].parts){
                        $scope.SidebarPartId = sidebar[0].parts[0].configId;
                    }else{
                        $scope.SidebarPartId = -1;
                    }
                    //localStorage.setItem("SidebarId",$scope.SidebarId);
                    //localStorage.setItem("SidebarPartId",$scope.SidebarPartId);
                }
                //console.log(sidebar, $scope.SidebarId, $scope.SidebarPartId);
            });
        }

        $rootScope.$on("loadSidebar", function (fun) {
            loadSidebar();
        });

        $scope.sidebarActive = function(item, part){
            if(part == undefined){
                if(item && item.parts){
                    $scope.SidebarId = item.configId;
                    $scope.SidebarPartId = item.parts[0].configId;
                    window.location.href = '#/deviceInfo/'+item.parts[0].deviceId;
                }else{
                    $scope.SidebarId = item.configId;
                    $scope.SidebarPartId = -1;
                }
            }else{
                $scope.SidebarId = item.configId;
                $scope.SidebarPartId = part.configId;
                window.location.href = '#/deviceInfo/'+part.deviceId;
            }
            //localStorage.setItem("SidebarId",$scope.SidebarId);
            //localStorage.setItem("SidebarPartId",$scope.SidebarPartId);
        };
    }
])
// (重写)设备详情页(活动告警、实时数据、设备控制)
.controller('deviceInfoCtrl',['$scope', '$rootScope', '$stateParams', '$interval', '$modal', 'deviceService', 'activeSignalService', 'activeDeviceService', 'alarmService', 'baseTypeService', 'userService', 'devcontrolService', 'balert',
    function($scope, $rootScope, $stateParams, $interval, $modal, deviceService, activeSignalService, activeDeviceService, alarmService, baseTypeService, userService, devcontrolService, balert){
        (function(){
            if($stateParams.deviceId == 0){
                deviceService.GetShowConfigureMold().then(function (sidebar) {
                    if(sidebar && sidebar[0].parts){
                        $scope.deviceId = sidebar[0].parts[0].deviceId;
                        loadDeviceInfo();
                        loadDeviceControl();
                    }
                });
            }else{
                $scope.deviceId = $stateParams.deviceId;
                loadDeviceInfo();
                loadDeviceControl();
            }
        })();

        function loadDeviceInfo(){
            if(!$scope.deviceId) return;
            // 活动告警
            alarmService.getAlarmsByDeviceId($scope.deviceId).then(function (data) {
                $scope.alarms = data;
            });
            // 实时数据
            if($scope.tableParams){
                var index = ($scope.tableParams.currentPage - 1)*$scope.tableParams.itemsPerPage;
                var count = $scope.tableParams.itemsPerPage;
                loadDeviceSignal($scope.deviceId, index, count);
            }
        }

        //#region 活动告警
        $scope.beginEndAlarm = function (uniqueId) {

            $scope.selectedAlarmUniqueId = uniqueId;
            //alert($scope.selectedAlarmUniqueId);

            remarkDialog = $modal({
                scope: $scope,
                templateUrl: 'partials/alarmRemarkDialog.html',
                show: false
            });

            remarkDialog.$promise.then(remarkDialog.show);
        };

        $scope.endEndAlarm = function (note) {
            if (note == undefined || note == "") {
                balert.show('danger', $scope.languageJson.RoomHome.AlarmTitle.EndAlarm.ReasonError, 3000);//'理由不能为空!'
                return;
            }
            var logonId = localStorage.getItem("username");
            var param = "'" + $scope.selectedAlarmUniqueId + "'|" + logonId + "|" + note;

            alarmService.endAlarm(param).then(function (data) {
                remarkDialog.hide();
            });
        };
        //#endregion

        //#region 实时数据
        //分页对象定义
        $scope.filter = {
            isQuery: false
        };
        $scope.tableParams = {
            currentPage: 1,//当前页面
            itemsPerPage: 100,//显示条数
            pagesLength: 10,
            totalItems: 0,//总条数
            hint: {
                the: $scope.languageJson.Paging.The,
                page: $scope.languageJson.Paging.Page,
                articel: $scope.languageJson.Paging.Articel,
                eachPage: $scope.languageJson.Paging.EachPage,
                total: $scope.languageJson.Paging.Total,
                noData: $scope.languageJson.Paging.NoData
            },
            list: [],//数据集
            perPageOptions: [100, 200, 500, 1000],//显示条数组
            onChange: function (newValue, oldValue) {
                if (newValue == undefined) return;
                $scope.stop();
                // var index = ($scope.tableParams.currentPage - 1)*$scope.tableParams.itemsPerPage;
                // var count = $scope.tableParams.itemsPerPage;
                // loadDeviceSignal($scope.deviceId, index, count);
                $scope.start();
            }
        };
        function loadDeviceSignal(deviceId, index, count){
            activeDeviceService.getActiveDevices().then(function (data) {
                var dev = undefined;
                data.forEach(function (item) {
                    if (item.id == $stateParams.deviceId)
                        dev = item;
                });
                if (dev == undefined) return;

                if (dev.status === "Alarm") dev.info = $scope.languageJson.RoomHome.AlarmTitle.DataTable.Alarm;//"告警中"
                if (dev.status === "Normal") dev.info = $scope.languageJson.RoomHome.AlarmTitle.DataTable.Normal;//"正常运行"
                if (dev.status === "Disconnect") dev.info = $scope.languageJson.RoomHome.AlarmTitle.DataTable.Disconnect;//"已中断"

                dev.colorClass = function () {
                    if (dev.status === "Alarm") return "text-danger";
                    if (dev.status === "Normal") return "text-success";
                    if (dev.status === "Disconnect") return "text-muted";
                };

                dev.iconClass = function () {
                    if (dev.status === "Alarm") return "fa fa-bell";
                    if (dev.status === "Normal") return "fa fa-check";
                    if (dev.status === "Disconnect") return "fa fa-times";
                };

                $scope.device = dev;
            });
            activeSignalService.getActiveSignalByDeviceByPage(deviceId, index, count).then(function (signals) {
                if ($scope.device && $scope.device.status != undefined && $scope.device.status == "Disconnect") {//设备状态为中断时,所有的信号状态都为中断
                    signals.forEach(function (item) {
                        item.alarmSeverity = -255;
                    });
                }
                $scope.tableParams.list = signals;
                //console.log(deviceId, index, count, signals.length);
            });
            activeSignalService.getActiveSignalByDeviceTotal(deviceId).then(function (total) {
                $scope.tableParams.totalItems = parseInt(total);
                $rootScope.$emit('resultTotal',{});
                //console.log($scope.deviceId, total);
            });
        }
        $scope.getStatusLabel = function (status) {
            if (status == 255)
                return $scope.languageJson.RoomHome.AlarmTitle.DataTable.Normal;//"正常"
            else if (status == -255)
                return $scope.languageJson.RoomHome.AlarmTitle.DataTable.Disconnect;//"已中断"
            else if (parseInt(status) >= 0 && parseInt(status) <= 3)
                return $scope.languageJson.RoomHome.AlarmTitle.DataTable.Alarm;//"告警"
            else
                return $scope.languageJson.RoomHome.AlarmTitle.DataTable.Loading;//"加载中"
        };
        // 信号状态提示
        $scope.getStatusTextClass = function (preClass, status) {
            if (status == 255)
                return preClass + " text-success";
            else if (status >= 0 && status <= 3)
                return preClass + " text-danger";
            else
                return "text-muted";
        };
        // 信号状态图标
        $scope.getStatusIconClass = function (status) {
            if (status == 255)
                return "fa fa-check";
            else if (status >= 0 && status <= 3)
                return "fa fa-bell";
            else
                return "fa fa-times";
        };
        //#endregion

        //#region 设备控制
        function loadDeviceControl(){
            if(!$scope.deviceId) return;
            baseTypeService.GetAllControlMeaningByDeviceId($scope.deviceId,1).then(function(controls){
                $scope.Controls = controls;
                //console.log(controls);
            });
        }

        var controlSetterDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/controlauthorizesetter.html',
            show: false
        });
        $scope.sendControlClk = function(control){
            var isShow = false;
            var value = "0";
            if(control.CommandType == "1"){//遥调
                isShow = false;
                value = control.MinValue;
            }else{//遥控
                isShow = true;
                value = control.ParameterValue;
            }
            $scope.controlinfo = {
                isPwd : true,
                isShow : isShow,
                pwdType : 'LoginPassword',
                Pwd : '',
                deviceid : $scope.deviceId,
                controlid : control.BaseTypeId,
                optionType : value,
                optionValue : value,
                commdanType : control.CommandType,
                min: control.MinValue,
                max: control.MaxValue
            };
            controlSetterDlg.$promise.then(controlSetterDlg.show);
        };
        $scope.sendcontrol = function(){
            var alert = $scope.languageJson.Configuration.RemoteControl.Alert;
            var paras = $scope.controlinfo;
            var userName = localStorage.getItem("username");

            userService.changePassword(userName,paras.userpwd).then(function(data){
                if(data == "OK"){
                    devcontrolService.senddevcontrol(paras.deviceid,paras.controlid,paras.optionType,userName).then(function(data){
                        if(data == "success"){
                            balert.show('success', alert.Succeed, 3000);//"下发命令成功!"
                            controlSetterDlg.hide();
                        }
                        else
                            balert.show('danger', alert.Failed, 3000);//"下发命令失败!"
                    });
                }else
                    balert.show('danger', alert.PasswordError,3000);//'密码不正确,请重新输入!'
            });
        }
        $scope.changeValue = function(value){
            $scope.controlinfo.optionType = value;
        };
        //#endregion

        //#region 定时器
        var stop = undefined;
        $scope.start = function () {
            if (angular.isDefined(stop)) return;

            loadDeviceInfo();

            stop = $interval(function () {
                loadDeviceInfo();
            }, 3000);
        };

        $scope.stop = function () {
            if (angular.isDefined(stop)) {
                $interval.cancel(stop);
                stop = undefined;
            }
        };

        $scope.$on('$destroy', function () {
            // Make sure that the interval is destroyed too
            $scope.stop();
        });
        //#endregion
    }
])
// (重写)配置管理
.controller('ConfigCtrl',['$scope', '$rootScope', '$modal', '$filter', 'notifyService', 'stationService', 'equipmentTemplateService', 'TemplateService', 'baseTypeService', 'uploadService', 'monitorUnitService', 'employeeService', 'equipmentService', 'portService', 'samplerUnitService', 'deviceService', 'balert', 'bconfirm',
    function($scope, $rootScope, $modal, $filter, notifyService, stationService, equipmentTemplateService, TemplateService, baseTypeService, uploadService, monitorUnitService, employeeService, equipmentService, portService, samplerUnitService, deviceService, balert, bconfirm){
        //#region 1.初始化配置
        //配置分页基本参数
        $scope.paginationConf = {
            hint: {
                the: $scope.languageJson.Paging.The,
                page: $scope.languageJson.Paging.Page,
                articel: $scope.languageJson.Paging.Articel,
                eachPage: $scope.languageJson.Paging.EachPage,
                total: $scope.languageJson.Paging.Total,
                noData: $scope.languageJson.Paging.NoData
            },
            currentPage: 1,
            itemsPerPage: 10,
            pagesLength: 10,
            totalItems: 0,
            equipments: [],
            perPageOptions: [10, 20, 30, 40, 50],
            onChange: function () {
            }
        };

        $scope.equipmentItems = -1;

        //中心
        $scope.center = {};
        $scope.center.centerId = -1;
        $scope.center.centerIP = "";
        $scope.center.centerPort = -1;
        $scope.center.centerDSIP = "";
        $scope.center.Enable = false;

        //局站
        $scope.station = {};
        $scope.stationId = -1;
        $scope.station.stationName = "";
        $scope.station.contactId = -1;
        $scope.station.remark = "";
        $scope.station.employee = {};

        //监控单元
        $scope.monitorUnit = {};
        $scope.monitorUnit.MonitorUnitId = -1;

        //模板
        $scope.equipmentTemplate = {};
        $scope.equipmentTemplate.EquipmentTemplateId = -1;
        $scope.equipmentTemplate.EquipmentTemplateName = "";

        //设备
        $scope.equipment = {};
        $scope.equipment.EquipmentId = -1;
        $scope.equipment.EquipmentName = "";
        $scope.equipment.EquipmentType = -1;
        $scope.equipment.StationIArrayListd = -1;
        $scope.equipment.EquipmentTemplateId = -1;
        $scope.equipment.SamplerUnitId = -1;
        $scope.equipment.MonitorUnitId = -1;

        //端口
        $scope.portFlag = 0;
        $scope.port = {};
        $scope.port.PortId = -1;
        $scope.port.MonitorUnitId = -1;
        $scope.port.PortNo = -1;
        $scope.port.PortType = 0;
        $scope.port.Setting = "9600,n,8,1";
        $scope.port.PortTypeVar = {};

        //采集单元
        $scope.samplerUnit = {};
        $scope.samplerUnit.SamplerUnitId = -1;
        $scope.samplerUnit.PortId = -1;
        $scope.samplerUnit.MonitorUnitId = -1;
        $scope.samplerUnit.Address = 1;
        $scope.samplerUnit.DllPath = "";
        $scope.samplerUnit.SamplerId = -1;
        $scope.samplerUnit.SamplerType = -1;
        $scope.samplerUnit.SamplerUnitName = "";

        $scope.Template = {
            EquipmentCategory: [],
            Property: []
        };
        $scope.Signal = {
            SignalCategory: [],
            SignalType: [],
            ChannelType: [],
            DataType: []
        };
        $scope.Event = {
            EventCategory: [],
            StartType: [],
            EndType: [],
            EventSeverity: []
        };
        $scope.Control = {
            ControlCategory: [],
            ControlSeverity: [],
            CommandType: [],
            ControlType: [],
            DataType: []
        };
        $scope.seleBaseType = {};
        //#endregion
    
        //#region 2.初始化数据
        (function(){
            //获取端口类型
            notifyService.getDataItems("39").then(function (data) {
                var result = data;
                if (result == "fail to get dataItems") {
                    alert($scope.languageJson.Config.Failed.Title);/*获取端口类型失败,请检查连接是否正常!*/
                } else {
                    $scope.portTypes = parsePortTypes(data);
                }
            });
            //进入局站管理页面后,判断局站是否进行初始化,如果没有初始化,初始化局站
            stationService.initStationInfo().then(function (data) {
                var result = data;
                if (result == "fail to init station info") {
                    balert.show('danger', $scope.languageJson.Config.Failed.Initialization, 3000);/*'初始化局站失败,请检查连接是否正常!'*/
                } else {
                    //获取局站数据
                    stationService.getStationInfo().then(function (data) {
                        var result = data;
                        if (result == "fail to get station info") {
                            balert.show('danger', $scope.languageJson.Config.Failed.Station, 3000);/*'获取局站信息失败,请检查连接是否正常!'*/
                        } else {
                            getStation(result);

                            //获取中心配置
                            stationService.getCenterInfo().then(function (data) {
                                var result = data;
                                if (result == "fail to get center info") {
                                    balert.show('danger', $scope.languageJson.Config.Failed.Center, 3000);/*'获取中心信息失败,请检查连接是否正常!'*/
                                } else {
                                    getCenter(result);
                                }
                            });

                            //获取监控单元数据
                            monitorUnitService.getMonitorUnit($scope.stationId).then(function (data) {
                                $scope.monitorUnit = getMonitorUnit(data);
                            });

                            //获取人员信息
                            employeeService.getAllEmployees().then(function (data) {
                                $scope.employees = parseEmployees(data);

                                for (var i = 0; i < $scope.employees.length; i++) {
                                    if ($scope.employees[i].EmployeeId == $scope.station.contactId) {
                                        $scope.station.employee = $scope.employees[i];
                                        break;
                                    }
                                }
                            });
                        }
                    });
                }
            });

            $scope.selectEvent = {};
            //初始化 模板列表
            equipmentTemplateService.getAllEquipmentTemplate().then(function (data) {
                $scope.equipmentTemplates = parseEquipmentTemplate(data);
                if ($scope.equipmentTemplates[0])
                    $scope.selectEvent.EquipmentTemplateId = $scope.equipmentTemplates[0].EquipmentTemplateId;
            });

            //初始化等级信息
            $scope.selectEventSever = {};
            TemplateService.getAllEventSeverity().then(function (data) {
                $scope.equipmentEvent = data;
                $scope.selectEventSever.EventSeverity = $scope.equipmentEvent[0].EventSeverity;
            });

            function initTemplateDataItem() {
                TemplateService.GetDataItemByEntryId("7").then(function (data) {
                    $scope.Template.EquipmentCategory = data;
                });
                TemplateService.GetDataItemByEntryId("9").then(function (data) {
                    $scope.Template.Property = data;
                });
                TemplateService.GetEquipmentBaseType().then(function (data) {
                    $scope.Template.EquipmentBaseType = data;
                });
                TemplateService.GetDataItemByEntryId("17").then(function (data) {
                    $scope.Signal.SignalCategory = data;
                });
                TemplateService.GetDataItemByEntryId("18").then(function (data) {
                    $scope.Signal.SignalType = data;
                });
                TemplateService.GetDataItemByEntryId("22").then(function (data) {
                    $scope.Signal.ChannelType = data;
                });
                TemplateService.GetDataItemByEntryId("70").then(function (data) {
                    $scope.Signal.DataType = data;
                });

                TemplateService.GetDataItemByEntryId("24").then(function (data) {
                    $scope.Event.EventCategory = data;
                });
                TemplateService.GetDataItemByEntryId("25").then(function (data) {
                    $scope.Event.StartType = data;
                });
                TemplateService.GetDataItemByEntryId("26").then(function (data) {
                    $scope.Event.EndType = data;
                });
                TemplateService.GetDataItemByEntryId("23").then(function (data) {
                    $scope.Event.EventSeverity = data;
                });

                TemplateService.GetDataItemByEntryId("31").then(function (data) {
                    $scope.Control.ControlCategory = data;
                });
                TemplateService.GetDataItemByEntryId("28").then(function (data) {
                    $scope.Control.ControlSeverity = data;
                });
                TemplateService.GetDataItemByEntryId("32").then(function (data) {
                    $scope.Control.CommandType = data;
                });
                TemplateService.GetDataItemByEntryId("68").then(function (data) {
                    $scope.Control.ControlType = data;
                });
                TemplateService.GetDataItemByEntryId("70").then(function (data) {
                    $scope.Control.DataType = data;
                });
                uploadService.GetAllJsonTemplates().then(function (data) {
                    $scope.ConfigTemplates = parseJsonTemplate(data);
                });
                uploadService.GetAllJsonConfiguration().then(function (data) {
                    $scope.JsonConfiguration = parseJsonTemplate(data);
                });

            };
            initTemplateDataItem();

            baseTypeService.getDeviceList().then(function(data){
                $scope.AllDevices = data;
            });
        })();
        //解析端口类型数据
        function parsePortTypes(data) {

            var dataArray = [];
            var lan = $scope.languageJson.Language;
            data.forEach(function (element, index) {
                //if (element.ItemId == 1 || element.ItemId == 5 || element.ItemId == 6)
                if (element.ItemId == 1 || element.ItemId == 5 || element.ItemId == 6 || element.ItemId == 3 || element.ItemId == 19) {
                    //只保留串口和网口
                    var portType = {};
                    portType.PortTypeId = element.ItemId;
                    if (lan == "Chinese")
                        portType.PortTypeValue = element.ItemValue;
                    else
                        portType.PortTypeValue = element.ItemAlias;
                    dataArray.push(portType);
                }
            });

            return dataArray;
        }
        // 解析设备模板
        function parseEquipmentTemplate(data) {
            var result = [];
            if (data) {
                data.forEach(function (item) {
                    if (item.SoName != undefined && item.SoName.indexOf(".") != -1) {
                        var index = item.SoName.indexOf(".");
                        item.SoName = item.SoName.substring(0, index) + ".so";
                        if(result.length == 0){
                            result.push(item);
                        }else{
                            var f = _.findWhere(result, {EquipmentTemplateId:item.EquipmentTemplateId});
                            if(f == undefined){
                                result.push(item);
                            }
                        }
                    }
                });
            }
            return result;
        }
        // 解析组态模板
        function parseJsonTemplate(data) {
            data.forEach(function (item) {
                if ($scope.languageJson.Language != "Chinese") {
                    if (item.id == "201") item.name = $scope.languageJson.ConfigurationType.CT201;
                    else if (item.id == "301") item.name = $scope.languageJson.ConfigurationType.CT301;
                    else if (item.id == "401") item.name = $scope.languageJson.ConfigurationType.CT401;
                    else if (item.id == "402") item.name = $scope.languageJson.ConfigurationType.CT402;
                    else if (item.id == "501") item.name = $scope.languageJson.ConfigurationType.CT501;
                    else if (item.id == "702") item.name = $scope.languageJson.ConfigurationType.CT702;
                    else if (item.id == "1001") item.name = $scope.languageJson.ConfigurationType.CT1001;
                    else if (item.id == "1004") item.name = $scope.languageJson.ConfigurationType.CT1004;
                    else if (item.id == "1006") item.name = $scope.languageJson.ConfigurationType.CT1006;
                    else if (item.id == "1101") item.name = $scope.languageJson.ConfigurationType.CT1101;
                    else if (item.id == "1201") item.name = $scope.languageJson.ConfigurationType.CT1201;
                    else if (item.id == "1501") item.name = $scope.languageJson.ConfigurationType.CT1501;
                    else if (item.id == "2001") item.name = $scope.languageJson.ConfigurationType.CT2001;
                }
                if (item.name == "8888") item.name = $scope.languageJson.Configuration.ConfigurationPage.Export.Topology;//"拓扑图"
                else if (item.name == "8889") item.name = $scope.languageJson.Configuration.ConfigurationPage.Export.MDC;//"MDC统计";
                //else if(item.name == "8890") item.name = $scope.languageJson.Configuration.ConfigurationPage.Export.IView;//"iView首页";
                else if (item.name == "9999") item.name = $scope.languageJson.Configuration.ConfigurationPage.Export.Blank;//"空白页面";
                else if (item.name == "9999.table") item.name = $scope.languageJson.Configuration.ConfigurationPage.Export.Table;//"表格页面";
            });
            return data;
        }
        // 获取站点信息
        function getStation(data) {

            data.forEach(function (element, index) {
                $scope.stationId = element.StationId;
                $scope.station.stationName = element.StationName;
                $scope.station.contactId = element.ContactId;
                $scope.station.remark = element.Description;
            });
        }
        // 获取中心站点信息
        function getCenter(data) {

            data.forEach(function (element, index) {
                $scope.center.centerId = element.CenterId;
                $scope.center.centerIP = element.CenterIP;
                $scope.center.centerDSIP = element.CenterDSIP;
                $scope.center.centerPort = element.CenterPort;
                if (element.Enable == "true") {
                    $scope.center.Enable = true;
                } else {
                    $scope.center.Enable = false;
                }

            });
        }
        // 获取监控器信息
        function getMonitorUnit(data) {
            var mu = {};

            data.forEach(function (element, index) {
                mu.MonitorUnitId = element.MonitorUnitId;
            });

            return mu;
        }
        // 解析人员信息
        function parseEmployees(data) {

            var dataArray = [];

            data.forEach(function (element, index) {
                var employee = {};
                employee.EmployeeId = element.EmployeeId;
                employee.EmployeeName = element.EmployeeName;
                employee.Mobile = element.Mobile;
                employee.Email = element.Email;
                dataArray.push(employee);
            });

            return dataArray;
        }
        //#endregion

        //#region 3.设备信息管理
        //#region 3.1.新增设备
        var addEquipmentDialog = $modal({
            scope: $scope,
            templateUrl: 'fsu_model/partials/addEquipment.html',
            show: false
        });
        $scope.addEquipmentClick = function(){
            //增加设备前初始化
            $scope.equipmentTemplate = {};
            $scope.equipment = {};
            $scope.port = {};
            $scope.samplerUnit = {};
            $scope.portType = undefined;
            $scope.portFlag = 0;
            $scope.configurationType = "";
            $scope.templates = false;
            $scope.uploadGroup = false;
            addEquipmentDialog.$promise.then(addEquipmentDialog.show);
        };
        $scope.addClick = function(){
            //增加设备前校验输入是否正确
            //判断是否输入完成
            if ($scope.equipment.EquipmentName == undefined) {
                balert.show('danger', $scope.languageJson.Config.Config.Enter, 3000);/*请输入设备名称!*/
                return;
            }
            //检查名称长度是否超长
            if ($scope.equipment.EquipmentName.length > 128) {
                balert.show('danger', $scope.languageJson.Config.Config.Allowed, 3000);/*设备名称长度不允许超过128位!*/
                return;
            }
            //检查端口、采集单元信息是否输入正确
            if (!PortAndSPUnitValidate($scope.monitorUnit.MonitorUnitId)) {
                return;
            }
            //虚拟端口:106端口只能配置成IO设备
            var isPortNo = false;
            if ($scope.port.PortNo == 106) {
                if ($scope.equipment.EquipmentType != 1004) {
                    balert.show('danger', $scope.languageJson.Config.Config.Ports, 3000);/*'106端口只能配置成IO设备!'*/
                    return;
                }
            }
            //终端服务端口:已存在100端口,开放端口设置
            if ($scope.port.PortType == 6) {
                if ($scope.port.PortNo < 100 || $scope.port.PortNo >= 201) {
                    balert.show('danger', $scope.languageJson.Config.Config.Network, 3000);/*'网口的端口号只能在100-200之间!'*/
                    return;
                }
            }
            //非基本串口,不可重复端口号
            if (parseInt($scope.port.PortType) != 1 && parseInt($scope.port.PortType) != 6) {
                $scope.paginationConf.equipments.forEach(function (item, index) {
                    if (item.PortNo == $scope.port.PortNo) {
                        isPortNo = true;
                    }
                });
                if (isPortNo) {
                    balert.show('danger', $scope.languageJson.Config.Config.Repeated, 3000);/*'端口已存在,不能重复!'*/
                    return;
                }
            }

            //判断设备是否重名、端口的地址是否重复
            equipmentService.checkEquipmentConfig(0, $scope.equipment.EquipmentName, $scope.port.PortNo, $scope.samplerUnit.Address).then(function (result) {
                if (result == "OK") {
                    //新增设备
                    AddEquipment($scope.monitorUnit.MonitorUnitId);
                } else if (result == "Name Exists") {
                    balert.show('danger', $scope.languageJson.Config.Config.Exists, 3000);/*'设备名称已存在!'*/
                    return;
                } else if (result == "Address Exists") {
                    balert.show('danger', $scope.languageJson.Config.Config.Script, 3000);/*'同端口的地址不能重复!'*/
                    return;
                } else {
                    balert.show('danger', $scope.languageJson.Config.Config.Wrong, 3000);/*'脚本错误,请尝试其他端口!'*/
                    return;
                }
            });
        };
        //新增设备前校验端口和采集单元设置
        function PortAndSPUnitValidate(monitorUnitId) {

            if ($scope.port.PortNo == "" || $scope.port.PortNo == undefined) {
                balert.show('danger', $scope.languageJson.Config.Port.Title, 3000);/*'请输入端口号'*/
                return false;
            }
            if (isNaN($scope.port.PortNo)) {
                balert.show('danger', $scope.languageJson.Config.Port.Entered, 3000);/*'端口号输入有误!'*/
                return false;
            }
            if ($scope.port.PortType == undefined) {
                balert.show('danger', $scope.languageJson.Config.Port.Select, 3000);/*'请选择端口类型'*/
                return false;
            }
            if ($scope.port.Setting == "" || $scope.port.Setting == undefined) {
                balert.show('danger', $scope.languageJson.Config.Port.Communication, 3000);/*'请输入通讯参数'*/
                return false;
            }
            if ($scope.samplerUnit.Address == "" || $scope.samplerUnit.Address == undefined) {
                balert.show('danger', $scope.languageJson.Config.Port.Address, 3000);/*'请输入地址'*/
                return false;
            }
            if (isNaN($scope.samplerUnit.Address)) {
                balert.show('danger', $scope.languageJson.Config.Port.Incorrectly, 3000);/*'地址输入有误!'*/
                return false;
            }
            if ($scope.samplerUnit.DllPath == "" || $scope.samplerUnit.DllPath == undefined) {
                balert.show('danger', $scope.languageJson.Config.Port.SO, 3000);/*'请输入SO库名!'*/
                return false;
            }

            return true;
        }
        function AddEquipment(monitorUnitId) {
            //增加端口
            // FSU特殊处理
            if($scope.port.PortType == "1") $scope.port.PortType = "6";
            portService.getInsertPort($scope.port).then(function (data) {
                if (data == "fail to get insert port") {
                    //插入失败
                    balert.show('danger', $scope.languageJson.Config.Config.Failed, 3000);/*'插入端口失败,请检查连接是否正常!'*/
                    return;
                } else {
                    //插入成功,返回portId
                    $scope.samplerUnit.PortId = parseInt(data);
                    samplerUnitService.getInsertSamplerUnit($scope.samplerUnit).then(function (data) {
                        if (data == "fail to get insert samplerUnit") {
                            //插入失败
                            balert.show('danger', $scope.languageJson.Config.Config.Connection, 3000);/*'插入采集单元失败,请检查连接是否正常!'*/
                            return;
                        } else {
                            //插入成功,返回samplerUnitId
                            $scope.equipment.SamplerUnitId = parseInt(data);
                            $scope.equipment.StationId = $scope.stationId;
                            $scope.equipment.EquipmentTemplateId = $scope.equipmentTemplate.EquipmentTemplateId;
                            $scope.equipment.MonitorUnitId = $scope.monitorUnit.MonitorUnitId;

                            equipmentService.getInsertEquipment($scope.equipment,$scope.configurationType).then(function (data) {
                                if (data == "fail to get insert equipment") {
                                    //插入失败
                                    balert.show('danger', $scope.languageJson.Config.Config.Faileds, 3000);/*'插入设备失败,请检查连接是否正常!'*/
                                    return;
                                } else {
                                    $scope.equipmentItems = parseInt(data);
                                    $scope.paginationConf.totalItems = $scope.equipmentItems;

                                    balert.show('success', $scope.languageJson.Config.Config.Equipments, 3000);/*'增加设备成功!'*/
                                    addEquipmentDialog.hide();
                                }
                            });
                        }
                    });
                }
            });
        }
        //#endregion

        //#region 3.1.1.新增设备:选择协议文件
        var templateDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/selectTemplate.html',
            show: false
        });
        $scope.selectTemplateClick = function(){
            equipmentTemplateService.getAllEquipmentTemplate().then(function (data) {
                $scope.equipmentTemplates = data;

                //初始化
                $scope.equipmentTemplate = {};
                $scope.equipment = {};
                $scope.port = {};
                $scope.samplerUnit = {};
                $scope.portFlag = 0;

                templateDialog.$promise.then(templateDialog.show);
            });
        };
        $scope.selectEquipmentTemplateId = function (equipmentTemplateId) {
            $scope.selectedTemplateId = equipmentTemplateId;
        };
        $scope.select = function () {

            if ($scope.selectedTemplateId == undefined) {
                balert.show('danger', $scope.languageJson.Select.Please, 3000);/*请选择模板!*/
                return;
            }

            //获取所选模板
            equipmentTemplateService.getEquipmentTemplate($scope.selectedTemplateId).then(function (data) {
                $scope.equipmentTemplate = getEquipmentTemplate(data);

                //获取默认设备名
                equipmentService.getDefaultEquipment($scope.monitorUnit.MonitorUnitId, $scope.equipmentTemplate.EquipmentTemplateId).then(function (data) {
                    $scope.equipment = getEquipment(data);
                });

                //获取默认端口
                $scope.portNoChange(1);
            });

            $scope.selectedTemplateId = undefined;
            templateDialog.hide();
        };
        function getEquipmentTemplate(data) {
            var template = {};

            data.forEach(function (element, index) {
                template.EquipmentTemplateId = element.EquipmentTemplateId;
                template.EquipmentTemplateName = element.EquipmentTemplateName;
            });

            return template;
        }
        function getEquipment(data) {
            var equipment = {};

            data.forEach(function (element, index) {
                equipment.EquipmentId = element.EquipmentId;
                equipment.EquipmentName = element.EquipmentName;
                equipment.EquipmentType = element.EquipmentType;
            });

            return equipment;
        }
        function getPort(data) {
            var port = {};

            data.forEach(function (element, index) {
                port.PortId = element.PortId;
                port.MonitorUnitId = element.MonitorUnitId;
                port.PortName = element.PortName;
                port.PortNo = element.PortNo;
                port.PortType = element.PortType;
                port.Setting = element.Setting;
            });

            return port;
        }
        function getSamplerUnit(data) {
            var samplerUnit = {};

            data.forEach(function (element, index) {
                samplerUnit.SamplerUnitId = element.SamplerUnitId;
                samplerUnit.PortId = element.PortId;
                samplerUnit.MonitorUnitId = element.MonitorUnitId;
                samplerUnit.Address = element.Address;
                samplerUnit.DllPath = element.DllPath;
                samplerUnit.SamplerId = element.SamplerId;
                samplerUnit.SamplerType = element.SamplerType;
                samplerUnit.SamplerUnitName = element.SamplerUnitName;
            });

            return samplerUnit;
        }
        function parsePortByFSU(port, samplerUnit){
            if(port.PortType == "1"){
                if(samplerUnit && samplerUnit.Address){
                    var portNo = port.PortNo;
                    if(portNo.length < 2) portNo = "0"+portNo;
                    port.Setting = "127.0.0.1:80"+portNo;
                }
            }
            return port;
        }
        // 端口号 值变化事件
        $scope.portNoChange = function(portNo){
            portService.getDefaultPort($scope.monitorUnit.MonitorUnitId, portNo).then(function (data) {
                $scope.port = getPort(data);
                $scope.portFlag = 1;
                if($scope.port.PortType == "6" && parseInt($scope.port.PortNo) <= 16){
                    $scope.port.PortTypeVar = $scope.portTypes[0];
                    $scope.port.PortType = "1";
                }else{
                    for (var i = 0; i < $scope.portTypes.length; i++) {
                        if ($scope.portTypes[i].PortTypeId == $scope.port.PortType) {
                            $scope.port.PortTypeVar = $scope.portTypes[i];
                            break;
                        }
                    }
                }
                //获取默认采集单元
                samplerUnitService.getDefaultSamplerUnit($scope.equipmentTemplate.EquipmentTemplateId, $scope.port.PortId, $scope.port.PortNo, $scope.monitorUnit.MonitorUnitId).then(function (data) {
                    $scope.samplerUnit = getSamplerUnit(data);
                    // FSU版特殊处理
                    $scope.port = parsePortByFSU($scope.port, $scope.samplerUnit);
                });
            });
        };
        // 端口类型 值变化直接
        $scope.portTypeChange = function (portTypeId) {
            //portTypeId => 串口:1、SNMP口:3、虚拟端口:5、网口:6、简单逻辑口:19

            $scope.port.PortType = portTypeId;
            $(".address-text").html($scope.languageJson.Config.Equipment.Address);
            $(".address-input").show();

            //端口不重复
            if (portTypeId == 3 || portTypeId == 6 || portTypeId == 19) {
                var nextNo = 1;
                if ($scope.paginationConf && $scope.paginationConf.equipments) {
                    $scope.paginationConf.equipments.forEach(function (item) {
                        if (item.PortNo != 106 && parseInt(item.PortNo) > nextNo)
                            nextNo = parseInt(item.PortNo);
                    });
                }

                if ($scope.port.PortNo < 100) {
                    if (portTypeId == 3) {//SNMP
                        if (nextNo >= 150)
                            $scope.port.PortNo = nextNo + 1;
                        else
                            $scope.port.PortNo = 150;
                    } else if (portTypeId == 19) {//简单逻辑串口
                        if (nextNo > 200)
                            $scope.port.PortNo = nextNo + 1;
                        else
                            $scope.port.PortNo = 201;
                    } else {//网口
                        if (nextNo == 105)
                            $scope.port.PortNo = 107;
                        else if (nextNo >= 100)
                            $scope.port.PortNo = nextNo + 1;
                        else
                            $scope.port.PortNo = 100;
                    }
                }
            }

            //通讯参数文本  与  IP参数文本  切换
            if (portTypeId != 1 && portTypeId != 5) {
                $(".param-text").html($scope.languageJson.Config.Equipment.IPParameters);
            } else
                $(".param-text").html($scope.languageJson.Config.Equipment.Parameters);
            //通讯参数值
            if (portTypeId == 1) {//串口
                $scope.port.Setting = "127.0.0.1:8001";
                $scope.port.PortNo = 1;
            } else if (portTypeId == 3 || portTypeId == 6 || portTypeId == 19) {//SNMP口:3、网口:6、简单逻辑口:19
                $scope.port.Setting = "127.0.0.1:7070";
            } else if (portTypeId == 5) {//虚拟口
                $scope.port.Setting = "comm_io_dev.so";
                $scope.port.PortNo = 106;
            }
            $scope.portNoChange($scope.port.PortNo);
        };
        //#endregion
        
        //#region 3.2.新增IO设备
        var ioTemplateDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/selectIOTemplate.html',
            show: false
        });
        $scope.addIOEquipmentClick = function(){
            //增加设备前初始化
            $scope.equipmentTemplate = {};
            $scope.equipment = {};
            $scope.port = {};
            $scope.samplerUnit = {};

            //判断是否存在IO设备
            equipmentService.getIOEquipments($scope.stationId).then(function (data) {
                //返回IO设备个数
                var result = data;
                if (result == "fail to get io equipments") {
                    /*查看IO设备是否存在失败,请检查数据库连接是否正常*/
                    balert.show('danger', $scope.languageJson.Config.Config.Check, 3000);
                } else {
                    var ioEquipments = data.length;
                    if (ioEquipments > 0) {
                        balert.show('danger', $scope.languageJson.Config.Config.Already, 3000);/*已存在IO设备,不允许重复增加!*/
                    } else {
                        //插入IO设备
                        /*请确认是否增加IO设备?*/
                        bconfirm.show($scope, $scope.languageJson.Config.Config.Pease).then(function (data) {
                            if (data) {
                                InsertIOEquipment();
                            }
                        });
                    }
                }
            });
        };
        $scope.selectIO = function () {
            if ($scope.selectedIOTemplateId == undefined) {
                balert.show('danger', $scope.languageJson.Select.Please, 3000);/*请选择模板!*/
                return;
            }

            AddIOEquipment($scope.selectedIOTemplateId);

            ioTemplateDialog.hide();
        };
        $scope.selectIOEquipmentTemplateId = function (equipmentTemplateId) {
            $scope.selectedIOTemplateId = equipmentTemplateId;
        };
        function InsertIOEquipment() {

            //第一步:获取IO模板
            equipmentTemplateService.getIOEquipmentTemplates().then(function (data) {

                var ioEquipmentTemplateId = -1;
                var result = data;

                if (result == "fail to get io equipmentTemplates") {
                    balert.show('danger', $scope.languageJson.Config.Port.Failed, 3000);/*'获取IO模板失败,请检查数据库连接是否正常!'*/
                    return;
                } else {
                    //获取IO模板成功
                    $scope.ioEquipmentTemplates = data;

                    //第二步:获取IO模板ID
                    if ($scope.ioEquipmentTemplates.length <= 0) {
                        //没有IO模板
                        balert.show('danger', $scope.languageJson.Config.Port.Entereds, 3000);/*'没有找到IO模板,请在协议管理中增加IO模板!'*/
                        return;
                    } else if ($scope.ioEquipmentTemplates.length > 1) {
                        //存在多个IO模板,需要弹出对话框供用户选择
                        $scope.selectedIOEquipmentTemplateId = -1;

                        ioTemplateDialog.$promise.then(ioTemplateDialog.show);
                        return;
                    } else {
                        ioEquipmentTemplateId = $scope.ioEquipmentTemplates[0].EquipmentTemplateId;
                    }
                }

                //第三步:增加IO设备
                AddIOEquipment(ioEquipmentTemplateId);
            });
        }
        function AddIOEquipment(equipmentTemplateId) {
            //获取所选模板
            equipmentTemplateService.getEquipmentTemplate(equipmentTemplateId).then(function (data) {
                $scope.equipmentTemplate = getEquipmentTemplate(data);

                //获取默认端口
                portService.getDefaultPort($scope.monitorUnit.MonitorUnitId, 106).then(function (data) {
                    if(parseInt($scope.port.PortType) > 1 && parseInt(data[0].PortType) > 1) return;
                    $scope.port = getPort(data);
                    // FSU版特殊处理
                    $scope.port.PortType = "6";
                    $scope.port.Setting = "127.0.0.1:8101";

                    //获取默认采集单元
                    samplerUnitService.getDefaultSamplerUnit($scope.equipmentTemplate.EquipmentTemplateId, $scope.port.PortId, $scope.port.PortNo, $scope.monitorUnit.MonitorUnitId).then(function (data) {
                        $scope.samplerUnit = getSamplerUnit(data);

                        //获取默认设备
                        equipmentService.getDefaultEquipment($scope.monitorUnit.MonitorUnitId, $scope.equipmentTemplate.EquipmentTemplateId).then(function (data) {
                            $scope.equipment = getEquipment(data);

                            AddEquipment($scope.monitorUnit.MonitorUnitId);
                        });
                    });
                });
            });
        }
        //#endregion

        //#region 3.3新增自诊断设备
        var hostEquipmentDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/selectHostTemplate.html',
            show: false
        });
        $scope.addHostEquipmentClick = function () {

            equipmentService.getHostEquipments($scope.stationId).then(function (data) {
                var result = data;
                if (result == "fail to get io equipments") {
                    /*查看自诊断设备是否存在失败,请检查数据库连接是否正常*/
                    balert.show('danger', $scope.languageJson.Config.AddHost.GetErrorPrompt, 3000);
                } else {
                    var equipments = data.length;
                    if (equipments > 0) {
                        balert.show('danger', $scope.languageJson.Config.AddHost.ExistPrompt, 3000);/*已存在自诊断设备,不允许重复增加!*/
                    } else {
                        //插入IO设备
                        /*请确认是否增加自诊断设备?*/
                        bconfirm.show($scope, $scope.languageJson.Config.AddHost.SelectPrompt).then(function (data) {
                            if (data) {
                                InsertHostEquipment();
                            }
                        });
                    }
                }
            });
        };
        function InsertHostEquipment() {
            //第一步:获取IO模板
            equipmentTemplateService.getHostEquipmentTemplates().then(function (data) {

                var hostEquipmentTemplateId = -1;
                var result = data;

                if (result == "fail to get io equipmentTemplates") {
                    balert.show('danger', $scope.languageJson.Config.Port.Failed, 3000);/*'获取IO模板失败,请检查数据库连接是否正常!'*/
                    return;
                } else {
                    //获取自诊断模板成功
                    $scope.hostEquipmentTemplates = data;

                    //第二步:获取自诊断模板ID
                    if ($scope.hostEquipmentTemplates.length <= 0) {
                        //没有自诊断模板
                        balert.show('danger', $scope.languageJson.Config.AddHost.NoExistPrompt, 3000);/*'没有找到自诊断模板,请在协议管理中增加自诊断模板!'*/
                        return;
                    } else if ($scope.hostEquipmentTemplates.length > 1) {
                        //存在多个自诊断模板,需要弹出对话框供用户选择
                        $scope.selectedHostTemplateId = undefined;

                        hostEquipmentDlg.$promise.then(hostEquipmentDlg.show);
                        return;
                    } else {
                        hostEquipmentTemplateId = $scope.hostEquipmentTemplates[0].EquipmentTemplateId;
                    }
                }

                //第三步:增加自诊断设备
                AddHostEquipment(hostEquipmentTemplateId);
            });
        }
        $scope.selectHostEquipmentTemplateId = function (equipmentTemplateId) {
            $scope.selectedHostTemplateId = equipmentTemplateId;
        };
        $scope.selectHost = function () {

            if ($scope.selectedHostTemplateId == undefined) {
                balert.show('danger', $scope.languageJson.Select.Please, 3000);/*请选择模板!*/
                return;
            }

            AddHostEquipment($scope.selectedHostTemplateId);

            hostEquipmentDlg.hide();
        };
        function AddHostEquipment(equipmentTemplateId) {
            //获取所选模板
            equipmentTemplateService.getEquipmentTemplate(equipmentTemplateId).then(function (data) {
                $scope.equipmentTemplate = getEquipmentTemplate(data);

                //获取默认端口
                portService.getDefaultPort($scope.monitorUnit.MonitorUnitId, 31).then(function (data) {
                    $scope.port = getPort(data);

                    //获取默认采集单元
                    samplerUnitService.getDefaultSamplerUnit($scope.equipmentTemplate.EquipmentTemplateId, $scope.port.PortId, $scope.port.PortNo, $scope.monitorUnit.MonitorUnitId).then(function (data) {
                        $scope.samplerUnit = getSamplerUnit(data);

                        //获取默认设备
                        equipmentService.getDefaultEquipment($scope.monitorUnit.MonitorUnitId, $scope.equipmentTemplate.EquipmentTemplateId).then(function (data) {
                            $scope.equipment = getEquipment(data);

                            AddEquipment($scope.monitorUnit.MonitorUnitId);
                        });
                    });
                });
            });
        }
        //#endregion

        //#region 3.4.修改设备
        var updEquipmentDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/updEquipment.html',
            show: false
        });
        $scope.updateEquipmentClick = function (data) {
            //var e = $scope.paginationConf.equipments;
            $scope.equipment = data;
            portService.getDefaultPort(data.MonitorUnitId, data.PortNo).then(function (port) {
                if (port.length > 0) {

                    $scope.equipment.Setting = port[0].Setting;
                    $scope.equipment.PortId = port[0].PortId;
                    $scope.equipment.PortType = port[0].PortType;
                    // FSU特殊处理
                    if($scope.equipment.PortType == "6" && parseInt(port[0].PortNo) <= 16){
                        $scope.equipment.PortType = "1";
                    }

                    //是否有其他同端口的设备,如果有其他端口则不允许修改“端口类型”和“通讯参数”
                    var isExist = isOtherPortExist(data.EquipmentId, port[0].PortNo);
                    if (isExist) $scope.equipment.readonly = true;
                    else $scope.equipment.readonly = false;

                    samplerUnitService.getDefaultSamplerUnit(data.EquipmentTemplateId, port[0].PortId, port[0].PortNo, data.MonitorUnitId).then(function (unit) {
                        if (unit.length > 0) {
                            $scope.samplerUnit = unit[0];
                        }
                    });

                    $scope.equipment.EquipmentTemplateName = getEquipmentTemplateNameById(data.EquipmentTemplateId);
                }
            });
            updEquipmentDlg.$promise.then(updEquipmentDlg.show);
        };
        function getEquipmentTemplateNameById(etid) {
            var etname = "";
            if ($scope.equipmentTemplates) {
                $scope.equipmentTemplates.forEach(function (item) {
                    if (item.EquipmentTemplateId == etid)
                        etname = item.EquipmentTemplateName;
                });
            }
            return etname;
        }
        function isOtherPortExist(equipment, portNo) {
            var is = false;
            if ($scope.paginationConf && $scope.paginationConf.equipments) {
                $scope.paginationConf.equipments.forEach(function (item) {
                    if (item.PortNo == portNo) {
                        if (item.EquipmentId != equipment)
                            is = true;
                    }
                });
            }
            return is;
        }
        $scope.updClick = function () {
            if ($scope.equipment.EquipmentId == "" || $scope.equipment.EquipmentName == "" || $scope.equipment.PortNo == ""
                || $scope.equipment.PortType == "" || $scope.equipment.Setting == "" || $scope.equipment.Address == "") {
                balert.show('danger', $scope.languageJson.Config.Confirms.Device, 3000);/*'设备信息均不能为空!'*/
                return;
            }
            equipmentService.checkEquipmentConfig($scope.equipment.EquipmentId, $scope.equipment.EquipmentName,
                $scope.equipment.PortNo, $scope.equipment.Address).then(function (result) {
                if (result == "OK") {
                    //添加端口
                    // FSU特殊处理
                    if($scope.equipment.PortType == "1") $scope.equipment.PortType = "6";
                    portService.getInsertPort($scope.equipment).then(function (portId) {
                        if (portId == "fail to get insert port") {
                            balert.show('danger', $scope.languageJson.Config.Config.Failed, 3000);/*'插入端口失败,请检查连接是否正常!'*/
                            return;
                        } else {
                            //添加采集单元
                            $scope.samplerUnit.PortId = parseInt(portId);
                            $scope.samplerUnit.Address = $scope.equipment.Address;
                            //修改so库
                            if ($scope.equipment.DllPath != $scope.samplerUnit.DllPath) {
                                $scope.samplerUnit.SamplerUnitId = -1;
                                $scope.samplerUnit.DllPath = $scope.equipment.DllPath;
                            }
                            samplerUnitService.getInsertSamplerUnit($scope.samplerUnit).then(function (units) {
                                if (units == "fail to get insert samplerUnit") {
                                    balert.show('danger', $scope.languageJson.Config.Config.Connection, 3000);/*'插入采集单元失败,请检查连接是否正常!'*/
                                    return;
                                } else {
                                    $scope.equipment.SamplerUnitId = parseInt(units);
                                    //修改设备
                                    equipmentService.updateEquipment($scope.equipment.EquipmentId, $scope.equipment.EquipmentName, $scope.equipment.Vendor, $scope.equipment.SamplerUnitId).then(function (data) {
                                        if (data == "OK") {
                                            balert.show('success', $scope.languageJson.Config.Confirms.Modify, 3000);/*'修改设备成功!'*/
                                            $scope.equipment = {};
                                            updEquipmentDlg.hide();
                                        } else {
                                            balert.show('danger', $scope.languageJson.Config.Confirms.Modifying, 3000);/*'修改设备失败!'*/
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else if (result == "Name Exists") {
                    balert.show('danger', $scope.languageJson.Config.Confirms.Exists, 3000);/*'设备名称已存在!'*/
                    return;
                } else if (result == "Address Exists") {
                    balert.show('danger', $scope.languageJson.Config.Confirms.Port, 3000);/*'同端口的地址不能重复!'*/
                    return;
                }
            });
        };

        $scope.changePortNo = function (newValue, oldValue) {
            if (newValue == undefined || newValue == oldValue) return;
            portService.getDefaultPort($scope.equipment.MonitorUnitId, newValue).then(function (port) {
                if (port.length > 0) {
                    $scope.equipment.Setting = port[0].Setting;
                    $scope.equipment.PortId = port[0].PortId;
                    $scope.equipment.PortType = port[0].PortType;

                    var isExist = isOtherPortExist(newValue);
                    if (port[0].PortId != -1 && isExist) $scope.equipment.readonly = true;
                    else $scope.equipment.readonly = false;

                    samplerUnitService.getDefaultSamplerUnit($scope.equipment.EquipmentTemplateId, port[0].PortId, port[0].PortNo, $scope.equipment.MonitorUnitId).then(function (unit) {
                        if (unit.length > 0) {
                            $scope.samplerUnit = unit[0];
                            // FSU特殊处理
                            $scope.equipment = parsePortByFSU($scope.equipment, $scope.samplerUnit);
                        }
                    });
                }
            });
        };
        //#endregion

        //#region 3.4.1.修改设备:重新绑定设备模板
        var templateListDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/equipmentTemplates.html',
            show: false
        });
        $scope.showTemplateListClick = function (templateId) {
            if ($scope.equipmentTemplates) {
                $scope.equipmentTemplates.forEach(function (item) {
                    if (item.EquipmentTemplateId == templateId) {
                        // 解决DLL后缀问题
                        if(item.SoName.toUpperCase().indexOf("DLL") > -1) {
                            var index = item.SoName.lastIndexOf(".");
                            item.SoName = item.SoName.substring(0,index)+".so";
                        }
                        $scope.Rebinding = item;

                        $scope.Rebinding.CategoryName = getCategoryName($scope.Rebinding.EquipmentCategory);
                        $scope.Rebinding.PropertyName = getPropertyName($scope.Rebinding.Property);
                    }
                });
            }
            templateListDlg.$promise.then(templateListDlg.show);
        };
        function getCategoryName(category) {
            var name = category;
            if ($scope.Template.EquipmentCategory) {
                $scope.Template.EquipmentCategory.forEach(function (item) {
                    if (item.ItemId == category) {
                        if ($scope.languageJson.Language == "English")
                            name = item.ItemAlias;
                        else
                            name = item.ItemValue;
                    }
                });
            }
            return name;
        }
        function getPropertyName(property) {
            var result = "";
            var name = "";
            var pros = property.split("/");
            if (pros) {
                pros.forEach(function (pro) {
                    if ($scope.Template.Property) {
                        $scope.Template.Property.forEach(function (item) {
                            if (pro == item.ItemId) {
                                if ($scope.languageJson.Language == "English")
                                    name = item.ItemAlias;
                                else
                                    name = item.ItemValue;
                            }
                        });
                    }
                    if (result == "")
                        result = name;
                    else
                        result += "/" + name;
                });
            }
            return result;
        }
        $scope.changeRebinding = function (obj) {
            $scope.Rebinding = angular.fromJson(obj);
            // 解决DLL后缀问题
            if($scope.Rebinding.SoName.toUpperCase().indexOf("DLL") > -1) {
                var index = $scope.Rebinding.SoName.lastIndexOf(".");
                $scope.Rebinding.SoName = $scope.Rebinding.SoName.substring(0,index)+".so";
            }

            $scope.Rebinding.CategoryName = getCategoryName($scope.Rebinding.EquipmentCategory);
            $scope.Rebinding.PropertyName = getPropertyName($scope.Rebinding.Property);
        };
        //重新绑定模板
        $scope.rebindingClick = function () {
            var equipmentId = $scope.equipment.EquipmentId;
            var equipmentTemplateId = $scope.Rebinding.EquipmentTemplateId;
            $scope.equipment.DllPath = $scope.Rebinding.SoName;

            equipmentService.RebindingEquipmentTemplate(equipmentId, equipmentTemplateId).then(function (data) {
                if (data == "OK") {
                    balert.show('success', $scope.languageJson.Config.Confirms.Modify, 3000);/*'修改设备成功!'*/
                    $scope.equipment.EquipmentTemplateId = $scope.Rebinding.EquipmentTemplateId;
                    $scope.equipment.EquipmentTemplateName = $scope.Rebinding.EquipmentTemplateName;
                    templateListDlg.hide();
                } else {
                    balert.show('danger', "[" + data + "]" + $scope.languageJson.Config.Confirms.Modifying, 3000);/*'修改设备失败!'*/
                }
            });
        };
        //#endregion

        //#region 3.5.删除设备
        $scope.removeEquipmentClick = function (id, name, samplerUnitId) {
            $scope.selectedEquipmentId = id;
            $scope.selectedEquipmentName = name;

            bconfirm.show($scope, $scope.languageJson.Config.Confirms.Title + $scope.selectedEquipmentId + ")" + $scope.selectedEquipmentName + "?").then(function (data) {
                if (data) {
                    equipmentService.deleteEquipment($scope.stationId, $scope.selectedEquipmentId, samplerUnitId).then(function (data) {
                        //删除完成后,返回设备个数
                        var result = data;
                        if (result == "fail to delete equipment") {
                            balert.show('danger', $scope.languageJson.Config.Confirms.Deleting, 3000);/*'删除设备失败,请检查连接是否正常!'*/
                        } else {
                            $scope.equipmentItems = parseInt(data);
                            $scope.paginationConf.totalItems = $scope.equipmentItems;
                            balert.show('success', $scope.languageJson.Config.Confirms.Successfully, 3000);/*'删除设备成功!'*/
                        }
                    });
                }
            });
        };
        //#endregion

        //#region 3.6.配置生效
        $scope.reLoadEquipmentConfigClick = function () {
            /*请确认是否执行配置生效?*/
            bconfirm.show($scope, $scope.languageJson.Config.Config.Whether).then(function (data) {
                if (data) {
                    $scope.loading = true;
                    equipmentService.reLoadEquipment($scope.stationId, $scope.station.stationName).then(function (data) {
                        //删除完成后,返回设备个数
                        var result = data;
                        var ver = localStorage.getItem("versions");
                        if (result == "fail to reload equipment") {
                            balert.show('danger', $scope.languageJson.Config.Config.Sails, 3000);/*执行配置生效失败,请检查连接是否正常!*/
                        } else {
                            if (ver == "IView") {
                                balert.show('success', $scope.languageJson.Config.Config.Configuration, 3000);/*'执行配置生效成功!'*/
                            }
                            else{
                                balert.show('success', $scope.languageJson.Config.Config.Configuration, 3000);/*'执行配置生效成功!'*/
                                $("#side-menu .sub-li").remove();
                                deviceService.getAllDevicesType().then();
                            }
                        }
                        $scope.loading = false;
                        // 重新加载组态列
                        $rootScope.$emit("loadSidebar");
                    });
                    //生成备份文件
                    equipmentService.CreateConfigManager().then(function (data) {
                    });
                }
            });
        };
        //#endregion

        //#endregion
    
        //#region 4.局站信息管理
        $scope.saveStationConfigClick = function () {
            if ($scope.station.stationName === undefined ||
                $scope.station.contactId == -1) {
                //'局站信息不完整,请检查是否输入完整!'
                balert.show('danger', $scope.languageJson.Config.Stations.Input, 3000);
                return;
            }
            $scope.loading = true;
            stationService.updateStationInfo($scope.stationId, $scope.station.stationName, $scope.station.contactId, $scope.station.remark).then(function (data) {
                if (data == "OK") {
                    equipmentService.ReLoadFSU().then(function (data) {
                        $scope.loading = false;
                        balert.show('success', $scope.languageJson.Config.Stations.Successfully, 3000);//'保存局站配置成功!'
                    });

                } else {
                    //'保存局站配置失败!'
                    balert.show('danger', $scope.languageJson.Config.Stations.Failed, 3000);
                }
            });
        };
        $scope.contactManChange = function (EmployeeId) {
            $scope.station.contactId = EmployeeId;
        };
        //#endregion
    
        //#region 5.中心信息管理
        $scope.saveCenterConfigClick = function () {
            if ($scope.center.centerIP === undefined || $scope.center.centerDSIP === undefined ||
                $scope.center.centerPort == -1 || $scope.center.centerPort == undefined) {
                balert.show('danger', $scope.languageJson.Config.Room.The, 3000);/*中心信息不完整,请检查是否输入完整!*/
                return;
            }
            $scope.loading = true;
            stationService.updateCenterInfo($scope.center.centerId, $scope.center.centerIP, $scope.center.centerPort, $scope.center.centerDSIP, $scope.center.Enable).then(function (data) {
                if (data == "OK") {
                    equipmentService.ReLoadFSU().then(function (data) {
                        $scope.loading = false;
                        balert.show('success', $scope.languageJson.Config.Room.Center, 3000);/*'保存中心配置成功!'*/
                    });
                } else {
                    balert.show('danger', $scope.languageJson.Config.Room.Saves, 3000);/*'保存中心配置失败!'*/
                }
            });
        };

        $scope.resetCenterConfigClick = function () {
            $scope.center = {};
            $scope.center.centerId = -1;
            $scope.center.centerIP = "";
            $scope.center.centerPort = 15001;
            $scope.center.centerDSIP = "";
            $scope.center.Enable = false;
        };

        $scope.selectEnable = function () {
            var a = $scope.center.Enable;
        };
        //#endregion

        //#region 6.模板管理
        //#region 6.1.设备模板
        // 查询
        $scope.selectEventClick = function () {
            document.querySelector("#rollBtn").style.display = "block";
            document.querySelector("#rollAlarm").style.display = "block";
            if ($scope.selectEvent.EquipmentTemplateId == undefined) {
                balert.show('danger', $scope.languageJson.Config.Templatenames.Please, 3000);/*'请选择设备模板!'*/
                return;
            }

            //遍历选中的模板设备编号
            $scope.equipmentTemplates.forEach(function (item) {
                if (item.EquipmentTemplateId == $scope.selectEvent.EquipmentTemplateId)
                    $scope.selectEvent.EquipmentBaseType = item.EquipmentBaseType;
            });

            TemplateService.GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (data) {
                TemplateService.GetSignalMeaningsByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (datas) {
                    $scope.SignalMeaningsList = datas;
                    $scope.SignalList = parseSignalList(data, datas);
                    $scope.filterSignalList = $filter('filter')($scope.SignalList, $scope.query);

                    GetEventByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);

                    GetControlByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                });
            });
        };
        //查询信号
        function GetSignalByEquipmentTemplateId(EquipmentTemplateId) {
            TemplateService.GetSignalByEquipmentTemplateId(EquipmentTemplateId).then(function (data) {
                TemplateService.GetSignalMeaningsByEquipmentTemplateId(EquipmentTemplateId).then(function (datas) {
                    $scope.SignalMeaningsList = datas;
                    $scope.SignalList = parseSignalList(data, datas);
                    $scope.filterSignalList = $filter('filter')($scope.SignalList, $scope.query);
                    document.getElementById('signalListSelAll').indeterminate = false
                });
            });
        };
        //查询事件
        function GetEventByEquipmentTemplateId(EquipmentTemplateId) {
            TemplateService.GetEventByEquipmentTemplateId(EquipmentTemplateId).then(function (data) {
                TemplateService.GetEventConditionByEquipmentTemplateId(EquipmentTemplateId).then(function (datas) {
                    $scope.EventConditionList = datas;
                    $scope.EventList = parseEventList(data, datas);
                });
            });
        };
        //查询控制
        function GetControlByEquipmentTemplateId(EquipmentTemplateId) {
            TemplateService.GetControlByEquipmentTemplateId(EquipmentTemplateId).then(function (data) {
                TemplateService.GetControlMeaningsByEquipmentTemplateId(EquipmentTemplateId).then(function (datas) {
                    $scope.ControlMeaningsList = datas;
                    $scope.ControlList = parseControlList(data, datas);
                });
            });
        };
        function parseSignalList(data, datas) {
            data.forEach(function (item) {
                $scope.Signal.SignalCategory.forEach(function (es) {
                    if (item.SignalCategory == es.ItemId) {
                        item.SignalCategoryName = getLanguageItem(es);
                    }
                });
                $scope.Signal.ChannelType.forEach(function (es) {
                    if (item.ChannelType == es.ItemId) {
                        item.ChannelTypeName = getLanguageItem(es);
                    }
                });
                $scope.Signal.DataType.forEach(function (es) {
                    if (item.DataType == es.ItemId) {
                        item.DataTypeName = getLanguageItem(es);
                    }
                });
                if (item.Enable == 'true' || item.Visible == 'true') item.IsOpen = true;
                else item.IsOpen = false;

                if (datas) {
                    item.DataMeanings = [];
                    datas.forEach(function (sm) {
                        if (item.SignalId == sm.SignalId) {
                            if (item.Meanings == undefined) {
                                item.Meanings = sm.Meanings;
                            } else {
                                item.Meanings += "/" + sm.Meanings;
                            }
                            item.DataMeanings.push(sm);
                        }
                    });
                }
            });
            return data;
        };
        function parseEventList(data, datas) {
            data.forEach(function (item) {
                $scope.Event.EventCategory.forEach(function (es) {
                    if (item.EventCategory == es.ItemId) {
                        item.EventCategoryName = getLanguageItem(es);
                    }
                });
                $scope.Event.StartType.forEach(function (es) {
                    if (item.StartType == es.ItemId) {
                        item.StartTypeName = getLanguageItem(es);
                    }
                });
                $scope.Event.EndType.forEach(function (es) {
                    if (item.EndType == es.ItemId) {
                        item.EndTypeName = getLanguageItem(es);
                    }
                });
                if (item.Enable == 'true' || item.Visible == 'true') item.IsOpen = true;
                else item.IsOpen = false;

                if (datas) {
                    item.EventCondition = [];
                    datas.forEach(function (ec) {
                        if (item.EventId == ec.EventId) {
                            if (item.EventSeverity == undefined) {
                                item.EventSeverity = ec.EventSeverity;
                                item.EventSeverityName = getEventSeverityName(ec.EventSeverity);
                                item.Meanings = ec.EventConditionId;
                            } else {
                                item.EventSeverity += "/" + ec.EventSeverity;
                                item.EventSeverityName += "/" + getEventSeverityName(ec.EventSeverity);
                                item.Meanings += "/" + ec.EventConditionId;
                            }
                            item.EventCondition.push(ec);
                        }
                    });
                }

                if ($scope.SignalList) {
                    $scope.SignalList.forEach(function (s) {
                        if (item.SignalId == s.SignalId) {
                            item.SignalName = s.SignalName;
                        }
                    });
                }

                if (item.Enable == "true" || item.Enable == true)
                    item.Shield = false;
                else
                    item.Shield = true;
            });
            return data;
        };
        function getEventSeverityName(severity) {
            var name = "";
            if ($scope.Event.EventSeverity) {
                $scope.Event.EventSeverity.forEach(function (item) {
                    if (item.ItemId == severity) {
                        if ($scope.languageJson.Language == "English")
                            name = item.ItemAlias;
                        else
                            name = item.ItemValue;
                    }
                });
            }
            return name;
        }
        function parseControlList(data, datas) {
            data.forEach(function (item) {
                $scope.Control.ControlCategory.forEach(function (es) {
                    if (item.ControlCategory == es.ItemId) {
                        item.ControlCategoryName = getLanguageItem(es);
                    }
                });
                $scope.Control.ControlSeverity.forEach(function (es) {
                    if (item.ControlSeverity == es.ItemId) {
                        item.ControlSeverityName = getLanguageItem(es);
                    }
                });
                $scope.Control.CommandType.forEach(function (es) {
                    if (item.CommandType == es.ItemId) {
                        item.CommandTypeName = getLanguageItem(es);
                    }
                });
                $scope.Control.ControlType.forEach(function (es) {
                    if (item.ControlType == es.ItemId) {
                        item.ControlTypeName = getLanguageItem(es);
                    }
                });
                $scope.Control.DataType.forEach(function (es) {
                    if (item.DataType == es.ItemId) {
                        item.DataTypeName = getLanguageItem(es);
                    }
                });
                if (item.Enable == 'true' || item.Visible == 'true') item.IsOpen = true;
                else item.IsOpen = false;

                if (datas) {
                    item.DataMeanings = [];
                    datas.forEach(function (cm) {
                        if (item.ControlId == cm.ControlId) {
                            if (item.Meanings == undefined) {
                                item.Meanings = cm.Meanings;
                            } else {
                                item.Meanings += "/" + cm.Meanings;
                            }
                            item.DataMeanings.push(cm);
                        }
                    });
                }

                if ($scope.SignalList) {
                    $scope.SignalList.forEach(function (s) {
                        if (item.SignalId == s.SignalId) {
                            item.SignalName = s.SignalName;
                        }
                    });
                }
            });
            return data;
        }
        function getLanguageItem(item) {
            if ($scope.languageJson == undefined)
                $scope.languageJson = angular.fromJson(sessionStorage.getItem('languageJson'));
            var lan = $scope.languageJson.Language;
            if (lan == 'English') return item.ItemAlias
            else return item.ItemValue
        }

        //修改模版
        var ModifyTemplateDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/ModifyTemplate.html',
            show: false
        });
        $scope.UpdateEquipmentTemplateClick = function () {
            $scope.equipmentTemplates.forEach(function (item) {
                if (item.EquipmentTemplateId == $scope.selectEvent.EquipmentTemplateId) {
                    $scope.UpdateTemplate = item;
                    ModifyTemplateDialog.$promise.then(ModifyTemplateDialog.show);
                    checkoutProperty($scope.UpdateTemplate.Property);
                    return;
                }
            });
        };
        function checkoutProperty(data) {
            var d = data.split("/");
            if (data)
                $scope.UpdateTemplate.Property = data;
            else
                $scope.UpdateTemplate.Property = "";
            if ($scope.Template.Property)
                $scope.Template.Property.forEach(function (item) {
                    item.isChecked = false;
                    var str = [];
                    d.forEach(function (pro) {
                        if (pro == item.ItemId) {
                            item.isChecked = true;
                        }
                    });
                });
        };
        //设备模板属性
        $scope.isShowProperty = false;
        $scope.showProperty = function () {
            //$("#myProperty").show();
            $("#myProperty").css("display", "block");
            $scope.isShowProperty = true;
        };
        $(function () {
            $(document).click(function (e) {
                var myDiv = $("#myProperty");
                if (myDiv.css("display") == "block" && $scope.isShowProperty == false) {
                    //$("#myProperty").hide();
                    $("#myProperty").css("display", "none");
                }
                $scope.isShowProperty = false;
            });
        });
        $scope.ClickProperty = function (id) {
            if ($scope.Template.Property)
                $scope.Template.Property.forEach(function (item) {
                    if (item.ItemId == id) {
                        if (!item.isChecked) {
                            item.isChecked = true;
                            $scope.UpdateTemplate.Property = sortProperty($scope.UpdateTemplate.Property, id, true);
                        } else {
                            item.isChecked = false;
                            $scope.UpdateTemplate.Property = sortProperty($scope.UpdateTemplate.Property, id, false);
                        }
                    }
                });
        };
        function sortProperty(str, pro, isAdd) {
            var result = "";
            if (isAdd) {//添加
                if (str == "" || str == undefined) result = pro;
                else {
                    str = str + "/" + pro;
                    var arr = str.split("/");
                    arr = arr.sort();
                    for (var i = 0; i < arr.length; i++) {
                        if (result == "")
                            result += arr[i];
                        else
                            result += "/" + arr[i];
                    }
                }
            } else {//删除
                var arr = str.split("/");
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] == pro) continue;
                    if (result == "")
                        result += arr[i];
                    else
                        result += "/" + arr[i];
                }
            }
            return result;
        };
        $scope.SaveEquipmentTemplate = function () {
            var is = false;
            $scope.equipmentTemplates.forEach(function (item) {
                if ($scope.UpdateTemplate.EquipmentTemplateId != item.EquipmentTemplateId &&
                    $scope.UpdateTemplate.EquipmentTemplateName == item.EquipmentTemplateName) {
                    is = true;
                }
            });
            if (is) {
                balert.show('danger', $scope.languageJson.Config.Templatenames.Title, 3000);/*'模板名称不能相同!'*/
                return;
            }
            if ($scope.UpdateTemplate.EquipmentTemplateName == "" || $scope.UpdateTemplate.EquipmentTemplateName == undefined) {
                balert.show('danger', $scope.languageJson.Config.Templatenames.Cannot, 3000);/*'模板名称不能为空!'*/
                return;
            }
            if ($scope.UpdateTemplate.EquipmentCategory == "" || $scope.UpdateTemplate.EquipmentCategory == undefined) {
                balert.show('danger', $scope.languageJson.Config.Templatenames.Type, 3000);/*'类型不能为空!'*/
                return;
            }
            if ($scope.UpdateTemplate.EquipmentBaseType == "" || $scope.UpdateTemplate.EquipmentBaseType == undefined) {
                balert.show('danger', $scope.languageJson.Config.Templatenames.Empty, 3000);/*'设备基类不能为空!'*/
                return;
            }

            TemplateService.SaveEquipmentTemplate($scope.UpdateTemplate).then(function (data) {
                if (data == "SUCCESS") {
                    balert.show('success', $scope.languageJson.Config.Templatenames.Successfully, 3000);/*'修改成功!'*/
                    ModifyTemplateDialog.hide();
                } else
                    balert.show('danger', $scope.languageJson.Config.Templatenames.Fail, 3000);/*'修改失败!'*/
            });
        };

        // 导出协议模板
        $scope.ExportProtocol = function (templateId) {
            $scope.loading = true;
            TemplateService.ExportProtocol(templateId).then(function (data) {
                $scope.loading = false;
            });
        };
        //#endregion

        //#region 6.2.信号管理
        //#region 6.2.1.新增/修改信号
        var SignalSetterDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/SignalSetter.html',
            show: false
        });
        // 新增页面弹出框
        $scope.AddSignal = function () {
            //console.log($scope.paginationConf.equipments);
            if ($scope.selectEvent.EquipmentBaseType != undefined &&
                (parseInt($scope.selectEvent.EquipmentBaseType) >= 1100 && parseInt($scope.selectEvent.EquipmentBaseType) < 1200))
                $scope.ChargeShow = true;
            else
                $scope.ChargeShow = false;

            $scope.btnName = $scope.languageJson.Config.Signal.News;/*新增*/
            TemplateService.GetNextSignalId($scope.selectEvent.EquipmentTemplateId, 'Signal').then(function (data) {
                $scope.Signals = {
                    EquipmentTemplateId: $scope.selectEvent.EquipmentTemplateId,
                    DeviceId:"-1",
                    SignalId: parseInt(data) + 1,
                    SignalName: $scope.languageJson.Config.Config.Newsignal,
                    SignalType: '2',
                    ChannelNo: '-2',
                    ChannelType: '1',
                    DataType: '0',
                    SignalCategory: '1',
                    ShowPrecision: '0',
                    Enable: true,
                    Visible: true,
                    BaseTypeId: '',
                    Expression: '',
                    Unit: '',
                    StoreInterval: '',
                    AbsValueThreshold: '',
                    PercentThreshold: '',
                    StaticsPeriod: '',
                    ChargeStoreInterVal: '',
                    ChargeAbsValue: '',
                    IsBaseNameExt: "display:none;"
                };/*'新信号'*/
                $scope.CategoryHide = false;
                SignalSetterDialog.$promise.then(SignalSetterDialog.show);
                setTimeout(function () {
                    $("#Inspect-Hint").attr("data-original-title", "<h5>" + $scope.languageJson.Config.Signal.Accuracys + "</h5>");
                }, 500);
            });
            TemplateService.GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (data) {
                TemplateService.GetSignalMeaningsByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (datas) {
                    $scope.SignalMeaningsList = datas;
                    $scope.SignalList2 = parseSignalList(data, datas);
                });
            });
        };
        // 修改信号弹出框
        $scope.updateSignalClick = function (data) {
            if ($scope.selectEvent.EquipmentBaseType != undefined &&
                (parseInt($scope.selectEvent.EquipmentBaseType) >= 1100 && parseInt($scope.selectEvent.EquipmentBaseType) < 1200))
                $scope.ChargeShow = true;
            else
                $scope.ChargeShow = false;

            $scope.btnName = $scope.languageJson.Config.Config.Modify/*"修改"*/;
            $scope.Signals = data;
            if (data.Enable == 'true') $scope.Signals.Enable = true;
            if (data.Visible == 'true') $scope.Signals.Visible = true;
            $scope.ChangeCategory($scope.Signals.SignalCategory);
            SignalSetterDialog.$promise.then(SignalSetterDialog.show);
        };
        var oldNo;
        $scope.ChangeSignalType = function (type) {
            if (type == 2) {
                oldNo = $scope.Signals.ChannelNo;
                if ($scope.Signals.SignalId == -3)
                    $scope.Signals.ChannelNo = -3;
                else
                    $scope.Signals.ChannelNo = -2;
            } else {
                var is = false;
                $scope.SignalList.forEach(function (item) {
                    if (item.SignalId == $scope.Signals.SignalId) {
                        is = true;
                        $scope.Signals.ChannelNo = oldNo;
                    }
                });
                if (!is) {
                    TemplateService.GetMaxChannelNo($scope.selectEvent.EquipmentTemplateId).then(function (data) {
                        $scope.Signals.ChannelNo = parseInt(data) + 1;
                    });
                }
            }
        };
        $scope.ChangeDeviceToSignal = function(DeviceId){
            var EquipmentTemplateId = "-1";
            //$scope.Signals.SignalId = "";
            if(DeviceId == "-1"){
                EquipmentTemplateId = $scope.selectEvent.EquipmentTemplateId;
            }else{
                var device = _.findWhere($scope.AllDevices,{EquipmentId:DeviceId});
                if(device){
                    EquipmentTemplateId = device.EquipmentTemplateId;
                }
            }
            TemplateService.GetSignalByEquipmentTemplateId(EquipmentTemplateId).then(function (data) {
                TemplateService.GetSignalMeaningsByEquipmentTemplateId(EquipmentTemplateId).then(function (datas) {
                    $scope.SignalMeaningsList = datas;
                    $scope.SignalList2 = parseSignalList(data, datas);
                });
            });
        };
        $scope.ChangeSignalExpression = function (SignalId) {
            var str = "["+$scope.Signals.DeviceId+"," + SignalId + "]";
            $scope.ClickSignalsLi(str);
        };
        $scope.CheckExpression = function (id) {
            var textDom = document.getElementById(id);
            if (textDom.selectionStart || textDom.selectionStart == '0') {
                $scope.startPos = textDom.selectionStart;
                $scope.endPos = textDom.selectionEnd;
                $scope.scrollTop = textDom.scrollTop;
            }
        };
        $scope.ClickSignalsLi = function (symbol) {
            if ($scope.Signals.Expression == undefined)
                $scope.Signals.Expression = "";

            var textDom = document.getElementById("SignalExpression");
            var addStr = symbol;

            if (textDom.selectionStart || textDom.selectionStart == '0') {
                $scope.Signals.Expression = $scope.Signals.Expression.substring(0, $scope.startPos) + addStr +
                    $scope.Signals.Expression.substring($scope.endPos);
                textDom.focus();
                textDom.selectionStart = $scope.startPos + addStr.length;
                textDom.selectionEnd = $scope.startPos + addStr.length;
                textDom.scrollTop = $scope.scrollTop;
            } else {
                $scope.Signals.Expression += addStr;
                textDom.focus();
            }
        };
        $scope.ChangeCategory = function (cate) {
            if (cate == 1) {//模拟量,SignalId最后一位为1
                if ($scope.btnName == $scope.languageJson.Config.Signal.News)/*"新增"*/
                    if ($scope.Signals.SignalId % 10 == 0) {
                        $scope.Signals.SignalId += 1;
                    }
                $scope.CategoryHide = false;
            } else if (cate == 2) {//开关量,SignalId最后一位为0
                if ($scope.btnName == $scope.languageJson.Config.Signal.News)/*"新增"*/
                    if ($scope.Signals.SignalId % 10 == 1) {
                        $scope.Signals.SignalId -= 1;
                    }
                $scope.CategoryHide = true;
            } else
                $scope.CategoryHide = false;
        };
        // 保存
        $scope.saveSignal = function () {
            if ($scope.Signals.SignalName == "" || $scope.Signals.SignalName == undefined) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Title, 3000);/*'信号名称不能为空!'*/
                return;
            }

            if ($scope.SignalList && $scope.Signals.BaseTypeId != "" && $scope.Signals.BaseTypeId != undefined) {
                var is = false;
                $scope.SignalList.forEach(function (item) {
                    if (item.SignalId != $scope.Signals.SignalId && item.BaseTypeId == $scope.Signals.BaseTypeId)
                        is = true;
                });
                if (is) {
                    balert.show('danger', $scope.languageJson.Config.SignalName.Repeated, 3000);/*'基类编号不能重复!'*/
                    return;
                }
            }
            if ($scope.Signals.ChannelNo == "" || $scope.Signals.ChannelNo == undefined) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Channel, 3000);/*'通道号不能为空!'*/
                return;
            }
            if ($scope.Signals.ShowPrecision == "" || $scope.Signals.ShowPrecision == undefined) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Accuracy, 3000);/*'精确率不能为空!'*/
                return;
            }
            if ($scope.Signals.SignalType == 2) {
                if ($scope.Signals.SignalId == -3) {
                    if ($scope.Signals.ChannelNo != -3) {
                        balert.show('danger', $scope.languageJson.Config.SignalName.Status, 3000);/*'通讯状态信号通道号只能为-3!'*/
                        return;
                    }
                } else if ($scope.Signals.ChannelNo != -2) {
                    balert.show('danger', $scope.languageJson.Config.SignalName.Virtual, 3000);/*'虚拟信号通道号只能为-2!'*/
                    return;
                }
            }
            if ($scope.Signals.SignalType != 2 && $scope.Signals.ChannelNo < 0) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Acquisition, 3000);/*'采集信号/常量信号通道号不能为负数!'*/
                return;
            }
            var ret = /^\-?\d*(\.\d+)?$/;
            if (!ret.test($scope.Signals.StoreInterval) || !ret.test($scope.Signals.AbsValueThreshold) ||
                !ret.test($scope.Signals.PercentThreshold) || !ret.test($scope.Signals.ChargeStoreInterVal)) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Storage, 3000);/*'存储周期/百分比阀值/绝对值阀值/统计周期不能输入字符!'*/
                return;
            }
            if ($scope.Signals.StoreInterval < 0 || $scope.Signals.PercentThreshold < 0 ||
                $scope.Signals.ChargeStoreInterVal < 0) {
                balert.show('danger', $scope.languageJson.Config.SignalName.Storagcycle, 3000);/*'存储周期/百分比阀值/统计周期不能小于零!'*/
                return;
            }
            if ($scope.Signals.SignalType != 2 || $scope.Signals.ChannelNo != -2) {
                if ($scope.SignalList) {
                    var is = false;
                    $scope.SignalList.forEach(function (item) {
                        if (item.ChannelNo == $scope.Signals.ChannelNo && item.SignalId != $scope.Signals.SignalId) {
                            is = true;
                        }
                    });
                    if (is) {
                        balert.show('danger', $scope.languageJson.Config.SignalName.Repeateds, 3000);/*'通道号不能重复!'*/
                        TemplateService.GetMaxChannelNo($scope.selectEvent.EquipmentTemplateId).then(function (data) {
                            $scope.Signals.ChannelNo = parseInt(data) + 1;
                        });
                        return;
                    }
                }
            }

            if ($scope.btnName == $scope.languageJson.Config.Config.Modify) {/*"修改"*/
                TemplateService.SaveSignal($scope.Signals).then(function (ret) {
                    GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.SignalName.Successfully, 3000);/*'修改成功!'*/
                    SignalSetterDialog.hide();
                });
            } else {
                TemplateService.AddSignal($scope.Signals).then(function (ret) {
                    GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.SignalName.Added, 3000);/*'新增成功!'*/
                    SignalSetterDialog.hide();
                });
            }
        };
        //#endregion

        //#region 6.2.2.绑定信号基类
        var SignalBasetypeDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/SignalBasetype.html',
            show: false
        });
        $scope.SignalBaseTypeId = function () {
            $scope.Signals.StartNum = 2;
            $scope.Signals.EndNum = "";
            if ($scope.Signals.BaseTypeId == undefined || $scope.Signals.BaseTypeId == "")
                $scope.Signals.IsBaseNameExt = "display:none;";
            TemplateService.GetEquipmentBaseTypeById($scope.Signals.EquipmentTemplateId).then(function (data) {
                $scope.Signals.EquipmentBaseType = data;
                $scope.CheckedEquipmentBaseType();
                SignalBasetypeDialog.$promise.then(SignalBasetypeDialog.show);
            });
            // 重写
            $scope.confirmed = function () {
                if ($scope.Signals.BaseTypeId == "" || $scope.Signals.BaseTypeId == undefined)
                    SignalBasetypeDialog.hide();
                else if ($scope.SignalList) {
                    var is = false;
                    $scope.SignalList.forEach(function (item) {
                        if (item.SignalId != $scope.Signals.SignalId && item.BaseTypeId == $scope.Signals.BaseTypeId)
                            is = true;
                    });
                    if (is) {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.Repeated, 3000);/*'基类编号不能重复!'*/
                    } else
                        SignalBasetypeDialog.hide();
                }
            };
            $scope.clear = function () {
                $scope.Signals.BaseTypeId = "";
                SignalBasetypeDialog.hide();
            };
            $scope.create = function () {
                if ($scope.Signals.BaseTypeId == "" || $scope.Signals.BaseTypeId == undefined) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Title, 3000);/*'请选择基类信号!'*/
                    return;
                }
                if ($scope.Signals.BaseNameExt != "" && $scope.Signals.BaseNameExt != undefined) {
                    if ($scope.Signals.StartNum == "" || $scope.Signals.StartNum == undefined) {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.Starting, 3000);/*'开始序号不能为空!'*/
                        return;
                    }
                    if ($scope.Signals.EndNum != "" && $scope.Signals.EndNum != undefined) {
                        if (parseInt($scope.Signals.EndNum) <= parseInt($scope.Signals.StartNum)) {
                            balert.show('danger', $scope.languageJson.Config.Signalbase.Must, 3000);/*'结束序号必须大于开始序号!'*/
                            return;
                        }
                    }
                    if (isNaN($scope.Signals.StartNum) || ($scope.Signals.EndNum != "" && isNaN($scope.Signals.EndNum))) {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.Numbers, 3000);/*'开始序号和结束序号只能是数值!'*/
                        return;
                    }
                }
                var num = parseInt(parseInt($scope.Signals.BaseTypeId) / 100);
                var isBaseTypeId = false;
                $scope.Template.BaseDic.forEach(function (item) {
                    if (item.BaseTypeId.indexOf(num) == 0) {
                        var no = parseInt(item.BaseTypeId) % 100;
                        if ($scope.Signals.EndNum == undefined || $scope.Signals.EndNum == "") {
                            if (no == $scope.Signals.StartNum) {
                                balert.show('danger', $scope.languageJson.Config.Signalbase.Add, 3000);/*'新增基类信号已存在!'*/
                                isBaseTypeId = true;
                            }
                        } else {
                            if (no >= parseInt($scope.Signals.StartNum) && no <= parseInt($scope.Signals.EndNum)) {
                                balert.show('danger', $scope.languageJson.Config.Signalbase.Serial, 3000);/*'新增序号区间有已存在的基类信号!'*/
                                isBaseTypeId = true;
                            }
                        }
                    }
                });
                if (isBaseTypeId) return;
                TemplateService.InsertBaseType("TBL_SignalBaseDic", $scope.Signals.EquipmentBaseType, $scope.Signals.BaseTypeId, $scope.Signals.StartNum, $scope.Signals.EndNum).then(function (data) {
                    if (data) {
                        balert.show('success', $scope.languageJson.Config.Signalbase.Successfully, 3000);/*'新增成功!'*/
                        $scope.CheckedEquipmentBaseType();
                    } else {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.New, 3000);/*'新增失败!'*/
                    }
                });
            };
        };
        $scope.CheckedEquipmentBaseType = function () {
            if ($scope.Signals.EquipmentBaseType) {
                TemplateService.GetBaseDicByBaseType("SignalBaseDic", $scope.Signals.EquipmentBaseType).then(function (data) {
                    $scope.Template.BaseDic = data;
                    if ($scope.Signals.BaseTypeId)
                        $scope.CheckedBaseTypeId($scope.Signals.BaseTypeId);
                });
            }
        };
        $scope.CheckedBaseTypeId = function (baseTypeId) {
            $scope.Signals.IsBaseNameExt = "display:none;";
            $scope.Signals.IsSystem = "display:none;";
            $scope.Template.BaseDic.forEach(function (item) {
                if (item.BaseTypeId == baseTypeId) {
                    $scope.Signals.BaseNameExt = item.BaseNameExt;
                    if (item.IsSystem == "false")
                        $scope.Signals.IsSystem = "display:block;";
                    if (item.BaseNameExt != undefined && item.BaseNameExt != "")
                        $scope.Signals.IsBaseNameExt = "display:block;";
                }
            });
        };
        var ConfirmBoxDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/confirmBox.html',
            show: false
        });
        $scope.removeSignalBaseDic = function () {
            $scope.ConfirmBox = {
                type: "DeleteSignalBaseDic",
                equipmentTemplateId: undefined,
                id: $scope.Signals.BaseTypeId
            };
            $scope.message = $scope.languageJson.Config.Signalbase.Class;/*确定删除此基类信号吗?*/
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion
        
        //#region 6.2.3.删除信号
        $scope.deleteSignalClick = function (data) {
            $scope.ConfirmBox = {
                type: "DeleteSignal",
                equipmentTemplateId: data.EquipmentTemplateId,
                id: data.SignalId
            };
            $scope.message = $scope.languageJson.Config.SignalName.Confirm + data.SignalName + $scope.languageJson.Config.SignalName.Data;
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion

        //#region 6.2.4.批量修改存储
        var modifyStorageCycleDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/modifyStorageCycle.html',
            show: false
        });
        $scope.batchSignalConfigClk = function(selectedArr){
            $scope.signalResult = {
                TemplateId:0,
                SignalIdArray:[],						//信号id数组类型存储全部选中id
                StoreInterval:"",						//存储周期
                AbsValueThreshold:"",					//绝对值阀值
                PercentThreshold:"",						//百分比阀值
                StaticsPeriod:"",						//统计周期(时)
            };
            if (selectedArr == undefined){
                return;
            }else{
                selectedArr.forEach(function(item){
                    if(item.checked){
                        $scope.signalResult.SignalIdArray.push(item.SignalId)
                        $scope.signalResult.TemplateId = item.EquipmentTemplateId;
                    }
                })
            }
            if ($scope.signalResult.SignalIdArray.length == 0){
                balert.show('danger',$scope.languageJson.Configuration.SignalControl.ErrorPrompt, 3000);/*'请选择信号!'*/
            }else{
                modifyStorageCycleDlg.$promise.then(modifyStorageCycleDlg.show);
            }
        }
        $scope.selectSignalListAll = function(selectedArr){
            if(selectedArr.checkedAll) {
                selectedArr.forEach(function (item) {
                    item.checked = true;
                })
            }else {
                selectedArr.forEach(function (item) {
                    item.checked = false;
                })
            }
        }
        $scope.selectSignal = function(selectedArr,el){
            let allCount = 0
            let dom = document.getElementById(el)
            if(!dom) return
            selectedArr.forEach(function(item){
                if(item.checked){
                    allCount++
                }
            })
            if(allCount == selectedArr.length){
                dom.indeterminate = false
                selectedArr.checkedAll = true
            }else if(allCount >= 1){
                dom.indeterminate = true
            }else{
                dom.indeterminate = false
                selectedArr.checkedAll= false
            }
        }
        $scope.modifySignalCycle = function(){
            TemplateService.modifySignalCycle($scope.signalResult).then(function(date){
                if (date=="OK"){
                    balert.show('success', $scope.languageJson.Config.Templatenames.Successfully, 3000);/*'修改成功!'*/
                    GetSignalByEquipmentTemplateId($scope.signalResult.TemplateId);
                    modifyStorageCycleDlg.hide();
                }else{
                    balert.show('danger', $scope.languageJson.Config.Templatenames.Fail, 3000);/*'修改失败!'*/
                }
            })
        }
        //#endregion
        //#endregion

        //#region 6.3.信号/控制:信号/控制含义
        var BindingMeaningsDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/bindingMeanings.html',
            show: false
        });
        $scope.BindingMeanings = function (type, data) {
            if (type == 'Signal') {
                $scope.title = $scope.languageJson.Config.ControlSignal.Title;/*"信号"*/
                $scope.DataMeanings = getSignalMeanings(data);
            } else {
                $scope.title = $scope.languageJson.Config.ControlSignal.Control;/*"控制"*/
                $scope.DataMeanings = getControlMeanings(data);
            }
            BindingMeaningsDialog.$promise.then(BindingMeaningsDialog.show);
        };
        function getSignalMeanings(data) {
            var obj = [];
            if (data.DataMeanings) {
                data.DataMeanings.forEach(function (item) {
                    var cfg = {};
                    if (item.StateValue == undefined)
                        cfg.Value = item.Value;
                    else
                        cfg.Value = item.StateValue;
                    cfg.Meanings = item.Meanings;
                    obj.push(cfg);
                });
            }
            obj.EquipmentTemplateId = data.EquipmentTemplateId;
            if (obj.EquipmentTemplateId == undefined) obj.EquipmentTemplateId = $scope.selectEvent.EquipmentTemplateId;
            obj.Id = data.SignalId;
            return obj;
        };
        function getControlMeanings(data) {
            var obj = [];
            if (data.DataMeanings) {
                data.DataMeanings.forEach(function (item) {
                    var cfg = {};
                    if (item.ParameterValue == undefined) cfg.Value = item.Value;
                    else cfg.Value = item.ParameterValue;
                    cfg.Meanings = item.Meanings;
                    obj.push(cfg);
                });
            }
            obj.EquipmentTemplateId = data.EquipmentTemplateId;
            if (obj.EquipmentTemplateId == undefined) obj.EquipmentTemplateId = $scope.selectEvent.EquipmentTemplateId;
            obj.Id = data.ControlId;
            return obj;
        };
        // 新增含义
        $scope.addMeaningsCol = function () {
            var value = -1;
            $scope.DataMeanings.forEach(function (item) {
                if (item.Value > value) {
                    value = item.Value;
                }
            });
            value++;
            var cfg = {
                Value: value,
                Meanings: $scope.languageJson.Config.Meaning
            };/*'含义'*/
            $scope.DataMeanings.push(cfg);
        };
        // 保存含义
        $scope.saveMeanings = function () {
            if ($scope.title == $scope.languageJson.Config.ControlSignal.Title) {/*"信号"*/
                TemplateService.SaveSignalMeanings($scope.DataMeanings).then(function (data) {
                    balert.show('success', $scope.languageJson.Config.ControlSignal.Successful, 3000);/*'处理成功!'*/
                    parseSignalMeanings($scope.DataMeanings);
                });
            } else {
                TemplateService.SaveControlMeanings($scope.DataMeanings).then(function (data) {
                    balert.show('success', $scope.languageJson.Config.ControlSignal.Successful, 3000);/*'处理成功!'*/
                    parseControlMeanings($scope.DataMeanings);
                });
            }
            BindingMeaningsDialog.hide();
        };
        function parseSignalMeanings(data) {
            $scope.Signals.Meanings = undefined;
            $scope.Signals.DataMeanings = [];
            data.forEach(function (sm) {
                if ($scope.Signals.Meanings == undefined) {
                    $scope.Signals.Meanings = sm.Meanings;
                } else {
                    $scope.Signals.Meanings += "/" + sm.Meanings;
                }
                $scope.Signals.DataMeanings.push(sm);
            });
            if ($scope.Signals.DataMeanings.EquipmentTemplateId == undefined)
                $scope.Signals.DataMeanings.EquipmentTemplateId = $scope.selectEvent.EquipmentTemplateId;
            $scope.Signals.DataMeanings.Id = $scope.Signals.SignalId;
        };
        function parseControlMeanings(data) {
            $scope.Controls.Meanings = undefined;
            $scope.Controls.DataMeanings = [];
            data.forEach(function (sm) {
                if ($scope.Controls.Meanings == undefined) {
                    $scope.Controls.Meanings = sm.Meanings;
                } else {
                    $scope.Controls.Meanings += "/" + sm.Meanings;
                }
                $scope.Controls.DataMeanings.push(sm);
            });
            if ($scope.Controls.DataMeanings.EquipmentTemplateId == undefined)
                $scope.Controls.DataMeanings.EquipmentTemplateId = $scope.selectEvent.EquipmentTemplateId;
            $scope.Controls.DataMeanings.Id = $scope.Controls.ControlId;
        };
        // 删除含义
        $scope.deleteMeaningsClick = function ($index) {
            $scope.DataMeanings.splice($index, 1);
        };
        //#endregion

        //#region 6.4.事件管理
        //#region 6.4.1.新增/修改事件
        var EventSetterDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/EventSetter.html',
            show: false
        });
        // 新增信号弹出框
        $scope.AddEvent = function () {
            $scope.btnName = $scope.languageJson.Config.ControlSignal.New/*"新增"*/;
            TemplateService.GetNextSignalId($scope.selectEvent.EquipmentTemplateId, 'Event').then(function (data) {
                $scope.Events = {
                    EquipmentTemplateId: $scope.selectEvent.EquipmentTemplateId,
                    EventId: parseInt(data),
                    EventName: $scope.languageJson.Config.Details.NewName,
                    EventCategory: '2',
                    StartType: '1',
                    EndType: '3',
                    Enable: true,
                    Visible: true,
                    IsBaseNameExt: "display:none;"
                };/*'新事件'*/
                EventSetterDialog.$promise.then(EventSetterDialog.show);
            });
            if ($scope.SignalList == undefined) {
                TemplateService.GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (data) {
                    TemplateService.GetSignalMeaningsByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId).then(function (datas) {
                        $scope.SignalMeaningsList = datas;
                        $scope.SignalList = parseSignalList(data, datas);
                    });
                });
            }
        };
        // 修改信号弹出框
        $scope.updateEventClick = function (data) {
            $scope.btnName = $scope.languageJson.Config.ControlSignal.Modify;/*"修改"*/
            $scope.Events = data;
            if (data.Enable == 'true') $scope.Events.Enable = true;
            if (data.Visible == 'true') $scope.Events.Visible = true;
            EventSetterDialog.$promise.then(EventSetterDialog.show);
        };
        $scope.ChangeRelateEventSignal = function (signalId) {
            if ($scope.Events.StartExpression == undefined)
                $scope.Events.StartExpression = '';
            $scope.Events.StartExpression += "[-1," + signalId + "]";
            $scope.SignalList.forEach(function (item) {
                if (item.SignalId == signalId)
                    $scope.Events.EventName = item.SignalName + $scope.languageJson.Config.Details.Suffix;/*"事件"*/
            });
        };
        $scope.ClickEventsLi = function (symbol) {
            if ($scope.Events.StartExpression == undefined)
                $scope.Events.StartExpression = "";

            var textDom = document.getElementById("EventExpression");
            var addStr = symbol;

            if (textDom.selectionStart || textDom.selectionStart == '0') {
                $scope.Events.StartExpression = $scope.Events.StartExpression.substring(0, $scope.startPos) + addStr +
                    $scope.Events.StartExpression.substring($scope.endPos);
                textDom.focus();
                textDom.selectionStart = $scope.startPos + addStr.length;
                textDom.selectionEnd = $scope.startPos + addStr.length;
                textDom.scrollTop = $scope.scrollTop;
            } else {
                $scope.Events.StartExpression += addStr;
                textDom.focus();
            }
        };
        $scope.saveEvent = function () {
            if ($scope.Events.EventName == undefined || $scope.Events.EventName == '') {
                balert.show('danger', $scope.languageJson.Config.ControlSignal.Empty, 3000);/*'事件名称不能为空!'*/
                return;
            }
            if ($scope.btnName == $scope.languageJson.Config.ControlSignal.New) {/*'新增'*/
                TemplateService.AddEvent($scope.Events).then(function (data) {
                    GetEventByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.ControlSignal.Added, 3000);/*'新增成功!'*/
                });
            } else {
                TemplateService.SaveEvent($scope.Events).then(function (data) {
                    GetEventByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.ControlSignal.Modified, 3000);/*'修改成功!'*/
                });
            }
            EventSetterDialog.hide();
        };

        //#region 绑定事件&事件基类
        var BindingConditionDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/bindingCondition.html',
            show: false
        });
        $scope.BindingCondition = function (data) {
            $scope.EventCondition = data.EventCondition;
            if ($scope.EventCondition == undefined)
                $scope.EventCondition = [];
            $scope.EventCondition.EquipmentTemplateId = data.EquipmentTemplateId;
            $scope.EventCondition.EventId = data.EventId;
            BindingConditionDialog.$promise.then(BindingConditionDialog.show);
        };
        $scope.addConditionCol = function () {
            var number = -1;
            if ($scope.EventCondition) {
                $scope.EventCondition.forEach(function (item) {
                    if (item.EventConditionId > number) number = item.EventConditionId;
                });
            }
            var cfg = {
                EventConditionId: ++number,
                EventSeverity: '1',
                StartOperation: '=',
                StartCompareValue: '0',
                StartDelay: '0',
                Meanings: $scope.Events.EventName
            };
            if ($scope.Events.EventCondition && $scope.Events.EventCondition.length > 0)
                cfg.BaseTypeId = $scope.Events.EventCondition[0].BaseTypeId;
            $scope.EventCondition.push(cfg);
        };
        $scope.deleteConditionClick = function ($index) {
            $scope.EventCondition.splice($index, 1);
        };
        $scope.saveCondition = function () {
            $scope.Events.Meanings = undefined;
            TemplateService.SaveCondition($scope.EventCondition).then(function (data) {
                $scope.EventCondition.forEach(function (ec) {
                    if ($scope.Events.Meanings == undefined) {
                        $scope.Events.Meanings = ec.EventConditionId;
                    } else {
                        $scope.Events.Meanings += "/" + ec.EventConditionId;
                    }
                });
                $scope.Events.EventCondition = $scope.EventCondition;
                balert.show('success', $scope.languageJson.Config.ControlSignal.Successful, 3000);/*'处理成功!'*/
                BindingConditionDialog.hide();
            });
        };
        // 基类事件基类
        var EventBasetypeDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/EventBasetype.html',
            show: false
        });
        $scope.EventBaseTypeId = function (data) {
            $scope.Events.EventConditionId = data.EventConditionId;
            $scope.Events.BaseTypeId = data.BaseTypeId;
            $scope.Events.StartNum = 2;
            $scope.Events.EndNum = "";
            TemplateService.GetEquipmentBaseTypeById($scope.Events.EquipmentTemplateId).then(function (data) {
                $scope.Events.EquipmentBaseType = data;
                $scope.CheckedEventEquipmentBaseType();
                EventBasetypeDialog.$promise.then(EventBasetypeDialog.show);
            });
        };
        $scope.createEvent = function () {
            if ($scope.Events.BaseTypeId == "" || $scope.Events.BaseTypeId == undefined) {
                balert.show('danger', $scope.languageJson.Config.Signalbase.Title, 3000);/*'请选择基类事件!'*/
                return;
            }
            if ($scope.Events.BaseNameExt != "" && $scope.Events.BaseNameExt != undefined) {
                if ($scope.Events.StartNum == "" || $scope.Events.StartNum == undefined) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Starting, 3000);/*'开始序号不能为空!'*/
                    return;
                }
                if ($scope.Events.EndNum != "" && $scope.Events.EndNum != undefined) {
                    if ($scope.Events.EndNum <= $scope.Events.StartNum) {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.Must, 3000);/*'结束序号必须大于开始序号!*/
                        return;
                    }
                }
                if (isNaN($scope.Events.StartNum) || ($scope.Events.EndNum != "" && isNaN($scope.Events.EndNum))) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Numbers, 3000);/*开始序号和结束序号只能是数值!*/
                    return;
                }
            }
            var num = parseInt(parseInt($scope.Events.BaseTypeId) / 100);
            var isBaseTypeId = false;
            $scope.Template.EventBaseDic.forEach(function (item) {
                if (item.BaseTypeId.indexOf(num) == 0) {
                    var no = parseInt(item.BaseTypeId) % 100;
                    if ($scope.Events.EndNum == undefined || $scope.Events.EndNum == "") {
                        if (no == $scope.Events.StartNum) {
                            balert.show('danger', $scope.languageJson.Config.Signalbase.Add, 3000);/*新增基类信号已存在!*/
                            isBaseTypeId = true;
                        }
                    } else {
                        if (no >= parseInt($scope.Events.StartNum) && no <= parseInt($scope.Events.EndNum)) {
                            balert.show('danger', $scope.languageJson.Config.Signalbase.Serial, 3000);/*新增序号区间有已存在的基类信号!*/
                            isBaseTypeId = true;
                        }
                    }
                }
            });
            if (isBaseTypeId) return;
            TemplateService.InsertBaseType("TBL_EventBaseDic", $scope.Events.EquipmentBaseType, $scope.Events.BaseTypeId, $scope.Events.StartNum, $scope.Events.EndNum).then(function (data) {
                if (data) {
                    balert.show('success', $scope.languageJson.Config.Signalbase.Successfully, 3000);/*新增成功!*/
                    $scope.CheckedEventEquipmentBaseType();
                } else {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.New, 3000);/*新增失败!*/
                }
            });
        };
        $scope.confirmedEvents = function () {
            $scope.EventCondition.forEach(function (item) {
                if ($scope.Events.EventConditionId == item.EventConditionId)
                    item.BaseTypeId = $scope.Events.BaseTypeId;
            });
            EventBasetypeDialog.hide();
        };
        $scope.clearEvents = function () {
            $scope.Events.BaseTypeId = "";
            EventBasetypeDialog.hide();
        };
        $scope.removeEventBaseDic = function () {
            $scope.ConfirmBox = {
                type: "DeleteEventBaseDic",
                equipmentTemplateId: undefined,
                id: $scope.Events.BaseTypeId
            };
            $scope.message = $scope.languageJson.Config.Signalbase.Class;/*确定删除此基类信号吗?*/
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion
        //#endregion

        //#region 6.4.2.删除事件
        $scope.deleteEventClick = function (data) {
            $scope.ConfirmBox = {
                type: "DeleteEvent",
                equipmentTemplateId: data.EquipmentTemplateId,
                id: data.EventId
            };
            $scope.message = $scope.languageJson.Config.SignalName.Confirm + data.EventName + $scope.languageJson.Config.SignalName.Data;//"确定删除" / 事件的数据
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion
        
        //#region 6.4.3.屏蔽事件
        var shieldEventDlg = $modal({
            scope: $scope,
            templateUrl: 'partials/eventShieldStatus.html',
            show: false
        });
        $scope.ShieldEvent = function () {
            $scope.ShieldTemplate = getEquipmentTemplateById($scope.selectEvent.EquipmentTemplateId);

            shieldEventDlg.$promise.then(shieldEventDlg.show);
        };
        function getEquipmentTemplateById(id) {
            var obj = {};
            if ($scope.equipmentTemplates) {
                $scope.equipmentTemplates.forEach(function (item) {
                    if (item.EquipmentTemplateId == id)
                        obj = item;
                });
            }
            if ($scope.EventList) {
                obj.Shield = true;
                $scope.EventList.forEach(function (item) {
                    if (item.Shield == false)
                        obj.Shield = false;
                });
            }
            return obj;
        }
        $scope.checkShieldAll = function (equipmentTemplateId, shieldName, isShield) {
            if (shieldName !== undefined) {
                eval(shieldName + " = !" + shieldName);
            }
            isShield = !isShield;
            TemplateService.ShieldEnableEvent(equipmentTemplateId, "", isShield).then(function (data) {
                console.log("ShieldEnableEvent:" + data);
                if ($scope.EventList) {
                    $scope.EventList.forEach(function (item) {
                        item.Shield = isShield;
                    });
                }
            });
        };
        $scope.checkShieldEvent = function (row, isShield) {
            if (isShield == undefined) {
                row.Shield = !row.Shield;
                isShield = row.Shield;
            } else
                isShield = !isShield;
            TemplateService.ShieldEnableEvent($scope.ShieldTemplate.EquipmentTemplateId, row.EventId, isShield).then(function (data) {
                console.log("ShieldEnableEvent:" + data);
            });
        };
        $scope.ShieldEventSave = function () {
            balert.show('success', $scope.languageJson.Config.ShieldEventBox.Prompt.succeed, 3000);/*保存成功,请点击'配置生效'按钮!*/
            shieldEventDlg.hide();
        };
        //#endregion
        //#endregion

        //#region 6.5.控制管理
        //#region 6.5.1.新增/修改控制
        var ControlSetterDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/ControlSetter.html',
            show: false
        });
        // 新增控制弹出框
        $scope.AddControl = function () {
            $scope.btnName = $scope.languageJson.Config.Setting.New/*"新增"*/;
            TemplateService.GetNextSignalId($scope.selectEvent.EquipmentTemplateId, 'Control').then(function (data) {
                $scope.Controls = {
                    EquipmentTemplateId: $scope.selectEvent.EquipmentTemplateId,
                    ControlId: parseInt(data),
                    ControlName: $scope.languageJson.Config.Con.NewName,
                    ControlCategory: '1',
                    ControlSeverity: '1',
                    ControlType: '1',
                    DataType: '0',
                    CmdToken: '',
                    CommandType: '1',
                    MaxValue: '0.0',
                    MinValue: '0.0',
                    Meanings: '',
                    Enable: true,
                    Visible: true,
                    BaseTypeId: ''
                };/*'新控制'*/
                ControlSetterDialog.$promise.then(ControlSetterDialog.show);
            });
        };
        // 修改控制弹出框
        $scope.updateControlClick = function (data) {
            $scope.btnName = $scope.languageJson.Config.ControlSignal.Modify;/*"修改"*/
            $scope.Controls = data;
            if (data.Enable == 'true') $scope.Controls.Enable = true;
            if (data.Visible == 'true') $scope.Controls.Visible = true;
            ControlSetterDialog.$promise.then(ControlSetterDialog.show);
        };
        $scope.ChangeRelateControlSignal = function (signalId) {
            $scope.SignalList.forEach(function (item) {
                if (item.SignalId == signalId)
                    $scope.Controls.ControlName = item.SignalName + $scope.languageJson.Config.ControlSignal.Suffix;/*"控制"*/
            });
        };
        $scope.saveControl = function () {
            var controlSignal = $scope.languageJson.Config.ControlSignal;
            if ($scope.Controls.ControlName == "" || $scope.Controls.ControlName == undefined) {
                balert.show('danger', controlSignal.Controls, 3000);/*'控制名称不能为空!'*/
                return;
            }
            if ($scope.btnName == controlSignal.Modify) {/*"修改"*/
                TemplateService.SaveControl($scope.Controls).then(function (ret) {
                    GetControlByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', controlSignal.Modified, 3000);/*'修改成功!'*/
                    ControlSetterDialog.hide();
                });
            } else {
                TemplateService.AddControl($scope.Controls).then(function (ret) {
                    GetControlByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', controlSignal.Added, 3000);/*'新增成功!'*/
                    ControlSetterDialog.hide();
                });
            }
        };
        // 控制基类
        var ControlBasetypeDialog = $modal({
            scope: $scope,
            templateUrl: 'partials/ControlBasetype.html',
            show: false
        });
        $scope.ControlBaseTypeId = function (data) {
            $scope.Controls.StartNum = 2;
            $scope.Controls.EndNum = "";
            TemplateService.GetEquipmentBaseTypeById($scope.Controls.EquipmentTemplateId).then(function (data) {
                $scope.Controls.EquipmentBaseType = data;
                if ($scope.Controls.BaseTypeId == "" || $scope.Controls.BaseTypeId == undefined)
                    $scope.Controls.IsBaseNameExt = "display:none;";
                $scope.CheckedControlEquipmentBaseType();
                ControlBasetypeDialog.$promise.then(ControlBasetypeDialog.show);
            });
        };
        $scope.createControl = function () {
            if ($scope.Controls.BaseTypeId == "" || $scope.Controls.BaseTypeId == undefined) {
                balert.show('danger', $scope.languageJson.Config.Signalbase.Base, 3000);/*'请选择基类事件!'*/
                return;
            }
            if ($scope.Controls.BaseNameExt != "" && $scope.Controls.BaseNameExt != undefined) {
                if ($scope.Controls.StartNum == "" || $scope.Controls.StartNum == undefined) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Starting, 3000);/*'开始序号不能为空!'*/
                    return;
                }
                if ($scope.Controls.EndNum != "" && $scope.Controls.EndNum != undefined) {
                    if ($scope.Controls.EndNum <= $scope.Controls.StartNum) {
                        balert.show('danger', $scope.languageJson.Config.Signalbase.Must, 3000);/*'结束序号必须大于开始序号!'*/
                        return;
                    }
                }
                if (isNaN($scope.Controls.StartNum) || ($scope.Controls.EndNum != "" && isNaN($scope.Controls.EndNum))) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Numbers, 3000);/*'开始序号和结束序号只能是数值!'*/
                    return;
                }
            }
            var num = parseInt(parseInt($scope.Controls.BaseTypeId) / 100);
            var isBaseTypeId = false;
            $scope.Template.ControlBaseDic.forEach(function (item) {
                if (item.BaseTypeId.indexOf(num) == 0) {
                    var no = parseInt(item.BaseTypeId) % 100;
                    if ($scope.Controls.EndNum == undefined || $scope.Controls.EndNum == "") {
                        if (no == $scope.Events.StartNum) {
                            balert.show('danger', $scope.languageJson.Config.Signalbase.Add, 3000);/*'新增基类信号已存在!'*/
                            isBaseTypeId = true;
                        }
                    } else {
                        if (no >= parseInt($scope.Controls.StartNum) && no <= parseInt($scope.Controls.EndNum)) {
                            balert.show('danger', $scope.languageJson.Config.Signalbase.Serial, 3000);/*'新增序号区间有已存在的基类信号!'*/
                            isBaseTypeId = true;
                        }
                    }
                }
            });
            if (isBaseTypeId) return;
            TemplateService.InsertBaseType("TBL_CommandBaseDic", $scope.Controls.EquipmentBaseType, $scope.Controls.BaseTypeId, $scope.Controls.StartNum, $scope.Controls.EndNum).then(function (data) {
                if (data) {
                    balert.show('success', $scope.languageJson.Config.Signalbase.Successfully, 3000);/*'新增成功!'*/
                    $scope.CheckedControlEquipmentBaseType();
                } else {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.New, 3000);/*'新增失败!'*/
                }
            });
        };
        $scope.confirmedControls = function () {
            if ($scope.ControlList) {
                var is = false;
                $scope.ControlList.forEach(function (item) {
                    if (item.ControlId != $scope.Controls.ControlId && item.BaseTypeId == $scope.Controls.BaseTypeId)
                        is = true;
                });
                if (is) {
                    balert.show('danger', $scope.languageJson.Config.Signalbase.Repeated, 3000);/*'基类编号不能重复!'*/
                } else
                    ControlBasetypeDialog.hide();
            }
        };
        $scope.clearControls = function () {
            $scope.Controls.BaseTypeId = "";
            ControlBasetypeDialog.hide();
        };
        $scope.removeControlBaseDic = function () {
            $scope.ConfirmBox = {
                type: "DeleteCommandBaseDic",
                equipmentTemplateId: undefined,
                id: $scope.Controls.BaseTypeId
            };
            $scope.message = $scope.languageJson.Config.Signalbase.Class;/*"确定删除此基类信号吗?"*/
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion

        //#region 6.5.2.删除控制
        $scope.deleteControlClick = function (data) {
            $scope.ConfirmBox = {
                type: "DeleteControl",
                equipmentTemplateId: data.EquipmentTemplateId,
                id: data.ControlId
            };
            $scope.message = $scope.languageJson.Config.SignalName.Confirm + data.ControlName + $scope.languageJson.Config.SignalName.Data;//"确定删除“" / 控制的数据
            ConfirmBoxDialog.$promise.then(ConfirmBoxDialog.show);
        };
        //#endregion
        //#endregion

        //#region 6.6.排序
        $scope.sortingOrder = undefined;
        $scope.reverse = false;
        $scope.SortBy = function (newSortingOrder) {
            if ($scope.sortingOrder == newSortingOrder) {
                $scope.reverse = !$scope.reverse;
            }
            $scope.sortingOrder = newSortingOrder;
            // 遍历
            $('th i').each(function () {
                // 删除其他箭头样式
                $(this).removeClass("fa-chevron-down");
                $(this).removeClass("fa-chevron-up");
            });
            if ($scope.reverse) {
                $('th.' + newSortingOrder + ' i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
            } else {
                $('th.' + newSortingOrder + ' i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
            }

        };
        $scope.SortByChannelNo = function (newSortingOrder) {
            $scope.SignalList.forEach(function (item) {
                if (parseInt(item.ChannelNo) < 10 && parseInt(item.ChannelNo) > 0)
                    item.No = "1000" + item.ChannelNo;
                else if (parseInt(item.ChannelNo) < 100 && parseInt(item.ChannelNo) > 0)
                    item.No = "100" + item.ChannelNo;
                else if (parseInt(item.ChannelNo) < 1000 && parseInt(item.ChannelNo) > 0)
                    item.No = "10" + item.ChannelNo;
                else if (parseInt(item.ChannelNo) < 10000 && parseInt(item.ChannelNo) > 0)
                    item.No = "1" + item.ChannelNo;
                else
                    item.No = item.ChannelNo;
            });
            $scope.reverse = !$scope.reverse;
            $scope.sortingOrder = "No";
            // 遍历
            $('th i').each(function () {
                // 删除其他箭头样式
                $(this).removeClass("fa-chevron-down");
                $(this).removeClass("fa-chevron-up");
            });
            if ($scope.reverse) {
                $('th.' + newSortingOrder + ' i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
            } else {
                $('th.' + newSortingOrder + ' i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
            }
        };
        //#endregion
        
        //#region 公共代码
        $scope.ok = function () {
            if ($scope.ConfirmBox == undefined) return;
            if ($scope.ConfirmBox.type == "BatchBaseTypeId") {
                TemplateService.BatchBaseTypeId($scope.selectEvent.EquipmentTemplateId).then(function (ret) {
                    GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.Templatenames.Batch, 3000);/*'批处理完成!'*/
                });
            } else if ($scope.ConfirmBox.type == "DeleteSignal") {
                TemplateService.DeleteSignal($scope.ConfirmBox.equipmentTemplateId, $scope.ConfirmBox.id).then(function (ret) {
                    GetSignalByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                });
            } else if ($scope.ConfirmBox.type == "DeleteEvent") {
                TemplateService.DeleteEvent($scope.ConfirmBox.equipmentTemplateId, $scope.ConfirmBox.id).then(function (ret) {
                    GetEventByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                });
            } else if ($scope.ConfirmBox.type == "DeleteControl") {
                TemplateService.DeleteControl($scope.ConfirmBox.equipmentTemplateId, $scope.ConfirmBox.id).then(function (ret) {
                    GetControlByEquipmentTemplateId($scope.selectEvent.EquipmentTemplateId);
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                });
            } else if ($scope.ConfirmBox.type == "DeleteSignalBaseDic") {
                TemplateService.DeleteBaseDic("SignalBaseDic", $scope.ConfirmBox.id).then(function (data) {
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                    $scope.CheckedEquipmentBaseType();
                });
            } else if ($scope.ConfirmBox.type == "DeleteEventBaseDic") {
                TemplateService.DeleteBaseDic("EventBaseDic", $scope.ConfirmBox.id).then(function (data) {
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                    $scope.CheckedEventEquipmentBaseType();
                });
            } else if ($scope.ConfirmBox.type == "DeleteCommandBaseDic") {
                TemplateService.DeleteBaseDic("CommandBaseDic", $scope.ConfirmBox.id).then(function (data) {
                    balert.show('success', $scope.languageJson.Config.Templatenames.Deleted, 3000);/*'删除成功!'*/
                    $scope.CheckedControlEquipmentBaseType();
                });
            }
            ConfirmBoxDialog.hide();
        };
        $scope.CheckedEventEquipmentBaseType = function () {
            if ($scope.Events.EquipmentBaseType) {
                TemplateService.GetBaseDicByBaseType("EventBaseDic", $scope.Events.EquipmentBaseType).then(function (data) {
                    $scope.Template.EventBaseDic = data;
                    $scope.CheckedEventBaseTypeId($scope.Events.BaseTypeId);
                });
            }
        };
        $scope.CheckedEventBaseTypeId = function (baseTypeId) {
            $scope.Events.IsBaseNameExt = "display:none;";
            $scope.Events.IsSystem = "display:none;";
            $scope.Template.EventBaseDic.forEach(function (item) {
                if (item.BaseTypeId == baseTypeId) {
                    $scope.Events.BaseNameExt = item.BaseNameExt;
                    if (item.IsSystem == "false")
                        $scope.Events.IsSystem = "display:block;";
                    if (item.BaseNameExt != undefined && item.BaseNameExt != "")
                        $scope.Events.IsBaseNameExt = "display:block;";
                }
            });
        };
        $scope.CheckedControlEquipmentBaseType = function () {
            if ($scope.Controls.EquipmentBaseType) {
                TemplateService.GetBaseDicByBaseType("CommandBaseDic", $scope.Controls.EquipmentBaseType).then(function (data) {
                    $scope.Template.ControlBaseDic = data;
                    if ($scope.Controls.BaseTypeId)
                        $scope.CheckedControlBaseTypeId($scope.Controls.BaseTypeId);
                });
            }
        };
        $scope.CheckedControlBaseTypeId = function (baseTypeId) {
            $scope.Controls.IsBaseNameExt = "display:none;";
            $scope.Controls.IsSystem = "display:none;";
            $scope.Template.ControlBaseDic.forEach(function (item) {
                if (item.BaseTypeId == baseTypeId) {
                    $scope.Controls.BaseNameExt = item.BaseNameExt;
                    if (item.IsSystem == "false")
                        $scope.Controls.IsSystem = "display:block;";
                    if (item.BaseNameExt != undefined && item.BaseNameExt != "")
                        $scope.Controls.IsBaseNameExt = "display:block;";
                }
            });
        };
        //#endregion
        //#endregion
    }
]);