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

<!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','nick','doUpdate', 'note', 'leaf', { name: 'text', sortType: 'asNatural' }, 'status', 'assigned', 'text_f', 'ver', 'level', 'device_id','ip', 'waitUpdate'
                    ],
                    proxy: {
                        type: 'ajax',
                        url: 'Handler.ashx?action=GetStructureTreeByNickName'
                    },
                    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", "Nick")%>',
                                dataIndex:'nick',
                                renderer: function (value, id, record) {
                                    return "<font color=blue>" + value + "</font>";
                                }
                            },{
                                align: 'center',
                                renderer: function (value, id, record) {
                                    return (value=="" || value==null) ? "" : "<input type=button value='<%=GetGlobalResourceObject("CMSResource", "EditNick")%>' onclick='EditNick(\"" + record.get("id") + "\",\"" + record.get("nick") + "\");'/>";
                },
                                dataIndex: 'mac',
                width: 150
                            }],
                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("nick");
                                        }
                                    });

                                    //console.log(list);
                                    Ext.Ajax.request({
                                        url: 'Handler.ashx?action=SaveNickSetting',
                                        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")%>";
                      }

                  }

           
                  function EditNick(id,value){

                      var answer = prompt ("<%=GetGlobalResourceObject("CMSResource", "InputNickPls")%>",value);
                      if (answer != null) {
                          tree2.store.getNodeById(id).set("nick",answer);
                          tree2.store.getNodeById(id).set("doUpdate","Y");
                          Ext.getCmp("SaveButton").setDisabled(false);
                      }

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