<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ElevatorMgt.aspx.cs" Inherits="GigaTech.CMS.Web.Apps.DeviceSystem.ElevatorMgt" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
           <script language=javascript>
               var unitList = "<%=unitList %>";
               var totalLevel = unitList.split("@").length;
               var totalLength=<%=totalLength%> ;

           var tree2;
           var tree2_store;

           Ext.define('Ext.ux.CheckColumnPatch', {
               override: 'Ext.ux.CheckColumn',

               /**
                * @cfg {Boolean} [columnHeaderCheckbox=false]
                * True to enable check/uncheck all rows
                */
               columnHeaderCheckbox: false,

               constructor: function (config) {
                   var me = this;
                   me.callParent(arguments);

                   me.addEvents('beforecheckallchange', 'checkallchange');

                   if (me.columnHeaderCheckbox) {
                       me.on('headerclick', function () {
                           this.updateAllRecords();
                       }, me);

                       me.on('render', function (comp) {
                           var grid = comp.up('grid');
                           this.mon(grid, 'reconfigure', function () {
                               if (this.isVisible()) {
                                   this.bindStore();
                               }
                           }, this);

                           if (this.isVisible()) {
                               this.bindStore();
                           }

                           this.on('show', function () {
                               this.bindStore();
                           });
                           this.on('hide', function () {
                               this.unbindStore();
                           });
                       }, me);
                   }
               },

               onStoreDateUpdate: function () {
                   var allChecked,
                       image;

                   if (!this.updatingAll) {
                       allChecked = this.getStoreIsAllChecked();
                       if (allChecked !== this.allChecked) {
                           this.allChecked = allChecked;
                           image = this.getHeaderCheckboxImage(allChecked);
                           this.setText(image);
                       }
                   }
               },

               getStoreIsAllChecked: function () {
                   var me = this,
                       allChecked = true;
                   me.store.each(function (record) {
                       if (!record.get(this.dataIndex)) {
                           allChecked = false;
                           return false;
                       }
                   }, me);
                   return allChecked;
               },

               bindStore: function () {
                   var me = this,
                       grid = me.up('grid'),
                       store = grid.getStore();

                   me.store = store;

                   me.mon(store, 'datachanged', function () {
                       this.onStoreDateUpdate();
                   }, me);
                   me.mon(store, 'update', function () {
                       this.onStoreDateUpdate();
                   }, me);

                   me.onStoreDateUpdate();
               },

               unbindStore: function () {
                   var me = this,
                       store = me.store;

                   me.mun(store, 'datachanged');
                   me.mun(store, 'update');
               },

               updateAllRecords: function () {
                   var me = this,
                       allChecked = !me.allChecked;

                   if (me.fireEvent('beforecheckallchange', me, allChecked) !== false) {
                       this.updatingAll = true;
                       me.store.suspendEvents();
                       me.store.each(function (record) {
                           record.set(this.dataIndex, allChecked);
                       }, me);
                       me.store.resumeEvents();
                       me.up('grid').getView().refresh();
                       this.updatingAll = false;
                       this.onStoreDateUpdate();
                       me.fireEvent('checkallchange', me, allChecked);
                   }
               },

               getHeaderCheckboxImage: function (allChecked) {
                   var cls = [],
                       cssPrefix = Ext.baseCSSPrefix;

                   if (this.columnHeaderCheckbox) {
                       allChecked = this.getStoreIsAllChecked();
                       //Extjs 4.2.x css
                       cls.push(cssPrefix + 'grid-checkcolumn');
                       //Extjs 4.1.x css
                       cls.push(cssPrefix + 'grid-checkheader');

                       if (allChecked) {
                           //Extjs 4.2.x css
                           cls.push(cssPrefix + 'grid-checkcolumn-checked');
                           //Extjs 4.1.x css
                           cls.push(cssPrefix + 'grid-checkheader-checked');
                       }
                   }
                   return '<div style="margin:auto" class="' + cls.join(' ') + '">&#160;</div>'
               }
           });


           Ext.onReady(function () {
               Ext.QuickTips.init();

               tree2_store=Ext.create('Ext.data.TreeStore', {
                   autoLoad: true,
                   fields: [
                       'children', 'realId', 'expanded', 'icon', 'mac','nick','doUpdate', 'note', 'leaf', { name: 'text', sortType: 'asNatural' }, 'status', 'assigned', 'text_f', 'ver', 'level', 'device_id','ip', 'waitUpdate','model','reportGroup'
                   ],
                   proxy: {
                       type: 'ajax',
                       url: '/Apps/DeviceSystem/Handler.ashx?action=GetStructureTreeByNickName'
                   },
                   root: {
                       text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                       id: '<%=rootIdent %>'
                   },
                   sorters: [{ property: 'text', direction: 'ASC' }],
                   folderSort: true
               });


               tree2 = Ext.create('Ext.tree.Panel', {
                   region: 'center',
                   //title: '【<%=GetGlobalResourceObject("CMSResource", "CommunityStructure")%>】',
                   flex: 1,
                   border: true,
                   store:tree2_store ,
                   multiSelect: false,
                   singleExpand: false,

                   viewConfig: {
                       stripeRows: true
                   },
                   sortableColumns: false,

                   columns: [{
                       xtype: 'treecolumn', //this is so we know which column will show the tree
                       text: '<%=GetGlobalResourceObject("CMSResource", "DeviceType")%>',
                       flex: 1,
                       sortable: false,
                       dataIndex: 'text',
                       menuDisabled: true
                   }, {
                       text: 'MAC',
                       width: 120,
                       dataIndex: 'mac',
                       sortable: false,
                       menuDisabled: true
                   },{
                       text: 'IP',
                       width: 120,
                       dataIndex: 'ip',
                       sortable: false,
                       menuDisabled: true
                   }, {
                       text: '<%=GetGlobalResourceObject("CMSResource", "DeviceID")%>',
                       width: 90,
                       dataIndex: 'device_id',
                       sortable: false,
                       menuDisabled: false,
                       renderer: function (value, metaData, record) {
                           if (value == null) return "";

                           //console.log("waitUpdate=" + record.get("waitUpdate"));
                           if (record.get("waitUpdate") == "Y")
                               return "<font color=red>" + value + "</font>"
                           else
                               return "<font color=green>" + value + "</font>"
                       }
                   },{
                       text:'<%=GetGlobalResourceObject("CMSResource", "Nick")%>',
                       dataIndex:'nick',
                       flex: 1,
                       renderer: function (value, id, record) {
                           return "<font color=blue>" + value + "</font>";
                       }
                   },{
                       text:'<%=GetGlobalResourceObject("CMSResource", "BelongBox")%>',
                       width: 100,
                       hideable: false,
                       renderer: function (value, meta, record) {

                           if (record.get("model")!="280") {
                               return;
                           }

                           var id = Ext.id();
                           setTimeout(function () {
                               var button = Ext.create('Ext.form.ComboBox', {
                                   record: record,
                                   width:80,
                                   store: Ext.create('Ext.data.Store', {
                                       fields: ['abbr', 'name'],
                                       data : [
                                           {"abbr":"1", "name":"1"},
                                           {"abbr":"2", "name":"2"},
                                           {"abbr":"3", "name":"3"},
                                           {"abbr":"4", "name":"4"}
                                       ]
                                   }),
                                   queryMode: 'local',
                                   displayField: 'name',
                                   valueField: 'abbr',
                                   editable:false,
                                   value:record.get("reportGroup"),
                                   listeners:{
                                       'change':function(combo, newValue, oldValue, eOpts ){
                                           
                                           Ext.Ajax.request({
                                               url: 'Handler.ashx?action=UpdateElevatorNum',
                                               params: {
                                                   mac:record.get("mac"),
                                                   newValue: newValue
                                               },
                                               success: function (response) {
                                               //    try {
                                               //        var result = Ext.decode(response.responseText);
                                               //        if (result.success) {
                                                       
                                               //        }
                                               //        else {
                                               //            combo.setValue(oldValue);
                                               //        }
                                               //    } catch (e) {
                                               //        combo.setValue(oldValue);
                                               //    }

                                               },
                                               failure:function(){
                                                   //combo.setValue(oldValue);
                                               }
                                           });
                                       }
                                   }
                               });
                               if (Ext.get(id)) {
                                   button.render(Ext.get(id));
                               }
                           }, 1);
                           return '<div id="' + id + '"></div>';

                       }
                   },{
                       width: 100,
                       hideable: false,
                       renderer: function (value, meta, record) {

                           if (record.get("model")!="280") {
                               return;
                           }

                           var id = Ext.id();
                           setTimeout(function () {
                               var button = Ext.create('Ext.button.Button', {
                                   text:'<%=GetGlobalResourceObject("CMSResource", "ManageLevel")%>',
                                   icon: '/Common/DMZ/Images/16x16/edit.png',
                                   record: record,
                                   cls: 'x-btn-default-small',
                                   border: 1,
                                   style: {
                                       borderColor: 'gray',
                                       borderStyle: 'solid'
                                   },
                                   handler: function () {

                                       var s=Ext.create('Ext.data.Store', {
                                           autoLoad: true,
                                           fields:['name', 'ident', 'checked'],
                                           proxy: {
                                               type: 'ajax',
                                               url: 'Handler.ashx?action=GetElevatorMgt&mac=' + record.get("mac"),
                                               reader: {
                                                   type: 'json',
                                                   root: 'items',
                                                   totalProperty: 'totalCount'
                                               },
                                               simpleSortMode: true
                                           },
                                           sorters: [{
                                               property: "text"
                                           }]
                                       });

                                       var w = Ext.create('Ext.window.Window', {
                                           title: '<%=GetGlobalResourceObject("CMSResource", "ManageLevel")%>',
                                           height: 300,
                                           width: 300,
                                           layout: 'fit',
                                           modal: true,
                                           constrain: true,
                                           shadow: true,
                                           shadowOffset: 50,
                                           border: false,
                                           items: [
                                                Ext.create('Ext.grid.Panel', {
                                                    viewConfig:{
                                                        markDirty:false
                                                    },
                                                    store: s,
                                                    columns: [
                                                        {
                                                            xtype: "checkcolumn",
                                                            columnHeaderCheckbox: true,
                                                            store: s,
                                                            sortable: false,
                                                           hideable: false,
                                                           menuDisabled: true,
                                                            width:30,
                                                            dataIndex: "checked"
                                                        },
                                                        {  
                                                            dataIndex: 'name',
                                                            flex:1,
                                                            menuDisabled: true
                                                        }
                                                    ]
                                                })
                                           ],
                                           buttons: [
                                                                                              {
                                                                                                  text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                                                                                  border: 1,
                                                                                                  style: {
                                                                                                      borderColor: 'gray',
                                                                                                      borderStyle: 'solid'
                                                                                                  },
                                                                                                  handler: function() {

                                                                                                      var list="";
                                                                                                      s.each(function(rec){
                                                                                                          if(rec.get("checked")) {
                                                                                                              if(list!="") list=list + ",";
                                                                                                              list=list + rec.get("ident");
                                                                                                          }
                                                                                                      });


                                                                                                      Ext.Ajax.request({
                                                                                                          url: 'Handler.ashx?action=SaveElevatorMgt',
                                                                                                          params: {
                                                                                                              mac:record.get("mac"),
                                                                                                              list: list
                                                                                                          },
                                                                                                          success: function (response) {
                                                                                                              var result = Ext.decode(response.responseText);
                                                                                                              if (result.success) {
                                                                                                                  w.close();
                                                                                                              }
                                                                                                              else {

                                                                                                              }
                                                                                                          }
                                                                                                      });
                                                                                                      
                                                                                                  }
                                                                                              },
                                               {
                                                   text: '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                                                   border: 1,
                                                   style: {
                                                       borderColor: 'gray',
                                                       borderStyle: 'solid'
                                                   },
                                                   handler: function() {
                                                       w.close();
                                                   }
                                               }
                                           ]
                                       }).show(); 

                                   },
                               });
                               if (Ext.get(id)) {
                                   button.render(Ext.get(id));
                               }
                           }, 1);
                           return '<div id="' + id + '"></div>';

                       }
                   }],
                   listeners: {
                       //'afteritemexpand': function () {
                       //    tree2.getStore().sort("text", "ASC");
                       //},
                       'beforeitemappend':function(tree, node, eOpts){
                           if (node.isLeaf()==false || node.get("model")=="280"){
                           }
                           else{
                               return false;
                           }
                       },
                       'itemappend': function (n, node, index, eOpts) {

                           if (node.isLeaf()) {
                               var device_id = getAllParent(node);

                               //改編碼無全區
                               //device_id = padRight(device_id,totalLength);
                               //device_id = padLeft(device_id,8);
                               device_id = padRight(device_id,8);

                               //console.log("1--" + node.get("device_id").split('-')[0]);
                               //console.log("2--" + device_id);
                               if (node.get("device_id").split('-')[0] != device_id) {
                                   var dids = [];
                                   node.parentNode.eachChild(function (n) {

                                       if (n.isLeaf() && node.get("device_id") != n.get("device_id")) {

                                           dids.push(n.get("device_id"));
                                       }

                                   })

                                   for (var i = 1; i < 256; i++) {
                                       var curDid = device_id + "-" + i;
                                       var curDid_OK = true;
                                       dids.forEach(function (did) {
                                           if (curDid == did) {
                                               curDid_OK = false;
                                           }
                                       });

                                       if (curDid_OK) {
                                           node.set("device_id", curDid);
                                           break;
                                       }
                                   }

                               }


                           }
                           else {
                               if (totalLevel == node.getDepth()) {
                                   node.set("icon", "/Common/DMZ/Images/16x16/home.png");
                               }

                           }

                       }
                   }
               });


            //function padLeft(str, lenght) {
            //    if (str.length >= lenght)
            //        return str;
            //    else
            //        return padLeft("0" + str, lenght);
            //}
            function padRight(str, lenght) {
                if (str.length >= lenght)
                    return str;
                else
                    return padRight(str + "0", lenght);
            }

            function getAllParent(node) {
                var parentNode = node.parentNode;
                var names = "";
                if (parentNode) {
                    names = getAllParent(parentNode) + parentNode.get("realId");
                }
                return names;

            }


            Ext.create('Ext.container.Viewport', {
                layout: 'border',
                items: [ tree2

                ]
            });


            tree2.getSelectionModel().select(0); //Select Root
        });

           
    </script>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

