var gridManager = null;

$(document).ready(function () {
    initialize();
    loadGrid();
    bindEvent();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
}

function bindEvent(){
    $('#customerName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "KUNNR"}
        },
        onChange: function (value, data) {
            $('#customerCode').val(data.KUNNR);
            $('#customerName').val(data.NAME);
        }
    });
}

function loadGrid() {
    var toolbarOptions =null;
       toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            // UICtrl.addGridRow(gridManager,{
            //     itemNo: (gridManager.getData().length + 1)
            // });
            UICtrl.showAjaxDialog({
                title: '详情',
                height: 400,
                width: 1500,
                url: web_app.name + '/cashSettlementUnPayItem/showReceiptNoDetail.load?customerCode='+$('#customerCode').val(),
                ok: function(d){
                    var _self = this;
                    var rows = detailGridManager.getSelectedRows();
                    for (var i = 0 ;i<rows.length;i++){
                        var row = rows[i];
                        var newRow = JSON.parse(JSON.stringify(row));
                        UICtrl.addGridRow(gridManager, newRow);
                    }
                    _self.close();
                },
            });
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'cashSettlementUnPayItem/deleteCashSettlementUnPayItems.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        },
     });
    gridManager = UICtrl.grid("#maingrid", {
        columns: [
            { display: "收款状态", name: "payStatus", width: 100, minWidth: 60, type: "string", align: "left",},
            {display: "预收单号", name: "advanceReceiptNo", width: 150, minWidth: 60, type: "String", align: "left",
                render: function (item) {
                    var html = [];
                    html.push('<a class="viewDetail" href="javascript:void(0);"');
                    html.push(' data-id="', item.id, '"');
                    html.push(' data-code="', item.advanceReceiptNo, '">');
                    html.push(item.advanceReceiptNo);
                    html.push('</a>');
                    return html.join('');
                }
            },
            { display: "实际应收金额", name: "realAmount", width: 140, minWidth: 60, type: "string", align: "left",
                editor: {  type: "text",mask: 'nnnnnnnnn.nn',required: true }
            },
            {display: "项次", name: "detailNo", width: 60, minWidth: 60, type: "String", align: "left",},
            {display: "销售单号", name: "saleNo", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "销售项次", name: "saleDetailNo", width: 60, minWidth: 60, type: "String", align: "left",},
            {display: "订单类型", name: "orderType", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "验收日期", name: "acceptDate", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "验收单号", name: "acceptNo", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "审核销售订单日", name: "auditDate", width: 140, minWidth: 60, type: "string", align: "left",},
            {display: "客户单号", name: "customNo", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "产品类别", name: "productCategory", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "产品编码", name: "productCode", width: 100, minWidth: 60, type: "String", align: "left",
                //去掉前导零
                render: function (item) {
                    var code = item.productCode;
                    if (code) {
                        return code.replace(/^0+/, '');
                    }
                    return code;
                }},
            {display: "产品名称", name: "productName", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "指令号", name: "orderNo", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "型体配色", name: "color", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "单位（客户）", name: "customUnit", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "请款量", name: "applyNum", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "单价", name: "price", width: 100, minWidth: 60, type: "String", align: "left",},
            //{display: "是否客户确认单价", name: "customerConfirm", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "单重", name: "onePrice", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "实际金额", name: "realAmount", width: 100, minWidth: 60, type: "String", align: "left",},
            //{display: "应收金额", name: "receivableAmount", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "请款重量", name: "applyWeight", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "备注", name: "remark", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "单价折扣%", name: "priceDiscount", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "单价折后金额", name: "priceDiscountAmount", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "是否扣款%", name: "isDeduction", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "是否增款%", name: "isAdd", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "产品编码（客户）", name: "customerProductCode", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "产品名称（客户）", name: "customerProductName", width: 100, minWidth: 60, type: "String", align: "left",},
            {display: "跟单员", name: "salesman", width: 100, minWidth: 60, type: "String", align: "left",},
        ],
        /*columns: [
            {display: "", name: "id", width: 60, align: "left", type: "string",hide: true},
            {display: "项次", name: "itemNo", width: 60, align: "left", type: "string",},
            { display: "收款状态", name: "payStatus", width: 100, minWidth: 200, type: "string", align: "left",},
            {
                display: "预收单号", name: "advanceReceiptNo", width: 160, align: "left", type: "string",
                editor: {
                    required: true,
                    type: "text",
                }
                // editor: {
                //     required: true, type: "select",
                //     data: {
                //         type: 'system',
                //         name: "dictionary",
                //         getParam: function (item) {
                //             return {fieldName: "EKPO"}
                //         },
                //         back: {
                //             EBELN: "ebeln",
                //             MATNR: "matnr",
                //         }
                //     }
                // }
            },
            { display: "实际应收金额", name: "realAmount", width: 140, minWidth: 60, type: "string", align: "left",
                editor: {  type: "text",mask: 'nnnnnnnnn.nn',required: true }
            },
            {
                display: "操作", name: "viewDetail", width: 150, minWidth: 60, type: "string", align: "left",
                render: function (item) {
                    var html = [];
                    html.push('<a class="viewDetail" href="javascript:void(0);"');
                    html.push(' data-id="', item.id, '"');
                    html.push(' data-code="', item.advanceReceiptNo, '">');
                    html.push('<i class="fa fa-location-arrow"></i>&nbsp;');
                    html.push('查看详情');
                    html.push('</a>');
                    return html.join('');
                }
            },
        ],*/
        dataAction: "server",
        url: web_app.name + '/cashSettlementUnPayItem/queryCashSettlementUnPayItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{cashSettlementUnPayId:getId()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "80%",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit:function (item) {
            var id = item.record.id;
            if (item.column.name === "advanceReceiptNo" && Public.isNotBlank(id)) {
                var value = item.value;
                Public.ajax(web_app.name + '/cashSettlementUnPayItem/updateCashSettlementUnPayItems.ajax', {
                    id: id,
                    advanceReceiptNo: value
                }, function (data) {
                })
            }
        }
    });
    $('#maingrid').on('click', function (e) {
        var $clicked = $(e.target || e.srcElement);
        if ($clicked.is('a.viewDetail')) {// 查看预收单详情
            var id =$clicked.data('id');
            var advanceReceiptNo =$clicked.data('code');
            UICtrl.showAjaxDialog({
                title: '详情',
                height: 500,
                width: 1000,
                url: web_app.name + '/cashSettlementUnPayItem/showItemDetail.load?itemId='+id +"&advanceReceiptNo="+advanceReceiptNo,
                ok: function(d){
                    var _self = this;
                    _self.close();
                },
            });
            return false;
        }
    });
    UICtrl.setSearchAreaToggle(gridManager);
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);

    var _grid=UICtrl.getGridManager('#maingrid');
    _grid.options.parms.cashSettlementUnPayId = id;
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return 打样申请的id
 */
function getId() {
    return $("#id").val() || "";
}

function reloadGrid() {
    gridManager.loadData();
}
function getExtendedData(processAction) {
//回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
//不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#maingrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });

        if (!datas) {
            return false;
        }
        extendedData.items = Public.encodeJSONURI(datas);
    }
    return extendedData;
}