var gridManager = null;
var itemGridManager = null;
var itemNumberGridManager = null;
var itemNumberClickGridManager = null;
var  canEdit=true;

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

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(bizId) {
    $("#id").val(bizId);
    var _grid = UICtrl.getGridManager('#itemGrid');
    _grid.options.parms.processQuotedPriceId = bizId;
    itemGridManager.loadData();
}

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

// 加载订单行项目表格
function loadItemGrid() {
    var toolbarOptions = null;
    toolbarOptions = UICtrl.getDefaultToolbarOptions({
        // 添加一行表格
        addHandler: function () {
            UICtrl.addGridRow(itemGridManager,
                {
                    // 行号加一
                    itemNo: (itemGridManager.getData().length + 1),
                    status: 1
                }
            );
        },
        // 删除
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#itemGrid');
            DataUtil.delSelectedRows({
                action: 'processQuotedPrice/deleteProcessQuotedPriceItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    itemGridManager.loadData();
                }
            });
        },
        enableHandler: enableHandler,
        disableHandler: disableHandler,
        printHandler: {
            id: 'printHandler', text: '打印', img:'fa-clipboard', click: function(){
                printHandler();
            }
        },
    });
    // 表格
    itemGridManager = UICtrl.grid("#itemGrid", {
        columns: getOrderColumns(),
        dataAction: "server",
        _tableKey: 'processQuotedPriceItem',
        _local: true,
        url: web_app.name + '/processQuotedPrice/queryProcessQuotedPriceItems.ajax',
        parms: {processQuotedPriceId: getId()},
        pageSize: 20,
        usePager: true,
        sortName: "itemNo",
        sortOrder: "asc",
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "98%",
        height: "300px",
        heightDiff: -8,
        checkbox: false,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        rownumbers: true,
        onSelectRow: function (data, rowindex, rowobj) {
            queryProcessQuotedPriceItemNumber(data.id);
        }
    });
    $('#itemGrid').on('click', function (e) {
        var $clicked = $(e.target || e.srcElement);
        if ($clicked.is('a.bindAnln1')) {// 绑定资产编号
            var id =$clicked.data('id');
            var productCode =$clicked.data('code');
            var outProcess =$clicked.data('process');
            UICtrl.showAjaxDialog({
                title: '绑定',
                height: 400,
                width: 700,
                url: web_app.name + '/processQuotedPrice/showBindProcessQuotedPrice.load',
                param:{
                    itemId: id,
                    productCode: productCode,
                    outProcess: outProcess
                },
                ok: function(d){
                    var _self = this;
                    var datas = itemNumberGridManager.getData();
                    for (let i = 0; i < datas.length; i++) {
                        var row = datas[i];
                        if (Public.isBlank(row.unitPrice) || row.unitPrice ==0){
                            Public.tip("请填写含税单价");
                            return false;
                        }
                        if (Public.isBlank(row.purchaseMwskz)){
                            Public.tip("请填写税码");
                            return false;
                        }
                    }
                    //如果没保存过，需要主表单保存按钮
                    if (Public.isBlank(id)){
                        updateItemGridManager(datas,productCode,outProcess);
                        save("SAVE",null);
                    }else {
                        //如果是保存过的报价单明细，直接保存
                        Public.ajax(web_app.name+"/processQuotedPrice/saveProcessQuotedPriceItemNumber.ajax",
                            {
                                itemId: id,
                                numberList: Public.encodeJSONURI(datas)
                            },
                            function (data){

                            })
                    }
                    _self.close();
                    queryProcessQuotedPriceItemNumber(id);
                },
            });
            return false;
        }
    });
    UICtrl.setSearchAreaToggle(itemGridManager);
}

function getOrderColumns(){
    var columns = [];
    columns.push({
        display: "操作", name: "bindAnln1", width: 150, minWidth: 60, type: "string", align: "left",
        render: function (item) {
            var html = [];
            html.push('<a class="bindAnln1" href="javascript:void(0);"');
            html.push(' data-id="', item.id, '"');
            html.push(' data-code="', item.productCode, '"');
            html.push(' data-process="', item.outProcess, '">');
            html.push('<i class="fa fa-location-arrow"></i>&nbsp;');
            html.push('报价规则');
            html.push('</a>');
            return html.join('');
        }
    },)
    columns.push({display: "项次", name: "itemNo", width: 60, minWidth: 60, type: "string", align: "left"});
    columns.push({display: "启用/禁用", name: "status", width: 60, minWidth: 60, type: "string", align: "left",
        render: function (item) {
            return UICtrl.getStatusInfo(item.status);
        }
    });
    columns.push({
        display: "产品编码", name: "productCode", width: 160, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "sapProductSelect",
                getParam: function (item) {
                    return {
                        //filterValue:item.werks
                    }
                },
                back: {
                    MATNR: "productCode",
                    MAKTX: "productName",
                    MSEHL: "unitName"
                }
            },
        }
    },);
    columns.push({
        display: "产品名称", name: "productName", width: 300, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "单位", name: "unitName", width: 60, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({display: "外发工序编号",width: 100, name: "outProcess"},);
    columns.push({display: "外发工序", name: "outProcessName", width: 150, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "selectEpProcess",
                getParam: function (item) {
                    if (Public.isBlank(item.productCode)){
                        Public.tip("请先选择产品");
                        return false;
                    }
                    return {
                        itemCode:item.productCode
                    }
                },
                back: {
                    process_code: "outProcess",
                    process_name: "outProcessName"
                }
            },
        }
        },);
    columns.push({
        display: "机台", name: "machineTool", width: 100, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "text",
        }
    });
    columns.push({
        display: "印刷色数", name: "printColor", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "text",
        }
    });
    columns.push({
        display: "库存名称", name: "storeName", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", required: false
        }
    },);
    columns.push({
        display: "备注", name: "remark", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", required: false
        }
    },);
    columns.push({
        display: "禁用人", name: "disablePersonName", width: 100, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "禁用时间", name: "disableDate", width: 100, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "禁用原因", name: "disableReason", width: 200, minWidth: 60, type: "string", align: "left",
    },);
    return columns;
}

