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

<!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>
    <style>
                        .borderred {
            border: solid 2px green
        }
    </style>
     <script language=javascript>
         var itemList = '<%=itemList%>';
         var MAC = '<%=MAC%>';
         var modifyMap = new Ext.util.HashMap();

         Ext.define('MyTextfield', {
             extend: 'Ext.form.field.Text',
             xtype: 'mytextfield',
             labelStyle: 'color:#0041C2;',
             initComponent: function () {
                 var me = this,
                     tm = new Ext.util.TextMetrics();

                 me.labelWidth = tm.getWidth(me.fieldLabel) + 10;
                 tm.destroy();

                 me.callParent(arguments);
             },
             listeners: {
                 'change': function () {
                     if (this.doCheckValue) {
                         if (this.getValue() == this.originalValue) {
                             modifyMap.removeAtKey(this.getId());
                             this.setFieldStyle("border:solid 1px silver");
                         }
                         else {
                             modifyMap.add(this.getId(), this.getId());
                             this.setFieldStyle("border:solid 2px green");
                         }
                     }
                 }
             }
         });

         Ext.define('MyPassTextfield', {
             extend: 'Ext.form.field.Text',
             xtype: 'mypasstextfield',
             inputType: 'password',
             labelStyle: 'color:#0041C2;',
             initComponent: function () {
                 var me = this,
                     tm = new Ext.util.TextMetrics();

                 me.labelWidth = tm.getWidth(me.fieldLabel) + 10;
                 tm.destroy();

                 me.callParent(arguments);
             },
             listeners: {
                 'change': function () {
                     if (this.doCheckValue) {
                         if (this.getValue() == this.originalValue) {
                             modifyMap.removeAtKey(this.getId());
                             this.setFieldStyle("border:solid 1px silver");
                         }
                         else {
                             modifyMap.add(this.getId(), this.getId());
                             this.setFieldStyle("border:solid 2px green");
                         }
                     }
                 }
             }
         });

         Ext.define('MyNumberfield', {
             extend: 'Ext.form.field.Number',
             xtype: 'mynumberfield',
             labelStyle: 'color:#0041C2;',
             initComponent: function () {
                 var me = this,
                     tm = new Ext.util.TextMetrics();

                 me.labelWidth = tm.getWidth(me.fieldLabel) + 10;
                 tm.destroy();

                 me.callParent(arguments);
             },
             listeners: {
                 'change': function () {
                     if (this.doCheckValue) {
                         if (this.getValue() == this.originalValue) {
                             modifyMap.removeAtKey(this.getId());
                             this.setFieldStyle("border:solid 1px silver");
                         }
                         else {
                             modifyMap.add(this.getId(), this.getId());
                             this.setFieldStyle("border:solid 2px green");
                         }
                     }
                 }
             }
         });

         Ext.define('MyCombofield', {
             extend: 'Ext.form.field.ComboBox',
             xtype: 'mycombofield',
             labelStyle: 'color:#0041C2;',
             initComponent: function () {
                 var me = this,
                     tm = new Ext.util.TextMetrics();
                
                 me.labelWidth = tm.getWidth(me.fieldLabel) + 10;
                 tm.destroy();

           

                 me.callParent(arguments);
             },
             //getTextByValue: function (value) {
             //    var text = "";
             //    console.log("at getTextByValue");
             //    this.store.data.each(function (record) {
             //        if (record.get("abbr") == value) text=record.get("name");
             //    });
             //    console.log("text==>" + text);
             //    return text;
             //},
             listeners: {
                 'change': function () {
                     if (this.doCheckValue) {
                         if (this.getValue() == this.originalValue) {
                             modifyMap.removeAtKey(this.getId());
                             this.setFieldStyle("border:solid 1px silver");
                         }
                         else {
                             modifyMap.add(this.getId(), this.getId());
                             this.setFieldStyle("border:solid 2px green");
                         }
                     }


                 }
             }

         });

         var myaction4edit = {
             xtype:'actioncolumn',
             width: 30,
             sortable: false,
             menuDisabled: true,
             hideable: false,
             align: 'center',
             items: [{
                 icon: '/Common/DMZ/Images/16x16/edit.png',
                 tooltip: '<%=GetGlobalResourceObject("CMSResource", "Eidt")%>',
                 handler: function (view, rowIndex, colIndex, item, e, record, row) {
                     view.up('grid').getView().select(record);
                     view.up('grid').edit(this.up('grid'), record);
                 }
             }]
         };

         var myaction4del = {
             xtype: 'actioncolumn',
             width: 30,
             sortable: false,
             menuDisabled: true,
             align: 'center',
             items: [{
                 icon: '/Common/DMZ/Images/16x16/delete.png',
                 tooltip: '<%=GetGlobalResourceObject("CMSResource", "Delete")%>',
                 handler: function (view, rowIndex, colIndex, item, e, record, row) {
                     view.up('grid').store.remove(record);
                     view.up('grid').checkValue(view.up('grid').store);
                 }
             }]
         };

         var myproxy = {
             type: 'memory',
             reader: {
                 type: 'json',
                 root: 'items'
             }
         };

         Ext.define('MyStringArray', {
             extend: 'Ext.grid.Panel',
             xtype: 'mystringarray',
             //height: 300,
             hideHeaders: true,
             margin: '0 10 10 10',
             collapsible: true,
             frame: true,
             note: '',
             checkValue:function(s){
                 var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                 console.log("MyStringArray-checkValue==>" + s.originalValue + "==>" + value);
                 try {
                     if (value == s.originalValue) {
                         modifyMap.removeAtKey(s.ownerId.replace("extobj_", "exthid_"));
                         Ext.getCmp(s.ownerId).removeCls('borderred');
                     }
                     else {
                         modifyMap.add(s.ownerId.replace("extobj_", "exthid_"), s.ownerId.replace("extobj_", "exthid_"));
                         Ext.getCmp(s.ownerId).addClass('borderred');
                     }

                 } catch (e) {

                 }

                 Ext.getCmp(s.ownerId.replace("extobj_", "exthid_")).setValue(value);
             },
             initComponent: function () {
                 var me = this;
                 me.store.ownerId = me.id;

                 var _colData = Ext.getCmp(me.id.replace("extobj_", "exthid_")).getValue();

                 //me.store.originalValue = _colData;

                 me.store.data.items = [];

                 if (_colData != "") {
                     Ext.Array.each(_colData.split('@'), function (item) {
                         eval("me.store.data.items.push({ " + item + "})");
                     });
                 }


                 me.callParent(arguments);
             },
             viewConfig: {
                 markDirty: false
             },
             tools: [
                 {
                     type: 'help',
                     tooltip: '<%=GetGlobalResourceObject("CMSResource", "Explanation")%>',
                     callback: function (panel, tool, event) {
                         alert(this.up('mystringarray').note);
                     }
                 }
             ],
             header: {
                 titlePosition: 0,
                 items: [
                                                            {
                                                                xtype: 'button',
                                                                text: '<%=GetGlobalResourceObject("CMSResource", "NewItem")%>',
                                                                handler: function () {
                                                                    var person = prompt("<%=GetGlobalResourceObject("CMSResource", "InputItemPls")%>", "");
                                                                    if (person != null && person != "") {
                                                                        this.up('grid').store.add({ value: person });
                                                                        this.up('grid').checkValue(this.up('grid').store);
                                                                    }
                                                                },
                                                                cls: 'x-btn-default-small',
                                                                border: 1,
                                                                style: {
                                                                    borderColor: 'white',
                                                                    borderStyle: 'solid'
                                                                }
                                                            }
                 ]
             },
             store: {
                 xtype: 'store',
                 fields: ['value'],
                 data: {
                     'items': [
                     ]},
                 proxy: {
                     type: 'memory',
                     reader: {
                         type: 'json',
                         root: 'items'
                     }
                 },
                 listeners: {
                     'load':function(s){
                         var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                         this.originalValue = value;
                     }
                     //,
                     //'datachanged': function (s) {
                     //    var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                     //    console.log("MyStringArray-datachanged==>" + this.originalValue + "==>" + value);
                     //    try {
                     //        if (value == "[" + this.originalValue + "]")
                     //        {
                     //            modifyMap.removeAtKey(s.ownerId.replace("extobj_", "exthid_"));
                     //            Ext.getCmp(s.ownerId).removeCls('borderred');
                     //        }
                     //        else {
                     //            modifyMap.add(s.ownerId.replace("extobj_", "exthid_"), s.ownerId.replace("extobj_", "exthid_"));
                     //            Ext.getCmp(s.ownerId).addClass('borderred');
                     //        }
                                 
                     //    } catch (e) {

                     //    }

                     //    Ext.getCmp(s.ownerId.replace("extobj_", "exthid_")).setValue(value);
                     //}
                 }
             },
             selType: 'cellmodel',
             //plugins: [
             //    Ext.create('Ext.grid.plugin.CellEditing', {
             //        clicksToEdit: 1
             //    })
             //],

             selType: 'rowmodel',
             plugins: {
                 ptype: 'rowediting',
                 clicksToEdit: 1,
                 listeners: {
                     'edit': function (editor, context) {
                         Ext.Function.defer(function (t) {
                             context.grid.checkValue(context.grid.store);
                         }, 100);
                     }
                 }
             },
             columns: [
                 {xtype: 'rownumberer'},
                 {
                     text: '',
                     dataIndex: 'value',
                     flex: 1,
                     editor: {
                         xtype: 'textfield'
                         //listeners: {
                         //    'blur': function () {
                         //        Ext.Function.defer(function (t) {
                         //            t.up('grid').checkValue(t.up('grid').store);
                         //        }, 100);
                                 
                         //    }
                         //}
                     }
                 },
                {
                    xtype: 'actioncolumn',
                    width: 30,
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    items: [{
                        icon: '/Common/DMZ/Images/16x16/delete.png',
                        tooltip: '<%=GetGlobalResourceObject("CMSResource", "Delete")%>',
                        //scope: this,
                        handler: function (view, rowIndex, colIndex, item, e, record, row) {
                            view.up('grid').store.remove(record);
                            view.up('grid').checkValue(view.up('grid').store);
                        }
                    }]
                }
             ]
         });

         Ext.define('MyObjectArray', {
             extend: 'Ext.grid.Panel',
             xtype: 'myobjectarray',
             //height: 300,
             margin: '0 10 10 10',
             collapsible: true,
             frame: true,
             note: '',
             checkValue: function (s) {
                 var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                 try {
                     if (value == s.originalValue) {
                         modifyMap.removeAtKey(s.ownerId.replace("extobj_", "exthid_"));
                         Ext.getCmp(s.ownerId).removeCls('borderred');
                     }
                     else {
                         modifyMap.add(s.ownerId.replace("extobj_", "exthid_"), s.ownerId.replace("extobj_", "exthid_"));
                         Ext.getCmp(s.ownerId).addClass('borderred');
                     }

                 } catch (e) {

                 }
                 Ext.getCmp(s.ownerId.replace("extobj_", "exthid_")).setValue(value);
             },
             initComponent: function () {
                 var me = this;
                 me.store.ownerId = me.id;

                 me.store.fields = [];

                 me.columns = [];
                 me.columns.push({ xtype: 'rownumberer' });
                 
                 Ext.Array.each(me.editForm, function (item) {
                    
                     me.columns.push({
                         text: "<font color=#0041C2>" + item.fieldLabel + "</font>",
                         dataIndex: item.name,
                         flex: 1,
                         renderer: function (value) {
                             console.log("item.id==>" + item.id);
                             debugger;
                             try {
                                 var v = "";
                                 
                                 Ext.Array.each(item.store.data, function (k) {
                                     console.log("item.fields==>" + k.name);
                                     if (k.abbr == value) v = k.name;
                                 });

                               
                                 //eval("v=Ext.getCmp('" + item.id + "').getTextByValue(value);");
                                 console.log("v==>" + v);
                                 return v;
                             } catch (e) {
                                 return value;
                             }
                             
                         }
                     });

                     me.store.fields.push(item.name);
                 });
                 me.columns.push(myaction4edit);
                 me.columns.push(myaction4del);

                 me.callParent(arguments);

                 var _colData = Ext.getCmp(me.id.replace("extobj_", "exthid_")).getValue();

                 //me.store.originalValue = _colData;
                 me.store.data.items = [];

                 if (_colData != "") {
                     Ext.Array.each(_colData.split('@'), function (item) {
                         //eval("me.store.data.items.push({ " + item + "})");
                         eval("me.store.add({ " + item + "})");
                     });
                 }
                
                 
                 
             },
             edit: function (grid, rec) {
                 var w = Ext.create('Ext.window.Window', {
                     modal: true,
                     constrain: true,
                     shadow: true,
                     shadowOffset: 50,
                     layout: 'fit',
                     items: [
                         {
                             xtype: 'form',
                             padding: '5 5 5 5',
                             border: false,
                             items: this.editForm,
                             buttons: [
                                     {
                                         text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                         formBind: true,
                                         handler: function () {
                                             if (rec) {
                                                 //編輯
                                                 var selectedRecord = grid.getSelectionModel().getSelection()[0];
                                                 var row = grid.store.indexOf(selectedRecord);

                                                 eval("grid.store.insert(row," + Ext.JSON.encode(this.up('form').getValues()) + ")");
                                                 grid.store.removeAt(row + 1);
                                             }
                                             else {
                                                 //新增
                                                 console.log(Ext.JSON.encode(this.up('form').getValues()));
                                                 eval("grid.store.add(" + Ext.JSON.encode(this.up('form').getValues()) + ")");

                                             }
                                             grid.checkValue(grid.store);
                                             this.up('window').close();
                                         }
                                     }, {
                                         text: '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                                         handler: function () {
                                             this.up('window').close();

                                         }
                                     }
                             ]
                         }
                     ],

                     listeners: {
                         "afterrender": function (win) {
                             if (rec) {
                                 win.down('form').loadRecord(rec);
                             }
                         }
                     }
                 }).show();

             },
             tools: [
                 {
                     type: 'help',
                     tooltip: '<%=GetGlobalResourceObject("CMSResource", "Explanation")%>',
                     callback: function (panel, tool, event) {
                         alert(this.up('myobjectarray').note);
                     }
                 }
             ],
             header: {
                 titlePosition: 0,
                 items: [
                        {
                            xtype: 'button',
                            text: '<%=GetGlobalResourceObject("CMSResource", "NewItem")%>',
                            handler: function () {
                                this.up('grid').edit(this.up('grid'));
                            },
                            cls: 'x-btn-default-small',
                            border: 1,
                            style: {
                                borderColor: 'white',
                                borderStyle: 'solid'
                            }
                        }
                 ]
             }
             ,
             //editForm: [
             // //Server define
             //     {
             //         xtype: 'textfield',
             //         fieldLabel: 'value1',
             //         name: 'value1',
             //         allowBlank: false
             //     },
             //     {
             //         xtype: 'numberfield',
             //         fieldLabel: 'value2',
             //         name: 'value2',
             //         allowBlank: false
             //     }
             //],
             //colData: "value1:'aaa',value2:2@value1:'bbb',value2:3",//Server define
             store: {
                 fields:[],
                 data: {
                     'items': [
                     ]
                 }, proxy: myproxy,
                 listeners: {
                     'load':function(s){
                         var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                         this.originalValue = value;
                     }
                     //'datachanged': function (s) {
                     //    var value = Ext.encode(Ext.pluck(s.data.items, 'data'));

                     //    try {
                     //        if (value == "[" + this.originalValue + "]") {
                     //            modifyMap.removeAtKey(s.ownerId.replace("extobj_", "exthid_"));
                     //            Ext.getCmp(s.ownerId).removeCls('borderred');
                     //        }
                     //        else {
                     //            modifyMap.add(s.ownerId.replace("extobj_", "exthid_"), s.ownerId.replace("extobj_", "exthid_"));
                     //            Ext.getCmp(s.ownerId).addClass('borderred');
                     //        }

                     //    } catch (e) {

                     //    }
                     //    Ext.getCmp(s.ownerId.replace("extobj_", "exthid_")).setValue(value);
                     //}
                 }
             },
             columns: []
         });

         var currentRoot = "";

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

             var lbar = Ext.create('Ext.toolbar.Toolbar', {
                 dock: 'left'
             });

             if (itemList != "") {
                 Ext.Array.each(itemList.split(","), function (value) {
                     lbar.add({
                         xtype: 'button',
                         allowDepress:false,
                         text: value.split('@')[2],
                         tooltip: value.split('@')[1],
                         id: value.split('@')[0],
                         scale: 'large',
                         toggleGroup: "GP",
                         iconAlign: 'right',
                         toggleHandler: function (b, s) {

                             console.log("toggleHandler..." + s);
                             b.setIcon(s ? '/Common/DMZ/Images/32x32/ArrowRight.png' : '');

                             //Ext.getCmp("RButton").setDisabled(false);
                             Ext.getCmp("WButton").setDisabled(false);

                             if (s) {
                                 currentRoot = b.getId();
                                 modifyMap = new Ext.util.HashMap();

                                 //取得項目
                                 Ext.Ajax.request({
                                     url: 'Handler.ashx?iot=<%=iot%>',
                                     params: {
                                         action: 'GetJSONItem',
                                         Ident: value.split('@')[0],
                                         MAC: MAC
                                     },
                                     success: function (response) {
                                         //Ext.getCmp("DetailPanel").removeAll();

                                         Ext.getCmp("DetailPanel").removeAll();


                                         var result = Ext.decode(response.responseText);
                                         if (result.success) {
                                             var dp = Ext.getCmp("DetailPanel");
                                             var content = Ext.JSON.decode(Ext.String.htmlDecode(result.content));
                                             for (var k in content) {
                                                 dp.add(content[k]);
                                             }
                                             //eval("dp.add(" + Ext.String.htmlDecode(result.content) + ")");
                                         }

                                     }
                                 });
                             }


                         },
                         border: 1,
                         style: {
                             borderColor: 'gray',
                             borderStyle: 'solid'
                         }
                     });
                 });
             }


             Ext.create('Ext.container.Viewport', {
                 layout: {
                     type: 'border'
                 },
                 items: [
                     {
                         xtype: 'panel',
                         region: 'north',
                         border: false,
                         defaults: {
                             xtype: 'button',
                             margin: '5 5 5 5',
                             pressed: true,
                             border: '0 0 5 0',
                             style: {
                                 borderColor: 'red',
                                 borderStyle: 'solid'
                             }
                         },
                         items: [
                             {
                                 text: 'Name：<font color=yellow><%=deviceName%></font>'
                             },
                              {
                                  text: 'Model：<font color=yellow><%=deviceModel%></font>'
                              },
                              {
                                  text: 'MAC：<font color=yellow><%=MAC%></font>',
                                  hidden:"<%=iot%>"=="Y"
                              },
                               {
                                   text: 'IP：<font color=yellow><%=ip%></font>',
                                   hidden: '<%=ip%>'==''
                               },
                                {
                                    text: 'ID-s：<font color=yellow><%=deviceID%>-<%=deviceSubID%></font>'
                                },
                                  {
                                      text: 'Model-s：<font color=yellow><%=deviceCode%>-<%=deviceSubCode%></font>'
                                  },
                                 {
                                     text: 'Version：<font color=yellow><%=version%></font>'
                                 }
                         ]
                     },
                       {
                           xtype: 'form',
                           region:'center',
                           id: 'DetailPanel',
                           url: 'Handler.ashx?action=SendData2Device&iot=<%=iot%>',
                           border: false,
                           bodyPadding: 5,
                           defaults: {
                               anchor: '100%',
                               labelWidth: 150
                           },
                           defaultType: 'textfield',
                           autoScroll: true,
                           items: [
                               {
                                   xtype: 'label',
                                   padding:10,
                                   html: "<img src='/Common/DMZ/Images/24x24/back.png' style='vertical-align:middle;'>&nbsp;&nbsp;<font size=3><%=GetGlobalResourceObject("CMSResource", "SelectItemFunc")%></font>"
                               }
                           ],
                           tbar: [
                               '->',
                               //{
                               //    text: "Read From Device",
                               //    border: 1,
                               //    id:'RButton',
                               //    style: {
                               //        borderColor: 'gray',
                               //        borderStyle: 'solid'
                               //    },
                               //    disabled:true
                               //},
                               {
                                   text: "Write To Device",
                                   border: 1,
                                   id: 'WButton',
                                   style: {
                                       borderColor: 'gray',
                                       borderStyle: 'solid'
                                   },
                                   disabled: true,
                                   handler: function () {
                                       var form = this.up("form");
                                       form.submit({
                                           waitMsg: '<%=GetGlobalResourceObject("CMSResource", "SendWait")%>',
                                           params: {
                                               currentRoot: currentRoot,
                                               MAC: MAC,
                                               modifyMap: modifyMap.getKeys().toString()
                                           },
                                                        success: function () {
                                                            //等候5秒重新抓設備參數

                                                            Ext.MessageBox.show({
                                                                msg: '<%=GetGlobalResourceObject("CMSResource", "SuccessWait3Sec")%>',
                                                                progressText: '<%=GetGlobalResourceObject("CMSResource", "Updating")%>',
                                                                width: 300,
                                                                wait: true,
                                                                waitConfig: { interval: 200 }
                                                            });
                                                            setTimeout(function () {
                                                                Ext.MessageBox.hide();
                                                            }, 3000);

                                                            Ext.getCmp(currentRoot).toggle(false);
                                                            Ext.getCmp(currentRoot).toggle(true);
                                                        }
                                                    });
                                   }
                               }
                           ],
                           dockedItems: lbar
                       }
                 ]
             });
         });


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