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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
  <script language=javascript>
      var unitList = "<%=unitList %>";
      var totalLevel = unitList.split("@").length;
      var totalLength=<%=totalLength%> ;
      var TargetSystem="<%=TargetSystem%>";

      window.onbeforeunload = function (e) {
          if (!Ext.getCmp("SaveButton").isDisabled()) {
              e = e || window.event;
              e.preventDefault = true;
              e.cancelBubble = true;
              e.returnValue = "<%=GetGlobalResourceObject("CMSResource", "NotYetSaveData")%>";
          }

      }

      var tree,tree2;
      var tree2Loading=false;
      
      Ext.onReady(function () {

          Ext.apply(Ext.form.VTypes, {
              fileUpload: function(val, field) {                              
                  var fileName = /^.*\.(txt|csv)$/i;
                  return fileName.test(val);
              },                 
              fileUploadText: '<%=GetGlobalResourceObject("CMSResource", "FileFormatTxtOrCSV")%>'
          });

          Ext.QuickTips.init();

          var store = Ext.create('Ext.data.TreeStore', {
              fields: [
                  'children', 'expanded', 'icon', 'mac', 'nick', 'leaf', 'text', 'status', 'assigned', 'ver', 'ip', 'code', 'device_id', 'device_id_ori','model','MAC','IP', 'children_count', 'waitUpdate'
              ],
              proxy: {
                  type: 'ajax',
                  url: 'Handler.ashx?action=GetTree&hideAssign=Y&viewType=2'
              },
              root: {
                  expanded: true,
                  text: '<%=GetGlobalResourceObject("CMSResource", "AllDevice")%>',
                  allowDrag: false,
                  //id: '-1',
                  children: [
                      <%=TargetSystem=="1"?"":"{ text: '" + GetGlobalResourceObject("CMSResource", "IPBox") + "', leaf: false,id: '-2',expanded:false},"%>
            { text: "<%=GetGlobalResourceObject("CMSResource", "TerminalDevice")%>", leaf: false,id: '-1',expanded:true }
            
                  ]
              }
          });

          tree = Ext.create('Ext.tree.Panel', {
              region: 'west',
              title: '【<%=GetGlobalResourceObject("CMSResource", "ToDoDeviceList")%>】',
              flex: 1,
              split: true,
              border: true,
              store: store,
              useArrows: true,
              collapsible: true,
              collapsed:true,
              multiSelect: false,
              singleExpand: false,
              rootVisible: false,
              plugins: [
    Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1,
        listeners: {
            'beforeedit': function (editor, e) {
                if (e.record.parentNode.get("id") == "-1") return false;
            },
            'edit': function (editor, e) {
                var device_id = e.value;
                
                if (device_id != "") {
                    Ext.Ajax.request({
                        url: 'Handler.ashx?action=SaveSingleDeviceID',
                        params: {
                            device_id: device_id,
                            mac:e.record.get("mac")
                        },
                        success: function (response) {
                            var result = Ext.decode(response.responseText);
                            if (result.success) {

                                Ext.getCmp("SaveButton").setDisabled(false);

                                var buildingIdent = result.buildingIdent;

                                var node = tree2.store.getNodeById(buildingIdent);
                                if (node) {
                                    tree2.store.load({node:node});
                                }

                                tree.store.load({ node: e.record.parentNode });
                                //e.record.parentNode.removeChild(e.record);
                            }
                            else {

                            }
                        }
                    });
                }

            }
        }
    })
              ],
              viewConfig: {
                  stripeRows: true,
                  plugins: {
                      ptype: 'treeviewdragdrop',
                      ddGroup: 'MyG',
                      appendOnly: true,
                      sortOnDrop: true,
                      enableDrop: false,
                      containerScroll: true
                  }
              },
              sortableColumns: false,
              tbar:[                        '->',
                        {
                            text: '<%=GetGlobalResourceObject("CMSResource", "ImportMapList")%>',
                            cls: 'x-btn-default-small',
                            border: 1,
                            style: {
                                borderColor: 'gray',
                                borderStyle: 'solid'
                            },
                            icon: '/Common/DMZ/Images/16x16/Import.png',
                            handler: function () {
                                
                                var f=Ext.create('Ext.form.Panel', {
                                    width: 350,
                                    bodyBorder:false,
                                    border:false,
                                    bodyPadding: 10,
                                    items: [{
                                        xtype: 'filefield',
                                        name: 'mFile',
                                        hideLabel:true,
                                        msgTarget: 'side',
                                        allowBlank: false,
                                        anchor: '100%',
                                        vtype:'fileUpload',
                                        buttonText: '<%=GetGlobalResourceObject("CMSResource", "SelectFile")%>'
                                    },{
                                        xtype:'label',
                                        html:'<br><%=GetGlobalResourceObject("CMSResource", "FormatSample")%>(MAC,ID)：<br><br>' + 'AA:BB:06:00:00:00:AA:BB,A1001001-1<br>' + 'AA:BB:07:00:00:00:AA:BB,A1002001-1<br>' + 'AA:BB:08:00:00:00:AA:BB,A1002001-2<br>'
                                    }
                                    ],
                                    buttons: [{
                                        text: '<%=GetGlobalResourceObject("CMSResource", "Import")%>',
                                        icon: '/Common/DMZ/Images/16x16/Import.png',
                                        border: 1,
                                        style: {
                                            borderColor: 'gray',
                                            borderStyle: 'solid'
                                        },
                                        handler: function() {
                                            var form = this.up('form').getForm();
                                            if(form.isValid()){



                                                form.submit({
                                                    url: 'Handler.ashx?action=UploadMFile',
                                                    waitMsg: '<%=GetGlobalResourceObject("CMSResource", "Uploafing")%>',
                                                    success: function(fp, o) {
                                                        mWin.close();

                                                        alert("<%=GetGlobalResourceObject("CMSResource", "ImportSuccess")%>");

                                                        if(tree.store.getNodeById("-2")) tree.store.load({ node: tree.store.getNodeById("-2") });
                                                        tree.store.load({ node: tree.store.getNodeById("-1") });
                                                        tree2.store.load({ node: tree2.getRootNode() });

                                                    }
                                                });
                                            }
                                        }
                                    }]
                                });

                                var mWin=Ext.create('Ext.window.Window', {
                                    title: '<%=GetGlobalResourceObject("CMSResource", "ImportMapList")%>',
                                    layout: 'fit',
                                    modal:true,
                                    resizable:false,
                                    constrain:true,
                                    shadow: true,
                                    shadowOffset:50,
                                    items:f
                                }).show();


                            }
                        }
              ],
              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: false,
                  renderer: function (value, metaData, record) {
                      if (record.get("children_count") != "0" && record.get("children_count") != "")
                          return value + "<font color=blue>&nbsp;(" + record.get("children_count") + ")</font>";
                      else
                          return value;

                  }
              }, {
                  text: 'MAC',
                  width: 120,
                  dataIndex: 'mac',
                  sortable: false,
                  menuDisabled: false,
                  renderer:function(value,metaData,record){
                      return (record.get("leaf") || TargetSystem=="1")?value:"";
                  }
              }, {
                  text: 'IP',
                  width: 120,
                  dataIndex: 'ip',
                  sortable: false,
                  hidden: false,
                  menuDisabled: false
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "DeviceCode")%>',
                  width: 60,
                  dataIndex: 'code',
                  sortable: false,
                  hidden: true,
                  menuDisabled: false
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "DeviceID")%>',
                  width: 82,
                  dataIndex: 'device_id',
                  sortable: false,
                  menuDisabled: false,
                  renderer:function(value,metaData,record){
                      return (record.get("leaf") || TargetSystem=="1")?value:"";
                  }
                  //editor: {
                  //    xtype: 'textfield'
                  //}
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "FWVersion")%>',
                  align: 'center',
                  width: 60,
                  dataIndex: 'ver',
                  sortable: false,
                  hidden: true,
                  menuDisabled: false
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "Status")%>',
                  width: 35,
                  dataIndex: 'status',
                  sortable: false,
                  menuDisabled: false,
                  align: 'center',
                  hidden: true,
                  hideable: false,
                  renderer: function (value) {
                      if (value == "") return;
                      //return value == "1" ? '<img src=/Common/DMZ/Images/16x16/enabled.png />' : '<img src=/Common/DMZ/Images/16x16/alert.png />';
                      switch (value) {
                          case "1":
                              return '<img src=/Common/DMZ/Images/16x16/enabled.png />';
                              break;
                          case "-1":
                              return '<img src=/Common/DMZ/Images/16x16/question.png />';
                              break;
                          default:
                              return '<img src=/Common/DMZ/Images/16x16/alert.png />';
                              break;
                      }
                  }
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "Description")%>',
                  flex: 1,
                  dataIndex: 'nick',
                  sortable: false,
                  hidden: true,
                  hideable: false,
                  menuDisabled: false
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "InPosition")%>',
                  width: 50,
                  dataIndex: 'assigned',
                  sortable: false,
                  menuDisabled: false,
                  align: 'center',
                  hidden: true,
                  hideable: false,
                  renderer: function (value) {
                      if (value == "") return;
                      return value == "1" ? "<font color=green><%=GetGlobalResourceObject("CMSResource", "Yes")%></font>" : "<font color=red><%=GetGlobalResourceObject("CMSResource", "No")%></font>";
                  }
              }],
              listeners: {
                  'beforeitemremove': function (tree, node, isMove, eOpts) {
                      if(node.parentNode.get("id")!="-2") node.parentNode.set("children_count", node.parentNode.get("children_count") - 1);
                  }
              }
          });



          tree2 = Ext.create('Ext.tree.Panel', {
              region: 'center',
              title: '【<%=GetGlobalResourceObject("CMSResource", "CommunityStructure")%>】',
              flex: 1,
              border: true,
              store: Ext.create('Ext.data.TreeStore', {
                  autoLoad: true,
                  fields: [
                      'children', 'realId', 'expanded', 'icon', 'mac', 'note', 'leaf', { name: 'text', sortType: 'asNatural' }, 'status', 'assigned', 'text_f', 'ver', 'level', 'device_id', 'device_id_ori','model','ip', 'waitUpdate'
                  ],
                  proxy: {
                      type: 'ajax',
                      url: 'Handler.ashx?action=GetStructureTree'
                  },
                  root: {
                      text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                    id: '<%=rootIdent %>'
                  },
                  sorters: [{property:'text', direction: 'ASC'}],
                  folderSort: true,
                  listeners:{
                      'beforeload':function(){
                          tree2Loading=true;
                      },
                      'load':function(){
                          tree2Loading=false;
                      }
                  }
            }),
              multiSelect: false,
              singleExpand: false,

              viewConfig: {
                  stripeRows: true,
                  plugins: {
                      ptype: 'treeviewdragdrop',
                      ddGroup: 'MyG',
                                            appendOnly: false,
                      containerScroll: true
                  },
                  listeners: {
                      nodedragover: function (targetNode, position, dragData, e, eOpts) {

                          Ext.getCmp("SaveButton").setDisabled(false);

                          if("<%=TargetSystem%>"=="0"){
                              if (!dragData.records[0].get("leaf")) return false;
                          }

                          //console.log('nodedragover' + targetNode.get("text")); 
                      },

                      drop: function (node, data, overModel, dropPosition) {         
                         
                          if (data.records[0].isLeaf()) {
                               
                              var n=overModel;
                              if(n.isExpanded()){
                                  updateDeviceID(data.records[0],n);
                              }
                              else{
                                  n.expand();
                                  setTimeout(function(){
                                      updateDeviceID(data.records[0],n);
                                  },300);
                              }
                              
                          
                          }
                      }
                  }
              },
              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'
              }, {
                  text: 'MAC',
                  width: 120,
                  dataIndex: 'mac',
                  sortable: false
              },{
                  text: 'IP',
                  width: 120,
                  dataIndex: 'ip',
                  sortable: false,
                  hidden: false,
                  menuDisabled: false
              }, {
                  text: '<%=GetGlobalResourceObject("CMSResource", "DeviceID")%>',
                  width: 90,
                  dataIndex: 'device_id',
                  sortable: false,
                  renderer: function (value, metaData, record) {
                      if (value == null) return "";

                      //console.log("waitUpdate==" + (record.get("waitUpdate")=="Y") + ",id=" + value);

                      //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", "OriDeviceID")%>",
                  width: 90,
                  dataIndex: 'device_id_ori',
                  sortable: false,
                  hidden:true
              }],
              bbar: [
                  '<font size=3 color=red><b>※ <%=GetGlobalResourceObject("CMSResource", "AllowSameID")%></b></font>',
                  '->',
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "SaveSetting")%>',
                    scale: 'medium',
                    id: 'SaveButton',
                    disabled:true,
                    icon: '/Common/DMZ/Images/24x24/floppy.png',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    handler: function () {
                        var list = "";

                        tree2.getRootNode().cascade(function (n) {
                            if (n.get("waitUpdate")=="Y" && n.get("device_id") != null && n.get("device_id") !="") {
                                if (list != "") list = list + ",";
                                list = list + n.parentNode.get("id") + "|" + n.get("mac") + "|" + n.get("device_id");
                            }
                        });

                        //console.log(list);

                        Ext.MessageBox.show({
                            msg: '<%=GetGlobalResourceObject("CMSResource", "SaveSetting")%>',
                            progressText: '<%=GetGlobalResourceObject("CMSResource", "SaveWait")%>',
                                    width: 300,
                                    wait: true,
                                    waitConfig: { interval: 200 }
                                });

                        Ext.Ajax.request({
                            url: 'Handler.ashx?action=SaveDeviceID',
                            params: {
                                list: list
                            },
                            success: function (response) {
                                Ext.MessageBox.hide();
                                var result = Ext.decode(response.responseText);
                                if (result.success) {
                                    
                                    alert("<%=GetGlobalResourceObject("CMSResource", "DeviceAssignSuccess")%>");
                                    Ext.getCmp("SaveButton").setDisabled(true);
                                }
                                else {

                                }
                            }
                        });
                    }
                }
            ],
              listeners: {
                  'itemcontextmenu':function(view, record, item, index, event){
                      if(record.isLeaf()){
                          var menu=Ext.create('Ext.menu.Menu', {
                              items: [{
                                  text: '<%=GetGlobalResourceObject("CMSResource", "CustomSubID")%>',
                                  handler: function (){
                                      Ext.create('Ext.window.Window', {
                                          title: '<%=GetGlobalResourceObject("CMSResource", "CustomSubID")%>',
                                          layout: 'fit',
                                          modal:true,
                                          border:false,
                                          items: { 
                                              xtype:'form',
                                              border:false,
                                              bodyPadding: 5,
                                              items:[
                                                  {
                                                      xtype:'numberfield',
                                                      fieldLabel:'<%=GetGlobalResourceObject("CMSResource", "DeviceSubID")%>',
                                                      id:'nSubID',
                                                      minValue:1,
                                                      maxValue:99,
                                                      allowBlank:false,
                                                      value:record.get("device_id").split("-")[1]
                                                  }
                                              ],
                                              buttons:[
                                                  {
                                                      text:'<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                                      formBind:true,
                                                      handler:function(){
                                                          record.set("device_id",record.get("device_id").split("-")[0] + "-" + Ext.getCmp("nSubID").getValue());
                                                          record.set("waitUpdate",record.get("device_id")==record.get("device_id_ori")?"N":"Y");
                                                          record.commit();
                                                          Ext.getCmp("SaveButton").setDisabled(false);
                                                          this.up("window").close();
                                                      }
                                                  },
                                                    {
                                                        text:'<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                                                        handler:function(){
                                                            this.up("window").close();
                                                        }
                                                    }
                                              ]

                                          }
                                      }).show();

                                      //var dlg = Ext.MessageBox.prompt('自訂識別子碼', '請輸入識別子碼(1~99):', function(btn, text){
                                      //    if (btn == 'ok'){
                                      //        try {
                                      //            if(parseInt(text)<1 || parseInt(text)>99)
                                      //            {
                                      //                alert("識別子碼輸入錯誤！");
                                      //                return false;
                                      //            }
                                      //            else
                                      //            {
                                      //            }
                                      //        } catch (e) {
    
                                      //        }
                                              
                                      //    }
                                      //});
                                  }
                              },{
                                  text: '<%=GetGlobalResourceObject("CMSResource", "Parameters")%>',
                                  icon: '/Common/DMZ/Images/16x16/gear.png',
                                  handler: function () {

                                      var w = parent.Ext.create('Ext.window.Window', {
                                          title: '<%=GetGlobalResourceObject("CMSResource", "ParamMainten")%>',
                                          layout: 'fit',
                                          modal: true,
                                          constrain: true,
                                          shadow: true,
                                          shadowOffset: 50,
                                          width: '95%',
                                          height: '95%',
                                          maximizable: true,
                                          items: [
                                             {
                                                 xtype: "component",
                                                 border: false,
                                                 autoEl: {
                                                     tag: "iframe",
                                                     src: "/Apps/DeviceSystem/DeviceParameter.aspx?MAC=" + record.get("mac")
                                                 }
                                             }
                                          ],
                                          buttons: [
                   {
                       text: '<%=GetGlobalResourceObject("CMSResource", "Close")%>',
                       handler: function () {
                           this.up("window").close();
                       }
                   }
                                          ]
                                      }).show();
                                  }
                              },{
                                  text: '<%=GetGlobalResourceObject("CMSResource", "Action")%>',
                                  menu: Ext.create('Ext.menu.Menu', {
                                      items: [
                                          {
                                              text: '<%=GetGlobalResourceObject("CMSResource", "CallIdent")%>',
                                              icon: '/Common/DMZ/Images/16x16/bell.png',
                                              handler: function () {

                                                  Ext.Ajax.request({
                                                      url: 'Handler.ashx?action=HandsUP',
                                                      params: {
                                                          ip: record.get("IP")
                                                      }
                                                  });
                                              }
                                          },'-',
                                              {
                                                  text: '<%=GetGlobalResourceObject("CMSResource", "Reboot")%>',
                                                  icon: '/Common/DMZ/Images/16x16/reload_all_tabs.png',
                                                  handler: function () {
                                                      if (confirm("<%=GetGlobalResourceObject("CMSResource", "RebootConfirm")%>")) {
                                                          Ext.Ajax.request({
                                                              url: 'Handler.ashx?action=Reboot',
                                                              params: {
                                                                  ip: record.get("IP")
                                                              }
                                                          });
                                                      }
                                                  }
                                              }
                                      ]
                                  })
                              }]
                          });
                          menu.showAt(event.getXY());
                          event.stopEvent();
                      }

                  },
                  //'afteritemexpand': function () {
                  //    tree2.getStore().sort("text", "ASC");
                  //},
                  'itemappend': function (n, node, index, eOpts) {

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

                  },
                  'iteminsert': function (n, node, refNode, eOpts) {
                      updateDeviceID(node,n);
                  }
              }
          });

          function updateDeviceID(node,targetNode){

              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("updateDeviceID==>" + device_id);

              var items={};
              targetNode.eachChild(function (n) {
                  //console.log("updateDeviceID==>n.Text==" + n.get("text"));
                  if (n.isLeaf()) {

                      if(n.get("model") in items) 
                          items[n.get("model")]=items[n.get("model")]+1;
                      else
                          items[n.get("model")]=1;
                                      
                      var curDid = device_id + "-" + items[n.get("model")];

                      //console.log("curDid==>" + curDid);
                      //console.log("device_id==>" + n.get("device_id"));

                      //console.log("updateDeviceID==>n.device_id==" + n.get("device_id"));
                      //console.log("updateDeviceID==>curDid==" + curDid);

                      //console.log("device_id_ori==>" + n.get("device_id_ori"));

                      n.set("device_id", curDid);
                      n.set("waitUpdate",n.get("device_id_ori")==curDid?"N":"Y");
                      n.commit();

                  }

              })

                          
              //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);
                          node.set("waitUpdate","Y")
                          break;
                      }
                  }

              }
              */
          }

          //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;

          }

          function getName(record) {
              var Depth = record.getDepth();
              var unit = "";
              switch (Depth) {
                  case 0:
                      unit = "<%=GetGlobalResourceObject("CMSResource", "Building")%>";
                      break;
                  case 1:
                      unit = "<%=GetGlobalResourceObject("CMSResource", "Number")%>";
                      break;
                  case 2:
                      unit = "<%=GetGlobalResourceObject("CMSResource", "Floor")%>";
                      break;
                  case 3:
                      unit = "<%=GetGlobalResourceObject("CMSResource", "Of")%>";
                      break;

              }
              return unit;
          }

          Ext.create('Ext.container.Viewport', {
              layout: 'border',
              items: [tree, tree2
           
              ]
          });


          tree2.getSelectionModel().select(0); //Select Root
      });
  </script>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
