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

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

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

            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','label','doUpdate', 'note', 'leaf', { name: 'text', sortType: 'asNatural' }, 'status', 'assigned', 'text_f', 'ver', 'level', 'device_id','ip', 'waitUpdate'
                                ],
                                proxy: {
                                    type: 'ajax',
                                    url: 'Handler.ashx?action=GetStructureTree'
                                },
                                root: {
                                    text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                      id: '<%=rootIdent %>'
                                },
                                sorters: [{ property: 'text', direction: 'ASC' }],
                                folderSort: true
              }),
                            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", "AreaLabel")%>',
                              width: 200,
                              dataIndex: 'label',
                              sortable: false,
                              menuDisabled: true,
                              renderer:function(value){
                                  if(value.length==0) return "";
                                  var result="";
                                  for (var i = 0; i < value.split(",").length; i++) {
                                      if(result!="") result=result +  "、"
                                      result=result + value.split(",")[i].split("@")[1];
                                  }
                                  return result;
                              }
                          },                                               
                          {
                              xtype: 'actioncolumn',
                              hideable: false,
                              width: 30,
                              sortable: false,
                              menuDisabled: true,
                              align: 'center',
                              items: [{
                                  icon: '/Common/DMZ/Images/16x16/edit.png',
                                  tooltip: '<%=GetGlobalResourceObject("CMSResource", "SettingLabel")%>',
                                  scope: this,
                                  handler: function (view, rowIndex, colIndex, item, e, record, row) {

                                      Ext.create('Ext.window.Window', {
                                          title: "<%=GetGlobalResourceObject("CMSResource", "SettingLabel")%>",
                                          width: 250,
                                          height:300,
                                          constrain: true,
                                          shadow: true,
                                          shadowOffset: 50,
                                          layout: 'fit',
                                          modal: true,
                                          items: [
                                              {
                                                  xtype: 'form',
                                                  //bodyPadding: 5,
                                                  border:false,
                                                  layout: 'fit',
                                                  defaultType: 'textfield',
                                                  defaults: {
                                                      anchor: '100%'
                                                  },
                                                  border: false,
                                                  items: [
                                                                      {
                                                                          xtype: 'grid',
                                                                          id: 'areaGrid',
                                                                          border:false,
                                                                          //flex: 3,
                                                                          viewConfig: {
                                                                              loadMask: false,
                                                                              markDirty: false
                                                                          },
                                                                          store: Ext.create('Ext.data.Store', {
                                                                              autoLoad: true,
                                                                              fields: ['idno', 'name', 'show', 'allow'],
                                                                              proxy: {
                                                                                  type: 'ajax',
                                                                                  url: '/Common/SystemAdmin/Building/Handler.ashx?action=GetAreaData&list=1&ident=',
                                                                                  reader: {
                                                                                      type: 'json',
                                                                                      root: 'items'
                                                                                  }
                                                                              }
                                                                          }),
                                                                          columns: [
                                                                              { header: '<%=GetGlobalResourceObject("CMSResource", "SerialNumber")%>', menuDisabled: true, dataIndex: 'idno', width: 40, align: 'center' },
                        {
                            header: '<%=GetGlobalResourceObject("CMSResource", "AreaName")%>',
                            menuDisabled: true,
                            dataIndex: 'name',
                            flex: 1
                        },
                        {
                            xtype: 'checkcolumn',
                            header: '<%=GetGlobalResourceObject("CMSResource", "Marked")%>',
                            menuDisabled: true,
                            dataIndex: 'allow',
                            width: 90
                        }
                    ]
                                                                      }
                                                  ],
                                                  buttons: [
                                                      {
                                                          text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                                          handler: function () {

                                                              var areaList="";
                                                              Ext.getCmp("areaGrid").store.each(function(record) {
                                                                  if (record.get("allow")) {
                                                                      if (areaList != "") areaList = areaList + ",";
                                                                      areaList = areaList + record.get("idno") + "@"  + record.get("name");
                                                                  }
                                                              });
                                                              record.set("label",areaList);
                                                              record.set("doUpdate","Y");
                                                              
                                                              Ext.getCmp("SaveButton").setDisabled(false);

                                                              this.up("window").close();
                                                          }
                                                      },
                                                      {
                                                          text: '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                                                          handler: function () {
                                                              this.up("window").close();
                                                          }
                                                      }
                                                  ]
                                              }
                                          ]
                                      }).show();
                                  },
                                  isDisabled: function (view, rowIndex, colIndex, item, record) {
                                      return rowIndex == 0;
                                  }
                              }]
                          },
                          {
                              xtype: 'actioncolumn',
                              width: 30,
                              sortable: false,
                              menuDisabled: true,
                              hideable: false,
                              align: 'center',
                              items: [
                                  {
                                      icon: '/Common/DMZ/Images/16x16/broom.png',
                                      tooltip: '<%=GetGlobalResourceObject("CMSResource", "ClearLabel")%>',
                                                        scope: this,
                                                        handler: function (view, rowIndex, colIndex, item, e, record, row) {
                                                            record.set("label","");
                                                            record.set("doUpdate","Y");
                                                            Ext.getCmp("SaveButton").setDisabled(false);
                                                        },
                                                        isDisabled: function (view, rowIndex, colIndex, item, record) {
                                                            return rowIndex == 0;
                                                        }
                                                    }]
                          }],
                          buttons: [
                            {
                                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.dirty && n.get("doUpdate")=="Y") {
                                if (list != "") list = list + "|";
                                list = list + n.get("id") + "#" + n.get("label");
                            }
                        });
                        //console.log(list);
                        Ext.Ajax.request({
                            url: 'Handler.ashx?action=SaveAreaSetting',
                            params: {
                                list: list
                            },
                            success: function (response) {
                                var result = Ext.decode(response.responseText);
                                if (result.success) {

                                    tree2.getRootNode().cascade(function (n) {
                                        if (n.dirty && n.get("doUpdate")=="Y") {
                                            n.set("doUpdate","");
                                            n.commit();
                                        }
                                    });

                                    alert("<%=GetGlobalResourceObject("CMSResource", "SetSuccess")%>");
                                    Ext.getCmp("SaveButton").setDisabled(true);
                                }
                                else {

                                }
                            }
                        });
                    }
                }
              ],
                            listeners: {
                                //'afteritemexpand': function () {
                                //    tree2.getStore().sort("text", "ASC");
                                //},
                                '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
        });

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

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