Ext.namespace('Shipping');

Shipping.PiLiangBsEdit = function (config) {
    Ext.applyIf(this, config);
    this.initUIComponents();
    window.Shipping.PiLiangBsEdit.superclass.constructor.call(this);
};

Ext.extend(Shipping.PiLiangBsEdit, Ext.Panel, {
    PageSize: 15,
    ParentWin: null,
    OprationStatus: null, //仅当弹出界面时使用
    EditRecord: null,
    strbsno: '',

    initUIComponents: function () {
        //定义数据集
        this.storeList = Ext.create('Ext.data.Store', {
            model: 'MsOpStatus'
        });

        //客户加载_场站
        this.storeYARD = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CustomRefModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCustomRefList' }
        });
        this.storeYARD.load({ params: { condition: "ISYARD='1'"} });
        //船公司
        this.comboxYARD = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '场站',
            store: this.storeYARD,
            //            forceSelection: true,
            name: 'YARD',
            valueField: 'CustName',
            displayField: 'CodeAndName'
        });
        //客户加载_船公司
        this.storeCARRIER = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CustomRefModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCustomRefList' }
        });
        this.storeCARRIER.load({ params: { condition: "ISCARRIER='1'"} });
        //船公司
        this.comboxCARRIER = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '船公司',
            store: this.storeCARRIER,
            //           forceSelection: true,
            name: 'CARRIER',
            valueField: 'CustName',
            displayField: 'CodeAndName'
        });

        //客户加载_订舱代理
        this.storeFORWARDER = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CustomRefModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCustomRefList' }
        });
        this.storeFORWARDER.load({ params: { condition: "ISBOOKING='1'"} });
        //船公司
        this.comboxFORWARDER = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '订舱代理',
            store: this.storeFORWARDER,
            //            forceSelection: true,
            name: 'FORWARDER',
            valueField: 'CustName',
            displayField: 'CodeAndName'
        });

        //客户加载_车队
        this.storeTRUCKER = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CustomRefModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCustomRefList' }
        });
        this.storeTRUCKER.load({ params: { condition: "ISTRUCK='1'"} });
        //车队
        this.comboxTRUCKER = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '车队',
            store: this.storeTRUCKER,
            //            forceSelection: true,
            name: 'TRUCKER',
            valueField: 'CustName',
            displayField: 'CodeAndName'
        });

        //客户加载_报关报检
        this.storeCUSTOMSER = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CustomRefModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCustomRefList' }
        });
        this.storeCUSTOMSER.load({ params: { condition: "ISCUSTOM='1'"} });
        //报关行
        this.comboxCUSTOMSER = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '报关行',
            store: this.storeCUSTOMSER,
            //            forceSelection: true,
            name: 'CUSTOMSER',
            valueField: 'CustName',
            displayField: 'CodeAndName'
        });

        //箱型_集装箱列表中的下拉框加载
        this.storeLANE = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.Lane',
            proxy: { url: '/CommMng/BasicDataRef/GetCodeLaneList' }
        });
        this.storeLANE.load();
        this.comboxLANE = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '航线',
            store: this.storeLANE,
            //            forceSelection: true,
            name: 'LANE',
            valueField: 'LANE',
            displayField: 'LANE'
        });

        //国内港口(出口装货港、进口卸货港)
        this.storeCodeLoadport = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CodeLoadportModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCodeLoadportList' }
        });
        this.storeCodeLoadport.load();

        this.comboxPORTLOAD = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '装货港',
            store: this.storeCodeLoadport,
            name: 'PORTLOAD',
            valueField: 'PORT',
            displayField: 'CodeAndName',
            listeners: {
                scope: this,
                'select': function (combo, records, eOpts) {
                    if (records.length > 0) {
                        var selectrecords = DsStoreQueryBy(this.storeCodeLoadport, 'PORT', combo.value);
                        if (selectrecords.getCount() > 0) {
                            var selectdata = selectrecords.getAt(0).data;
                            this.formEdit.getForm().findField('PORTLOADID').setValue(selectdata.EDICODE);
                        } else {
                            this.formEdit.getForm().findField('PORTLOADID').setValue('');
                        }
                    }
                }
            }
        });
        this.storeCodeDisport = Ext.create('DsExt.ux.RefTableStore', {
            model: 'DsShipping.ux.CodeDisportModel',
            proxy: { url: '/CommMng/BasicDataRef/GetCodeDisportList' }
        });
        this.storeCodeDisport.load();

        this.comboxPORTDISCHARGE = Ext.create('DsExt.ux.RefTableCombox', {
            fieldLabel: '卸货港',
            store: this.storeCodeDisport,
            name: 'PORTDISCHARGE',
            valueField: 'PORT',
            queryMode: 'local',
            displayField: 'PORT',
            listeners: {
                scope: this,
                'select': function (combo, records, eOpts) {
                    if (records.length > 0) {
                        var selectrecords = DsStoreQueryBy(this.storeCodeDisport, 'PORT', combo.value);
                        if (selectrecords.getCount() > 0) {
                            var selectdata = selectrecords.getAt(0).data;
                            this.formEdit.getForm().findField('PORTDISCHARGEID').setValue(selectdata.EDICODE);
                        } else {
                            this.formEdit.getForm().findField('PORTDISCHARGEID').setValue('');
                        }
                    }
                }
            }
        });

        //#region 编辑formHead 基本信息
        this.formHead = Ext.widget('form', {
            region: 'north',
            frame: true,
            bodyPadding: 5,
            collapsed: false,
            collapsible: true,
            trackResetOnLoad: true,
            fieldDefaults: {
                margins: '2 2 2 2',
                labelAlign: 'right',
                flex: 1,
                labelWidth: 70,
                msgTarget: 'qtip'
            },

            items: [{
                xtype: 'container',
                layout: 'hbox',
                defaultType: 'textfield',
                items: [{
                xtype: 'container',
                layout: 'hbox',
                defaultType: 'textfield',
                items: [this.comboxYARD, this.comboxCARRIER, this.comboxFORWARDER, this.comboxLANE]
            }, {
                xtype: 'container',
                layout: 'hbox',
                defaultType: 'textfield',
                items: [this.comboxAgent, this.comboxCUSTOMSER,this.comboxPORTLOAD, this.comboxPORTDISCHARGE]
            }

            ]//end items(fieldset 1)

        }); //end this.formEdit 
        //#endregion


        this.gridListCellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        this.CheckBoxModel = Ext.create('Ext.selection.CheckboxModel');
        //定义Grid
        this.gridList = new Ext.grid.GridPanel({
            store: this.storeList,
            enableHdMenu: false,
            region: 'center',
            loadMask: { msg: "数据加载中,请稍等..." },
            trackMouseOver: true,
            disableSelection: false,
            plugins: [this.gridListCellEditing],
            selModel: this.CheckBoxModel,
            selType: 'cellmodel',
            columns: this.girdcolums,
            bbar: Ext.create('Ext.PagingToolbar', {
                store: this.storeList,
                displayInfo: true,
                displayMsg: '当前显示 {0} - {1}条记录 /共 {2}条记录',
                emptyMsg: "没有数据"
            })
        });


        this.storeBodyAddList = Ext.create('Ext.data.Store', {
            model: 'MsOpBill',
            remoteSort: true,
            proxy: {
                type: 'ajax',
                url: '/MvcShipping/MsOpBill/GetBLListData',
                reader: {
                    id: 'BSNO',
                    root: 'data',
                    totalProperty: 'totalCount'
                }
            }
        });

        //明细表表格


        this.gridAddList = new Ext.grid.GridPanel({
            store: this.storeBodyAddList,
            enableHdMenu: false,
            region: 'center',
            loadMask: { msg: "数据加载中,请稍等..." },
            trackMouseOver: true,
            disableSelection: false,
            columns: [{
                sortable: true,
                dataIndex: 'BSNO',
                header: 'BSNO',
                hidden: true,
                width: 100
            }, {
                sortable: true,
                dataIndex: 'OPLBNAME',
                header: '业务类别',
                width: 80
            }, {
                sortable: true,
                dataIndex: 'CUSTNO',
                header: '委托编号',
                width: 108
            }, {
                sortable: true,
                dataIndex: 'MBLNO',
                header: '主提单号',
                width: 108
            }, {
                sortable: true,
                dataIndex: 'CUSTOMERNAME',
                header: '委托单位',
                width: 100
            }, {
                sortable: true,
                dataIndex: 'ETD',
                header: '开船日期',
                renderer: Ext.util.Format.dateRenderer('Y-m-d'),
                width: 100
            }, {
                sortable: true,
                dataIndex: 'SALE',
                header: '揽货人',
                width: 80
            }, {
                sortable: true,
                dataIndex: 'ACCDATE',
                header: '会计期间',
                width: 80
            }, {
                sortable: true,
                dataIndex: 'OP',
                header: '操作',
                width: 80
            }, {
                sortable: true,
                dataIndex: 'INPUTBY',
                header: '录入人',
                width: 80
            }, {
                sortable: true,
                dataIndex: 'PORTLOAD',
                header: '起运港',
                width: 120
            }, {
                sortable: true,
                dataIndex: 'PORTDISCHARGE',
                header: '目的港',
                width: 120
            }, {
                sortable: true,
                dataIndex: 'VESSEL',
                header: '船名',
                width: 150
            }, {
                sortable: true,
                dataIndex: 'VOYNO',
                header: '航次',
                width: 60
            }
            ]
        });

        //#endregion

        //#region 按钮ToolBar
        this.panelBtn = new Ext.Panel({
            region: "north",
            tbar: [

                {
                    text: "新建",
                    iconCls: "btnadd",
                    handler: function (button, event) {
                        this.addDetail();
                    },
                    scope: this

                },
                {
                    text: "删除",
                    iconCls: "btndelete",
                    handler: function (button, event) {
                        this.deleteDetail();
                    },
                    scope: this
                },
                '-',

                {
                    text: "更新业务",
                    iconCls: "btnsave",
                    handler: function (button, event) {
                        this.onPostDetailClick(button, event);
                    },
                    scope: this
                }
            ]
        });


        //#endregion

        //#region 布局


        this.panelTop = new Ext.Panel({
            layout: "border",
            region: "north",
            height: 150,
            items: [this.panelBtn, this.gridList]
        });


        this.panelFee = new Ext.Panel({
            layout: "border",
            region: "center",
            items: [
                     this.gridAddList
            ]
        });

        Ext.apply(this, {
            items: [this.panelTop, this.panelFee]
        });
        //#endregion


        parentWin = window.parent.opener;
        this.InitData();

        //       this.SetBtnRight();

    }, //end initUIComponents

    InitData: function () {
        var condition = '';
        _this = this;
        if (parentWin) {
            var ret = parentWin.OprationSwap();
            _this.strbsno = ret[3];
            _this.storeBodyAddList.load({
                params: { start: 0, limit: 1000, sort: '', condition: _this.strbsno },
                waitMsg: "正在查询数据...",
                callback: function (r, options, success) {
                    if (success) {
                        var memdata = _this.storeBodyAddList.getAt(0);
                        var OPLBNAME = memdata.data.OPLBNAME;

                        _this.storeOpStatus.load({ params: { condition: "OPTYPE='" + OPLBNAME + "'"} });

                    }
                },
                scope: this
            });


        }


    },

    addDetail: function () {



        var newSerialno = DsGetNewSerialNo(this.storeList, 0);

        var n = this.storeList.getCount();

        var myDate = new Date();
        var mydatestr = Ext.util.Format.date(myDate, 'Y-m-d');

        var record = Ext.create('MsOpStatus', {
            ST_ID: NewGuid(),
            BSNO: '*',
            ORDNO: n + 1,
            STATUS: '',
            COMPTIME: mydatestr,
            COMPOP: SHOWNAME,
            REMARK: ''
        });

        this.storeList.add(record);

        var n = this.storeList.getCount();
        this.gridListCellEditing.startEditByPosition({ row: n - 1, column: 2 });
    },

    deleteDetail: function () {

        var selectedRecords = this.CheckBoxModel.selected.items;

        Ext.MessageBox.confirm('提示', '确定要删除选中的明细吗?', function (btn) {
            if (btn == 'yes') {

                var bodyDatas = [];
                for (var i = 0; i < selectedRecords.length; i++) {
                    var rec = selectedRecords[i];
                    if (rec.BSNO == "" || rec.BSNO == "*")  //如果是新增但没有保存的数据,没有必要提交到后台
                    {
                        this.storeList.remove(selectedRecords[i]);
                    } else {

                        bodyDatas.push(rec);
                    }
                }
                var jsonBody = ConvertRecordsToJsonAll(bodyDatas);
                _this = this;

                Ext.Msg.wait('正在删除数据...');

                Ext.Ajax.request({
                    waitMsg: '正在删除数据...',
                    url: '/MvcShipping/MsOpStatus/Delete',
                    params: {
                        bsno: _this.BsNo,
                        data: jsonBody
                    },
                    callback: function (options, success, response) {
                        if (success) {
                            var jsonresult = Ext.JSON.decode(response.responseText);
                            if (jsonresult.Success) {
                                for (var i = 0; i < selectedRecords.length; i++) {
                                    this.storeList.remove(selectedRecords[i]);
                                }

                                Ext.Msg.show({ title: '提示', msg: jsonresult.Message, icon: Ext.Msg.INFO, buttons: Ext.Msg.OK });
                            }
                            else {
                                Ext.Msg.show({ title: '错误', msg: jsonresult.Message, icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK });
                            }
                        }
                    },
                    failure: function (response, options) {
                        Ext.Msg.show({ title: '警告', msg: '服务器响应出错,请重试', icon: Ext.Msg.INFO, buttons: Ext.Msg.OK });
                    },
                    success: function (response, options) {
                    },
                    scope: this
                });   //end Ext.Ajax.request


            }
        }, this);

    },
    onPostDetailClick: function (button, event) {

        var bodyDrChFeeDatas = [];
        var i;
        var bodyBillDatas = [];

        for (i = 0; i < this.storeList.getCount(); i += 1) {
            var memberyf = this.storeList.getAt(i);
            bodyDrChFeeDatas.push(memberyf);

            var STATUS = memberyf.data.STATUS;

            if (STATUS == '') {
                Ext.Msg.show({ title: '警告',
                    msg: '状态不能为空,请修改后再保存',
                    icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK
                });

                return;
            }

        };

        for (i = 0; i < this.storeBodyAddList.getCount(); i += 1) {
            var memberyf = this.storeBodyAddList.getAt(i);
            bodyBillDatas.push(memberyf);
        };

        var jsonChFeeBody = ConvertFeeRecordsToJson(bodyDrChFeeDatas);
        var jsonbodyBill = ConvertRecordsToJsonAll(bodyBillDatas);


        _this = this;
        Ext.Msg.wait('正在保存数据, 请稍侯..');
        Ext.Ajax.request({
            waitMsg: '正在保存数据...',
            url: '/MvcShipping/MsOpStatus/PiliangSave',
            scope: this,
            params: {
                bill: jsonbodyBill,
                body: jsonChFeeBody
            },
            callback: function (options, success, response) {
                if (success) {
                    Ext.MessageBox.hide();
                    var jsonresult = Ext.JSON.decode(response.responseText);
                    if (jsonresult.Success) {
                        for (var i = 0; i < this.storeList.getCount(); i += 1) {
                            var member = this.storeList.getAt(i);
                            member.commit();
                        }

                    } else {
                        Ext.Msg.show({ title: '错误', msg: jsonresult.Message, icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK });
                    }
                } else {
                    Ext.Msg.show({ title: '请重试',
                        msg: '服务器响应出错',
                        icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK
                    });
                }
            }
        });
    }

});