<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Rule.aspx.cs" Inherits="GigaTech.CMS.Web.Common.SystemAdmin.Building.Rule" %>

<!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 loadFromServer = false;
      var InitTotalLevel = 0;
      var formatChange = false;

      var validMileRadius = /^[MX0]+$/;
      Ext.apply(Ext.form.field.VTypes, {
          //  vtype validation function
          ruleFormat: function (val, field) {
              return validMileRadius.test(val);
          },
          ruleFormatText: '<%=GetGlobalResourceObject("CMSResource", "RuleFormatAlt")%>'
      });

      Ext.onReady(function () {

          Ext.QuickTips.init();

          var store = Ext.create('Ext.data.Store', {
              storeId: 'gridStore',
              autoLoad: true,
              fields: ['text', 'length', 'format'],
              proxy: {
                  type: 'ajax',
                  url: 'Handler.ashx?action=GetIDRule',
                  reader: {
                      type: 'json',
                      root: 'items',
                      totalProperty: 'total'
                  }
              },
              listeners: {
                  'load': function (s, records, successful, eOpts) {
                      if (records.length == 0) {
                          BuildGrid(Ext.getCmp('totalLevel').getValue());
                      } else {

                          InitTotalLevel = records.length;
                          loadFromServer = InitTotalLevel != 5;
                          Ext.getCmp('totalLevel').setValue(records.length);
                          Preview();
                      }
                  },
                  'update': function (s, record, operation, modifiedFieldNames, eOpts) {
                      //                      if (record.get("type") == "E") {
                      //                          record.set("length", 1);
                      //                      }

                      var total = 0;
                      s.each(function (record) {
                          total = total + record.get("length");
                      });

                      if (total > 8) {
                          Ext.getCmp("CheckMsg").setText("<font color=red><%=GetGlobalResourceObject("CMSResource", "LengthTooLong")%></font>");
                          Ext.getCmp("SaveConfig").setDisabled(true);
                          //                          alert("長度總和不可超過 7！");
                      } else {
                          Ext.getCmp("CheckMsg").setText("");
                          Preview();
                      }

                  }
              }
          });


          Ext.create('Ext.container.Viewport', {
              layout: 'border',
              items: [
                  Ext.create('Ext.tree.Panel', {
                      id: 'tree1',
                      region: 'east',
                      title: '<%=GetGlobalResourceObject("CMSResource", "SamplePreview")%>',
                      margin: '5 5 5 5',
                      flex: 1.5,
                      emptyText: '<%=GetGlobalResourceObject("CMSResource", "DataNotComplete")%>',
                      viewConfig: {
                          markDirty: false
                      },
                      columns: [
                          {
                              xtype: 'treecolumn',
                              text: '<%=GetGlobalResourceObject("CMSResource", "Structure")%>',
                              flex: 1,
                              sortable: false,
                              dataIndex: 'text',
                              menuDisabled: true
                          }, {
                              text: '<%=GetGlobalResourceObject("CMSResource", "Description")%>',
                              flex: 1.5,
                              dataIndex: 'desc',
                              sortable: false,
                              menuDisabled: true
                          }
                      ],
                      store: Ext.create('Ext.data.TreeStore', {
                          fields: [
                              'children', 'expanded', 'icon', 'desc', 'leaf', 'text'
                          ],
                          proxy: {
                              type: 'memory'
                          },
                          root: {
                              expanded: true,
                              text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                              children: [
                              ]
                          }
                      })
                  }),
                  Ext.create('Ext.grid.Panel', {
                      region: 'center',
                      frame: true,
                      id: 'grid1',
                      flex: 1,
                      viewConfig: {
                          markDirty: false
                      },
                      margin: '5 0 5 5',
                      title: '<%=GetGlobalResourceObject("CMSResource", "CodeRule")%>',
                      tbar: ['->',
                          {
                              xtype: 'combo',
                              id: 'totalLevel',
                              fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "TotalLevel")%>',
                              labelWidth: 50,
                              width: 100,
                              store: Ext.create('Ext.data.Store', {
                                  fields: ['abbr', 'name'],
                                  data: [
                                      { "abbr": "1", "name": "1" },
                                      { "abbr": "2", "name": "2" },
                                      { "abbr": "3", "name": "3" },
                                      { "abbr": "4", "name": "4" },
                                      { "abbr": "5", "name": "5" },
                                      { "abbr": "6", "name": "6" },
                                      { "abbr": "7", "name": "7" },
                                      { "abbr": "8", "name": "8" }
                                  ]
                              }),
                              queryMode: 'local',
                              displayField: 'name',
                              valueField: 'abbr',
                              editable: false,
                              value: 5,
                              listeners: {
                                  'change': function (combo, newValue, oldValue, eOpts) {
                                      if (loadFromServer)
                                          loadFromServer = false;
                                      else
                                          BuildGrid(newValue);
                                  }
                              }
                          },
                          '->'
                      ],
                      store: store,
                      columns: [
                          { xtype: 'rownumberer', header: '<%=GetGlobalResourceObject("CMSResource", "Level")%>', width: 50, align: 'center' },
                          {
                              header: '<%=GetGlobalResourceObject("CMSResource", "DisplayText")%>',
                              dataIndex: 'text',
                              flex: 1,
                              align: 'center',
                              sortable: false,
                              menuDisabled: true,
                              editor: {
                                  xtype: 'combo',
                                  store: Ext.create('Ext.data.Store', {
                                      fields: ['abbr', 'name'],
                                      data: [
                                          { "abbr": "-1", "name": "<%=GetGlobalResourceObject("CMSResource", "PleaseSelect")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Zone")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Zone")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Building")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Building")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Place")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Place")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Lane")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Lane")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Number")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Number")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Floor")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Floor")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Layer")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Layer")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Room")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Room")%>" },
                                          { "abbr": "<%=GetGlobalResourceObject("CMSResource", "Of")%>", "name": "<%=GetGlobalResourceObject("CMSResource", "Of")%>" }
                                      ]
                                  }),
                                  queryMode: 'local',
                                  displayField: 'name',
                                  valueField: 'abbr',
                                  listeners: {
                                      'change': function () {
                                          //                                          Preview();
                                      },
                                      'expand': function () {

                                          var text = new Array();
                                          store.each(function (record) {
                                              if (record.get("text") != '-1') {
                                                  text.push(record.get("text"));
                                              }
                                          });

                                          this.store.filterBy(function (record) {
                                              return text.indexOf(record.get("abbr")) < 0;
                                          });
                                      }
                                  }
                              },
                              renderer: function (value) {
                                  return value == "-1" ? "<font color=red><%=GetGlobalResourceObject("CMSResource", "PleaseSelect")%></font>" : value;
                              }
                          }, {
                              header: '<%=GetGlobalResourceObject("CMSResource", "Format")%>' + '&nbsp;<img src=/Common/DMZ/Images/16x16/Help.png />',
                              dataIndex: 'format',
                              tooltip: '<%=GetGlobalResourceObject("CMSResource", "RuleFormatAlt")%>',
                              flex: 1,
                              align: 'center',
                              sortable: false,
                              menuDisabled: true,
                              editor: {
                                  xtype: 'textfield',
                                  vtype: 'ruleFormat',
                                  allowBlank: false,
                                  listeners: {
                                      change: function (field, newValue, oldValue) {
                                          field.setValue(newValue.toUpperCase());
                                          formatChange = true;
                                      },
                                      'blur': function (field) {

                                      }
                                  }
                              }
                          },
                          {
                              header: '<%=GetGlobalResourceObject("CMSResource", "Length")%>',
                              dataIndex: 'length',
                              flex: 1,
                              align: 'center',
                              sortable: false,
                              menuDisabled: true
                              //                              ,
                              //                              editor: {
                              //                                  xtype: 'numberfield',
                              //                                  value: 1,
                              //                                  maxValue: 8,
                              //                                  minValue: 1,
                              //                                  listeners: {
                              //                                      'blur': function () {
                              //                                          //                                          Preview();
                              //                                      }
                              //                                  }
                              //                              }
                          }
                      ],
                      plugins: [
                          Ext.create('Ext.grid.plugin.CellEditing', {
                              clicksToEdit: 1,
                              listeners: {
                                  'edit': function (editor, e) {
                                      if (e.field == "format") {
                                          e.record.set("length", e.record.get("format").length);
                                          //alert(e.record.get("format").length);
                                      }
                                      //alert(e.record.get("format"));
                                  }
                              }
                          })
                      ],
                      bbar: [
                          {
                              xtype: 'tbtext',
                              id: 'CheckMsg'
                          },
                          '->',
                          {
                              text: '<%=GetGlobalResourceObject("CMSResource", "SaveSetting")%>',
                              id: 'SaveConfig',
                              disabled: true,
                              scale: 'medium',
                              icon: '/Common/DMZ/Images/24x24/floppy.png',
                              border: 1,
                              style: {
                                  borderColor: 'gray',
                                  borderStyle: 'solid'
                              },
                              handler: function () {
                                  var clearData = 0;
                                  if ((InitTotalLevel > 0 && InitTotalLevel != store.getCount()) || (InitTotalLevel > 0 && formatChange)) {
                                      if (!confirm("<%=GetGlobalResourceObject("CMSResource", "ChangeCodeRuleAlert")%>")) {
                                          return;
                                      }
                                      clearData = 1;
                                  }

                                  var saveData = "";
                                  store.each(function (record) {
                                      if (saveData != "") saveData = saveData + ",";
                                      saveData = saveData + record.get("text") + "#" + record.get("length") + "#" + record.get("format");
                                  });

                                  Ext.Ajax.request({
                                      url: 'Handler.ashx?action=SaveIDRule',
                                      params: {
                                          content: saveData,
                                          clearData: clearData
                                      },
                                      success: function (response) {
                                          var result = Ext.decode(response.responseText);
                                          if (result.success) {
                                              alert("<%=GetGlobalResourceObject("CMSResource", "CodeRuleSaveSuccess")%>");
                                          }
                                      }
                                  });


                              }
                          }
                      ]
                  })
              ]
          });

          if("<%=TargetSystem%>"=="0") Ext.Msg.alert("<%=GetGlobalResourceObject("CMSResource", "Attention")%>", "<%=GetGlobalResourceObject("CMSResource", "Note4N2")%>");

      });

      function BuildGrid(value) {
          var store = Ext.getCmp("grid1").store;
          store.removeAll();

          for (var i = 0; i < value; i++) {
              store.add({ text: '-1', length: 1, format:'0' });
          }
      }

      function getPerText(record,cnt) {
          var perText = "";

          console.log(record.get("format") + "==indexOf==" + record.get("format").indexOf("X"));

//          if (record.get("format").indexOf("X") > -1 && record.get("format").indexOf("0")==-1) {
//              //全英文字母
//              perText = record.get("format").replace(/\X/g, String.fromCharCode(96 + cnt).toUpperCase());
//          }
          //          else 
          
              if (record.get("format").indexOf("X") == -1 && record.get("format").indexOf("M") == -1 && record.get("format").indexOf("0") > -1) {
              //全數字
              var base = 1;
              switch (record.get("length")) {
              case 1:
                  base = 1;
                  break;
              case 2:
                  base = 10;
                  break;
              case 3:
                  base = 100;
                  break;
              case 4:
                  base = 1000;
                  break;
              case 5:
                  base = 10000;
                  break;
              case 6:
                  base = 100000;
                  break;
              case 7:
                  base = 1000000;
                  break;
              case 8:
                  base = 1000000;
                  break;
              }
              perText = cnt * base;
          }
          else {
              //英文字母+數字
              perText = record.get("format").replace(new RegExp("X", 'g'), String.fromCharCode(96 + cnt).toUpperCase()).replace(/\0/g, cnt);
              //perText = perText.replace(new RegExp("M", 'g'), String.fromCharCode(96 + cnt).toUpperCase()).replace(/\0/g, cnt);
              perText = perText.replace(new RegExp("M", 'g'), cnt);
              perText = perText.replace(new RegExp("0", 'g'), cnt);
          }

          return perText;
      }

      function getChild(level,desc) {
          var store = Ext.getCmp("grid1").store;
          var record = store.getAt(level);

          if (record) {
              var ctx = [];
              for (var i = 0; i < 2; i++) {
                  var text = record.get("text") == "<%=GetGlobalResourceObject("CMSResource", "Of")%>" ? record.get("text") + ' ' + getPerText(record, i + 1) : getPerText(record, i + 1) + ' ' + record.get("text");

                  ctx=ctx.concat([{
                      text: text,
                      desc: level == store.getCount() - 1 ? desc + ' ' + text :"<font color=gray>" + desc + ' ' + text + "</font>",
                      expanded: level != store.getCount()-1,
                      icon: level == store.getCount()-1 ? "/Common/DMZ/Images/16x16/home.png" : "",
                      children: getChild(level + 1, desc + ' ' + text)
                  }]);
              }
              return ctx;

          }
          else {
              return [];
          }
      }

      function Preview() {
          var store = Ext.getCmp("grid1").store;
          var tree = Ext.getCmp("tree1");
          
          var check_ok = true;

          store.each(function(record) {
              if (record.get("text") == "-1" || record.get("format") == "") {
                  check_ok = false;
              }

          });

          Ext.getCmp("SaveConfig").setDisabled(!check_ok);

          if (check_ok) {

              tree.getRootNode().removeAll();

              var text = "<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>";
              var rootNode = {
                  text: text,
                  expanded: true,
                  children: getChild(0, text)
              };

              tree.store.setRootNode(rootNode);
              

          } else {
              //設定不完全
              tree.getRootNode().removeAll();


          }

      }

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