//启用
function enableHandler(){
    DataUtil.updateById({ action: 'processQuotedPrice/updateProcessQuotedPriceItemStatus.ajax',
        gridManager: itemGridManager,idFieldName:'id', param:{status: 1},
        message:'确实要启用选中数据吗?',
        onSuccess:function(){
            reloadGrid();
        }
    });
}
//禁用
function disableHandler(){
    DataUtil.updateById({ action: 'processQuotedPrice/updateProcessQuotedPriceItemStatus.ajax',
        gridManager: itemGridManager,idFieldName:'id', param:{status: 0},
        message: '确实要禁用选中数据吗?',
        onSuccess:function(){
            reloadGrid();
        }
    });
}

function printHandler(){
    var row = DataUtil.getUpdateRow(itemGridManager);
    if (!row) {
        return;
    }
    var url='/processQuotedPrice/print.load';
    Public.openPostWindow(web_app.name+url,{id: row.id});
}

function queryProcessQuotedPriceItemNumber(itemId){
    var _grid = UICtrl.getGridManager('#itemNumberClickGrid');
    _grid.options.parms.processQuotedPriceItemId = itemId;
    itemNumberClickGridManager.loadData();
}

function updateItemGridManager(datas,productCode,outProcess){
    var _maingrid = UICtrl.getGridManager('#itemGrid');
    if (_maingrid != null){
        if (_maingrid.currentData != null){
            var rows = _maingrid.currentData.Rows;
            $.each(rows, function (i, row) {
                //根据产品编码和工序编码
                if (productCode === row.productCode && outProcess === row.outProcess){
                    _maingrid.updateRow(row,{
                        numberList:datas
                    })
                }
            });
        }
    }
}

function loadClickItemGrid() {
    var toolbarOptions = null;
    toolbarOptions = UICtrl.getDefaultToolbarOptions({
    });
    // 表格
    itemNumberClickGridManager = UICtrl.grid("#itemNumberClickGrid", {
        gridManager: null,
        columns: [
            {display: "数量起", name: "numberFrom", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "数量止", name: "numberTo", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "数量区间", name: "numberSection", width: 200, minWidth: 60, type: "String", align: "left"},
            {display: "备注", name: "remark", width: 200, minWidth: 60, type: "String", align: "left"},
            {display: "含税单价", name: "unitPrice", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "税码", name: "purchaseMwskzTextView", width: 140, minWidth: 60, type: "string", align: "left"},
            {display: "不含税单价", name: "excludeTaxPrice", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "运输费", name: "freight", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "包装费", name: "packMoney", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "最低消费", name: "minimum", width: 100, minWidth: 60, type: "String", align: "left"},
            {display: "loss数", name: "lossNumber", width: 100, minWidth: 60, type: "String", align: "left"},
        ],
        dataAction: "server",
        url: web_app.name + '/processQuotedPrice/queryProcessQuotedPriceItemNumbers.ajax',
        parms: {},
        pageSize: 20,
        usePager: true,
        sortName: "numberFrom",
        sortOrder: "asc",
        toolbar: toolbarOptions,
        enabledEdit: canEdit,
        width: "98%",
        height: "300px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(itemNumberClickGridManager);
}

//获取数据保存的参数
function getExtendedData(processAction) {
    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
        //不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#itemGrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.items = Public.encodeJSONURI(datas);
    }
    return extendedData;
}


function checkConstraints(){
    //订单行项目信息
    var item_grid = UICtrl.getGridManager('#itemGrid');
    if (item_grid) {
        var datas = DataUtil.getGridData({
            gridManager: item_grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0){
            Public.tip("报价单明细必填");
            return false;
        }
        var hasItemNumber = true;
        var no = 0;
        //如果没保存，从datas中取数据判断有没有报价规则
        if (Public.isBlank(getId())){
            for (let i = 0; i < datas.length; i++) {
                var row = datas[i];
                no = row.itemNo;
                if (Public.isBlank(row.numberList) || row.numberList.length ==0){
                    hasItemNumber = false;
                }
            }
        }else {
            //保存了，从数据库查询
            for (let i = 0; i < datas.length; i++) {
                var row = datas[i];
                no = row.itemNo;
                //如果id为空，说明是新增的，从datas中取数据判断有没有报价规则
                if (Public.isBlank(row.id)){
                    if (Public.isBlank(row.numberList) || row.numberList.length ==0){
                        hasItemNumber = false;
                    }
                }else {
                    Public.syncAjax(web_app.name+"/processQuotedPrice/queryProcessQuotedPriceItemNumber.ajax",{
                        itemId: row.id
                    },function (data){
                        if (Public.isBlank(data.Total) || data.Total ==0){
                            hasItemNumber = false;
                        }
                    })
                }
            }
        }
        if (!hasItemNumber){
            Public.tip("明细项次："+ no +" 未绑定报价规则");
            return false;
        }
    }
    return true;
}


function bindEvent(){
    $('#supplierName').searchbox({
        type: "system", name: "selectSuppliersDatas",
        onChange: function (value, data) {
            $('#supplier').val(data.partner);
            $('#supplierName').val(data.nameOrg1);
        }
    });

    $('#currencyName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "WAERS"}
        },
        onChange: function (value, data) {
            $('#currency').val(data.WAERS);
            $('#currencyName').val(data.KTEXT);
        }
    });

}

function reloadGrid() {
    itemGridManager.loadData();
}