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

<!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">
    Ext.apply(Ext.data.SortTypes, {
        asNatural: function (str) {
            // Pad all the numbers we can find with 10 zeros to the left, then trim
            // down to the last 10 digits. A primitive natural sort occurs.
            // WARN: May do odd things to any numbers longer than 10 digits. It will
            // also not work as you might expect on decimals.
            return str.replace(/(\d+)/g, "0000000000$1").replace(/0*(\d{10,})/g, "$1");
        }
    });

    var unitList = "<%=unitList %>";
    var totalLevel = unitList.split("@").length;
    var tree2;
    Ext.onReady(function () {

        Ext.QuickTips.init();

        tree2 = Ext.create('Ext.tree.Panel', {
            region: 'center',
            //title: '【社區結構】',
            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'
                ],
                proxy: {
                    type: 'ajax',
                    url: 'Handler.ashx?action=GetStructureTree_Temp'
                },
                root: {
                    text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                    id: '<%=rootIdent %>'
                    //                    expanded: true,
                    //                    children: []
                },
                sorters: [{ property: 'text', direction: 'ASC' }],
                folderSort: true
            }),
            //              useArrows: true,
            //                    rootVisible: false,
            multiSelect: false,
            singleExpand: false,

            viewConfig: {
                stripeRows: true,
                markDirty: false
            },

            sortableColumns: false,
            sorters: [{
                property: 'text',
                direction: 'ASC'
            }],

            tbar: [
                {
                    xtype: 'tbtext',
                    text: '【<%=GetGlobalResourceObject("CMSResource", "CommunityStructure")%>】'
                },
                '->',
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "NewUnit")%>',
                    id: 'AddUnit',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    //                            icon: '/Common/DMZ/Images/16x16/find.png',
                    handler: function () {
                        var node = tree2.getSelectionModel().getLastSelected();

                        editUnit(node, null);


                    }
                }, {
                    text: '<%=GetGlobalResourceObject("CMSResource", "BatchNewUnit")%>',
                    id: 'AddUnit1',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    //                            icon: '/Common/DMZ/Images/16x16/find.png',
                    handler: function () {
                        var node = tree2.getSelectionModel().getLastSelected();

                        Ext.create('Ext.window.Window', {
                            //title: "整批新增【" + getName(node) + "】單元",
                            title: String.format('<%=GetGlobalResourceObject("CMSResource", "BatchNewUnit")%>', getName(node)),
                            width: 250,
                            constrain: true,
                            shadow: true,
                            shadowOffset: 50,
                            layout: 'fit',
                            modal: true,
                            items: [
                                {
                                    xtype: 'form',
                                    bodyPadding: 5,
                                    layout: 'anchor',
                                    defaultType: 'textfield',
                                    defaults: {
                                        anchor: '100%'
                                    },
                                    border: false,
                                    items: [
                                        {
                                            xtype: 'numberfield',
                                            fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "StartCode")%>',
                                            name: 'startID',
                                            value: 1,
                                            allowBlank: false
                                        },
                                        {
                                            xtype: 'numberfield',
                                            fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "Count")%>',
                                            name: 'count',
                                            value: 1,
                                            allowBlank: false
                                        }, {
                                            xtype: 'combo',
                                            fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "Interval")%>',
                                            name: 'interval',
                                            store: Ext.create('Ext.data.Store', {
                                                fields: ['abbr', 'name'],
                                                data: [
                                                    { "abbr": "0", "name": "0" },
                                                    { "abbr": "1", "name": "1" }
                                                ]
                                            }),
                                            queryMode: 'local',
                                            displayField: 'name',
                                            valueField: 'abbr',
                                            value: 0
                                        }
                                    ],
                                    buttons: [
                                        {
                                            text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                            handler: function () {
                                                var startID = this.up("form").getForm().findField("startID").getValue();
                                                var count = this.up("form").getForm().findField("count").getValue();
                                                var interval = this.up("form").getForm().findField("interval").getValue();

                                                var text = parseInt(startID);
                                                var length = getNextLength(node);

                                                var list = "";

                                                for (var i = 0; i < count; i++) {
                                                    //Check Rule

                                                    var displayText = padLeft(text.toString(), parseInt(length));


                                                    if (displayText.toString().length <= length) {

                                                        var id = 'TEMP' + i;

                                                        //查核是否有一樣資料
                                                        var pass = true;
                                                        node.cascade(function (n) {
                                                            if (n.get("realId") == displayText && node != n) {
                                                                pass = false;
                                                                return false;
                                                            }
                                                        });

                                                        if (pass) {
                                                            var cn = node.appendChild({
                                                                id: id,
                                                                realId: displayText,
                                                                text: getName(node) == "<%=GetGlobalResourceObject("CMSResource", "Of")%>" ? getName(node) + ' ' + displayText : displayText + ' ' + getName(node),
                                                                expanded: true,
                                                                children: []
                                                            });

                                                            if (list.length > 0) list = list + "@";
                                                            list = list + id + "," + displayText;
                                                        }



                                                        node.expand();

                                                        text = text + parseInt(interval) + 1;
                                                    }


                                                }

                                                if (list.length > 0) {
                                                    //AJAX-新增
                                                    Ext.Ajax.request({
                                                        url: 'Handler.ashx?action=StructureTreeEditNode',
                                                        params: {
                                                            edit: "ADD",
                                                            multi: 1,
                                                            text: list,
                                                            parentId: node.get("id"),
                                                            level: node.getDepth() + 1,
                                                            isLeaf: node.getDepth() + 1 == totalLevel ? 1 : 0
                                                        },
                                                        success: function (response) {
                                                            
                                                            var result = Ext.decode(response.responseText);
                                                            if (!result.success) {
                                                                alert(result.msg);
                                                            }
                                                            else {
                                                                var resultListarray = result.list.split("@");
                                                                var item, n;
                                                                if (result.success) {

                                                                    for (var k = 0; k < resultListarray.length; k++) {
                                                                        n = tree2.getStore().getNodeById(resultListarray[k].split(",")[0]);
                                                                        n.set("id", resultListarray[k].split(",")[1]);
                                                                    }
                                                                    Ext.getCmp("SaveButton").setDisabled(false);
                                                                }
                                                                else {


                                                                    for (var k = 0; k < resultListarray.length; k++) {
                                                                        n = tree2.getStore().getNodeById(resultListarray[k].split(",")[0]);
                                                                        n.remove();
                                                                    }
                                                                    alert(result.msg);
                                                                }



                                                                //tree2.getStore().sort("text", "ASC");
                                                            }

                                                        }
                                                    });
                                                }


                                                //                                                tree2.store.sort('value', 'ASC');
                                                this.up("window").close();
                                            }
                                        },
                                        {
                                            text: '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                                            handler: function () {
                                                this.up("window").close();
                                            }
                                        }
                                    ]
                                }
                            ]
                        }).show();
                    }
                }
            ],
            columns: [{
                xtype: 'treecolumn',
                text: '',
                flex: 1,
                sortable: false,
                dataIndex: 'text',
                menuDisabled: true
            }, {
                text: '<%=GetGlobalResourceObject("CMSResource", "Description")%>',
                flex: 1,
                dataIndex: 'note',
                hidden: false,
                sortable: false,
                menuDisabled: true
            }, {
                xtype: 'actioncolumn',
                hideable: false,
                width: 30,
                sortable: false,
                menuDisabled: true,
                align: 'center',
                items: [{
                    icon: '/Common/DMZ/Images/16x16/edit.png',
                    tooltip: '<%=GetGlobalResourceObject("CMSResource", "Eidt")%>',
                    scope: this,
                    handler: function (view, rowIndex, colIndex, item, e, record, row) {
                        var node = tree2.getStore().getNodeById(record.get("id"));

                        editUnit(node.parentNode, node);
                    },
                    isDisabled: function (view, rowIndex, colIndex, item, record) {
                        return rowIndex == 0;
                    }
                }]
            }, {
                xtype: 'actioncolumn',
                width: 30,
                sortable: false,
                menuDisabled: true,
                align: 'center',
                items: [{
                    icon: '/Common/DMZ/Images/16x16/delete.png',
                    tooltip: '<%=GetGlobalResourceObject("CMSResource", "Remove")%>',
                    scope: this,
                    handler: function (view, rowIndex, colIndex, item, e, record, row) {

                        //AJAX-刪除
                        Ext.Ajax.request({
                            url: 'Handler.ashx?action=StructureTreeEditNode',
                            params: {
                                edit: "DEL",
                                id: record.get("id")
                            },
                            success: function (response) {
                                var result = Ext.decode(response.responseText);
                                if (result.success) {
                                    var node = tree2.getStore().getNodeById(record.get("id"));
                                    var parentNode = node.parentNode;

                                    node.remove();

                                    tree2.fireEvent('itemclick', tree2, parentNode);

                                    Ext.getCmp("SaveButton").setDisabled(false);
                                }
                                else {

                                }
                            }
                        });
                    },
                    isDisabled: function (view, rowIndex, colIndex, item, record) {
                        return rowIndex == 0;
                    }
                }]
            }],
            buttons: [
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "SaveSetting")%>',
                    id: 'SaveButton',
                    disabled: true,
                    scale: 'medium',
                    icon: '/Common/DMZ/Images/24x24/floppy.png',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    handler: function () {
                        Ext.Ajax.request({
                            url: 'Handler.ashx?action=SaveStructureTree',
                            success: function (response) {
                                var result = Ext.decode(response.responseText);
                                if (result.success) {
                                    Ext.Ajax.request({
                                        url: 'Handler.ashx?action=SyncStructure2Account'
                                    });

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

                                    Ext.getCmp("SaveButton").setDisabled(true);
                                }
                                else {
                                    alert("<%=GetGlobalResourceObject("CMSResource", "SaveFail")%>");
                                }
                            }
                        });
                    }
                }
            ],
            listeners: {
                //'afteritemexpand': function () {
                //    tree2.getStore().sort("text", "ASC");
                //},
                'itemappend': function (n, node, index, eOpts) {

                    var note = getParentName(node) + " " + processInt(node.get("text").split(" ")[0]) + " " + node.get("text").split(" ")[1];
                    if (totalLevel == node.getDepth()) {
                        node.set("icon", "/Common/DMZ/Images/16x16/home.png");
                    }
                    else {
                        note = "<font color=gray>" + note + "</font>";
                    }
                    node.set("note", note);

                },
                //                'beforeitemappend': function (n, node, eOpts) {
                //                    if (tree2.getStore().getNodeById(node.get("id"))) {
                //                        return false;
                //                    }
                //                },
                'beforeitemclick': function (tree, record, item, index, e, eOpts) {
                    try {
                        var colIdx = e.getTarget('.x-grid-cell').cellIndex;

                        if (colIdx == 3) return false;
                    } catch (e) {

                    }
                },
                'itemclick': function (tree, record, item, index, e, eOpts) {

                    tree2.getSelectionModel().select(record);

                    var name = getName(record);

                    var AddUnit = Ext.getCmp("AddUnit");
                    var AddUnit1 = Ext.getCmp("AddUnit1");
                    if (name == "") {
                        AddUnit.hide();
                        AddUnit1.hide();
                    } else {
                        AddUnit.show();
                        AddUnit.setText(String.format('<%=GetGlobalResourceObject("CMSResource", "NewUnit")%>', name));

                        if (getNextIsNumber(record) == "Y") {
                            AddUnit1.show();
                            AddUnit1.setText(String.format('<%=GetGlobalResourceObject("CMSResource", "BatchNewUnit")%>', name));
                        }
                        else {
                            AddUnit1.hide();
                        }
                    }

                }
            }
        });

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


        tree2.fireEvent('itemclick', tree2, tree2.getRootNode());

        function getNextFormat(record) {
            var Depth = record.getDepth();
            try {
                return unitList.split("@")[Depth].split(",")[3];
            } catch (e) {

            }
            return "";
        }

        function getName(record) {
            var Depth = record.getDepth();
            var unit = "";

            try {
                unit = unitList.split("@")[Depth].split(",")[0];
            } catch (e) {

            }
            return unit;
        }

        function getIsNumber(record) {
            var Depth = record.getDepth() - 1;
            try {
                return unitList.split("@")[Depth].split(",")[1];
            } catch (e) {

            }
            return "";
        }

        function getNextIsNumber(record) {
            var Depth = record.getDepth();
            try {
                return unitList.split("@")[Depth].split(",")[1];
            } catch (e) {

            }
            return "";
        }

        function getLength(record) {
            var Depth = record.getDepth() - 1;
            try {
                return unitList.split("@")[Depth].split(",")[2];
            } catch (e) {

            }
            return 0;
        }

        function getNextLength(record) {
            var Depth = record.getDepth();
            try {
                return unitList.split("@")[Depth].split(",")[2];
            } catch (e) {

            }
            return 0;
        }

        function getParentName(node) {
            var parentNode = node.parentNode;
            var names = "";
            if (parentNode) {
                if(parentNode.get("text").split(" ").length==2)
                    names = getParentName(parentNode) + " " + (processInt(parentNode.get("text").split(" ")[0]) + " " + parentNode.get("text").split(" ")[1]);
                else
                    names = getParentName(parentNode) + " " + (processInt(parentNode.get("text").split(" ")[0]));
            }
            return names;

        }

        function processInt(str) {
            if (isNaN(parseInt(str))) {
                return str;
            }
            else {
                return parseInt(str);
            }
        }

        function editUnit(node, editNode) {

            if (getNextIsNumber(node) == "Y") {
                eval("var validRule = /^[0-9]+$/;");
            }
            else {
                eval("var validRule = /^" + getNextFormat(node).replace(new RegExp("0", 'g'), "[0-9]").replace(new RegExp("X", 'g'), "[A-J]").replace(new RegExp("M", 'g'), "[A-J,0-9]") + "+$/;");
            }

            console.log("validRule=" + validRule);
            Ext.apply(Ext.form.field.VTypes, {
                ruleFormat: function (val, field) {
                    return validRule.test(val);
                },
                //ruleFormatText: "輸入格式：【" + getNextFormat(node) + "】。0 代表數字、X 代表英文字母、M 代表數字或英文字母"
                ruleFormatText: String.format('<%=GetGlobalResourceObject("CMSResource", "InputFormatAlt")%>', getNextFormat(node))
            });

            Ext.create('Ext.window.Window', {
                title:String.format('<%=GetGlobalResourceObject("CMSResource", "NewUnit")%>', getName(node)),
                width: 250,
                constrain: true,
                shadow: true,
                shadowOffset: 50,
                layout: 'fit',
                modal: true,
                items: [
                    {
                        xtype: 'form',
                        bodyPadding: 5,
                        layout: 'anchor',
                        defaultType: 'textfield',
                        defaults: {
                            anchor: '100%'
                        },
                        border: false,
                        items: [
                            {
                                fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "UnitCode")%>',
                                id: 'UnitID',
                                maxLength: editNode == null ? getNextLength(node) : getLength(editNode),
                                vtype: 'ruleFormat',
                                //vtype: editNode == null ? (getNextIsNumber(node) == "Y" ? "alphanum" : "alpha") : (getIsNumber(editNode) == "Y" ? "alphanum" : "alpha"),
                                allowBlank: false,
                                value: editNode == null ? "" : editNode.get("realId"),
                                listeners: {
                                    change: function (field, newValue, oldValue) {
                                        field.setValue(newValue.toUpperCase());
                                    }
                                }
                            }
                        ],
                        buttons: [
                            {
                                text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                                formBind: true,
                                handler: function () {
                                    var text = this.up("window").down("textfield").getValue();


                                    if (editNode == null) {
                                        //新增
                                        text = padLeft(text.toString(), parseInt(getNextLength(node)));

                                        //查核是否有一樣資料
                                        var pass = true;
                                        node.cascade(function (n) {
                                            if (n.get("realId") == text && node != n) {
                                                pass = false;
                                                return false;
                                            }
                                        });

                                        if (!pass) {
                                            this.up("window").close();
                                            return;
                                        }


                                        var cn = node.appendChild({
                                            realId: text,
                                            text: getName(node) == "<%=GetGlobalResourceObject("CMSResource", "Of")%>" ? getName(node) + ' ' + text : text + ' ' + getName(node),
                                            expanded: true,
                                            children: []
                                        });

                                        node.expand();

                                        //AJAX-新增
                                        Ext.Ajax.request({
                                            url: 'Handler.ashx?action=StructureTreeEditNode',
                                            params: {
                                                edit: "ADD",
                                                multi:0,
                                                text: cn.get("realId"),
                                                parentId: node.get("id"),
                                                level: cn.getDepth(),
                                                isLeaf: cn.getDepth() == totalLevel ? 1 : 0
                                            },
                                            success: function (response) {
                                                var result = Ext.decode(response.responseText);
                                                if (result.success) {
                                                    cn.set("id", result.id);

                                                    Ext.getCmp("SaveButton").setDisabled(false);
                                                }
                                                else {
                                                    cn.remove();
                                                    alert(result.msg);
                                                }

                                                //tree2.getStore().sort("text", "ASC");
                                            }
                                        });


                                    }
                                    else {
                                        //編輯

                                        var realId = padLeft(text.toString(), parseInt(getLength(editNode)));
                                        var text = getName(node) == "<%=GetGlobalResourceObject("CMSResource", "Of")%>" ? getName(node) + ' ' + text : text + ' ' + getName(node);

                                        //AJAX-修改
                                        Ext.Ajax.request({
                                            url: 'Handler.ashx?action=StructureTreeEditNode',
                                            params: {
                                                edit: "MODIFY",
                                                text: realId,
                                                id: editNode.get("id")
                                            },
                                            success: function (response) {
                                                var result = Ext.decode(response.responseText);
                                                if (result.success) {

                                                    editNode.set("realId", realId);
                                                    editNode.set("text", text);

                                                    //tree2.getStore().sort("text", "ASC");

                                                    //改變描述..本身以及所有子節點

                                                    editNode.cascadeBy(function (node) {
                                                        var note = getParentName(node) + " " + node.get("text");
                                                        node.set("note", note);
                                                    });

                                                    Ext.getCmp("SaveButton").setDisabled(false);
                                                }
                                                else {

                                                }
                                            }
                                        });
                                    }

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

            Ext.getCmp('UnitID').focus(false, 200);
        }

        //Ext.EventManager.on(window, 'beforeunload', function () {
        //    if (!Ext.getCmp("SaveButton").isDisabled()) {
        //        return "社區結構尚未儲存！";
        //    }
        //});


    });

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

    }

    function padLeft(str, len) {
        if (str.length >= len) return str;
        else return padLeft("0" + str,len);
    }
</script>
<body>
    <form id="form1" runat="server">
    <div style="margin: 5">
    
    </div>
    </form>
</body>
</html>
