/**
 * 定义命名空间
 */
Ext.namespace("Ext.darkness");

/*
 *CRUD面板基类,继承自EXT的Panel
 */
Ext.darkness.CrudPanel = Ext.extend(Ext.Panel, {
    
    /**
      *基本属性
      */
    gridPanel:null,
    gridPanelId: 'gridPanel' + this.ID,
    gridViewConfig: {},
    cm: new Ext.grid.CheckboxSelectionModel(),
    sm: new Ext.grid.CheckboxSelectionModel({
		dataIndex: this.ID
	}),//-列选择模式
    store: null,
    storeMapping: null,
    pageSize: null,
    
    keywordText: null,
    
    baseUrl: null,
    
    width: 800,
    height: 600,
 
 
    //构造器
    constructor: function(config){
        
        config = config || {};
        this.pageSize = config.pageSize || 10;
        
        this.keywordText = new Ext.form.TextField({
            name: 'keyword',
            anchor: '95%',
            maxLength: 25
        });
        
        var flag = this.store == null;
        if(flag){
            this.store = new Ext.data.JsonStore({
                id: this.ID,
                url: this.baseUrl + '?cmd=List',//默认的数据源地址，继承时需要提供
                root: "data",
                totalProperty: "totalCount",
                remoteSort: true,
                fields: this.storeMapping
            });
        } 
        
        this.cm.defaultSortable = true;
        
        var viewConfig = Ext.apply({
            forceFit: true
        }, this.gridViewConfig);
        
        this.gridPanel = new Ext.grid.GridPanel({
            id: Ext.id(),
            store: this.store,
            cm: this.cm,
            sm: this.sm,
            trackMouseOver: false,
            loadMask: true,
            //超过长度带自动滚动条
		    autoScroll:true,
		    border:false,
		    collapsible: true,
            animCollapse: false,
            viewConfig: viewConfig,
            listeners: {
                'celldblclick': {//双击时执行修改
                    fn: this.onEdit,
                    scope: this
                },
                'contextmenu':function(e) {
                    e.stopEvent();
                }
            },
            tbar: [{
                id: 'addButton',
                text: '添加',
                iconCls: 'addicon',
                tooltip: '添加新纪录',
                handler: this.create,
                scope: this
            }, '-',//'-'给工具栏按钮之间添加'|'
            {
                id: 'editButton',
                text: '编辑',
                iconCls: 'editicon',
                tooltip: '修改记录',
                handler: this.onEdit,
                scope: this
            }, '-', {
                text: '删除',
                iconCls: 'deleteicon',
                tooltip: '删除所选中的信息',
                handler: this.onRemove,
                scope: this
            }, '-', {
                text: '刷新',
                iconCls: 'refreshicon',
                tooltip: '刷新纪录',
                handler: this.onRefresh,
                scope: this
            }, '->',//'->'代表让工具栏按钮到右边去
            'Search: ', this.keywordText, {
                text: '查询',
                pressed: true,
                iconCls: 'serchopenroomrecord',
                handler: this.onSearch,
                scope: this
            }, '   '],
            //分页
            bbar: new Ext.PagingToolbar({
                pageSize: this.pageSize,
                store: this.store
            })
        });
        
        //this.gridPanel.bbar = null;
        
        if(this.view){
            Ext.apply(this.gridPanel,{
                view: this.view
            });
        }
        
        this.store.load({
            params: {
                start: 0,
                limit: this.pageSize
            }
        });
        
        var configs = Ext.apply({
            closable: true,
            autoScroll: true,
            layout: "fit",
            items:[this.gridPanel],
            /**
              *渲染数据
              */
            //链接
            linkRenderer: function(v){
                if (!v) 
                    return "";
                else 
                    return String.format("<a href='{0}' target='_blank'>{0}</a>", v);
            },
            //时间
            dateRender: function(format){
                format = format || "Y-m-d h:i";
                return Ext.util.Format.dateRenderer(format);
            }
        },config);
        
        //调用父类的构造器
        Ext.darkness.CrudPanel.superclass.constructor.call(this,configs);
    },
       
       
    /**
      *事件
      */
    //查询
    onSearch: function(){
        var keyword = this.keywordText.getValue();//得到输入框的值
        this.store.load({
            params: {
                start: 0,
                limit: 10,
                keyword: keyword
            }
        });
    },
    //刷新
    onRefresh: function(){
        this.store.removeAll();
        this.store.reload();
    },
    //初始化窗口（用于新增，修改时）,继承后在createWin中调用该方法显示窗口
    initWin: function(width, height, status){
        var win = new Ext.Window({
            title: "信息（" + status + "）",
            width: width,
            height: height,
            modal: true,
            shadow: true,
			iconCls:"addicon",
			//不可以随意改变大小
			resizable:false,
			//是否可以拖动
			//draggable:false,
			defaultType:"textfield",
			labelWidth:100,
			collapsible:true, //允许缩放条
            closeAction : 'hide',
            closable:true,
            plain : true,
            //弹出模态窗体
			modal: 'true', 
			buttonAlign:"center",
			bodyStyle:"padding:10px 0 0 15px",
			/*
			listeners:{
			    "show":function() {
			        //当window show事件发生时清空一下表单
			        //this.fp.getForm().loadRecord(row);
			    }
			},*/

            items: [this.fp],
            buttons: [{
                text: "保存",
                handler: this.onSave,
                scope: this
            }, {
                text: "清空",
                handler: this.reset,
                scope: this
            }, {
                text: "关闭",
                handler: this.closeWin,
                scope: this
            }]
        });
        return win;
    },
    
    //显示（新增/修改）窗口
    showWin: function(status){ //createForm()需要在继承时提供，该方法作用是创建表单
        if (!this.win) {
            if (!this.fp) {
                this.fp = this.createForm();
            }
            this.win = this.createWin(status);
            this.win.on("close", function(){
                this.win = null;
                this.fp = null;
                this.store.reload();
            }, this);
        }
        //窗口关闭时，数据重新加载
        this.win.show();
    },
    //创建（新增/修改）窗口
    create: function(){
        this.showWin("Save");
        this.reset();
    },
    
    //数据保存[（新增/修改）窗口]
    onSave: function(){
        var id = this.fp.form.findField("Id").getValue();
        // if(EditTeacherInfofp.getForm().isValid())
        this.fp.form.submit({
            waitMsg: '正在保存。。。',
            url: this.baseUrl + "?cmd=" + (id ? "Update" : "Save"),
            method: 'POST',
            success: function(){
                this.closeWin();
                this.store.reload();
            },
            failure:function(form,action) {
                Ext.MessageBox.alert("提示!","信息操作失败!");
            },
            scope: this
        });
    },
    //（新增/修改）窗口上的清空
    reset: function(){
        if (this.win) 
            this.fp.form.reset();
    },
    //（新增/修改）窗口上的关闭
    closeWin: function(){
        if (this.win) 
            this.win.close();
        this.win = null;
        this.fp = null;
        this.store.reload();
    },
    //修改，双击行，或选中一行点击修改，
    onEdit: function(){
        if (this.gridPanel.selModel.hasSelection()) {
            var records = this.gridPanel.selModel.getSelections();//得到被选择的行的数组
            var recordsLen = records.length;//得到行数组的长度
            if (recordsLen > 1) {
                Ext.Msg.alert("系统提示信息", "请选择其中一项进行编辑！");
            }//一次只给编辑一行
            else {
                var record = this.gridPanel.getSelectionModel().getSelected();//获取选择的记录集
                //var id = record.get("id");
                this.showWin("Update");
                this.fp.form.loadRecord(record); //往表单（fp.form）加载数据
            }
        }
        else {
            Ext.Msg.alert("提示", "请先选择要编辑的行!");
        }
    },
    //删除,deleteIds为主键值
    onRemove: function(){
        var store = this.store;
        var baseUrl = this.baseUrl;
        if (this.gridPanel.selModel.hasSelection()) {
            var records = this.gridPanel.selModel.getSelections();//得到被选择的行的数组
            var recordsLen = records.length;//得到行数组的长度
            var deleteIds = "";
            for (var i = 0; i < recordsLen; i++) {
                var id = records[i].get(this.ID);
                if (i != 0) {
                    deleteIds += "," + id;
                }
                else {
                    deleteIds = id;
                }
            }
            
            //this.store.reload();这里能执行
            Ext.MessageBox.confirm('系统提示信息', '确定要删除所选的记录吗?', function(btn){
                if (btn == 'yes') {
                    var myCon = new Ext.data.Connection();
                    Ext.MessageBox.wait('正在删除数据中, 请稍候……'); //出现一个等待条
                    myCon.request({
                        url: baseUrl + '?cmd=Remove',
                        method: "POST",
                        params: {
                            'deleteIds': deleteIds
                        },
                        //callback : Function (Optional) options, success : Boolean ,response : Object 
                        callback: function(options, success, response){
                            Ext.MessageBox.hide();
                            if (success) {
                                Ext.Msg.alert("提示信息", "成功删除数据!", function(){
                                    store.reload();
                                }, this);
                            }
                            else {
                                Ext.MessageBox.alert("系统提示信息", "异步通讯失败,更新失败,请与管理员联系！");
                            }
                        }
                    }, this);
                }//if..yes
            }, this);
        }
        else {
            Ext.Msg.alert("提示", "请先选择要删除的行!");
        }
    }
});
