var el = {
    tb: '#tb',
    editIndex: undefined,
    costTypeData: [],
    form: '#form',
    materialCode: '#materialCode',
    materialName: '#materialName',
    taxTotalPrice: '#taxTotalPrice',
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    initDict('unit');
    var data1 = getParentCostDetailData();
    loadGrid();
    $(el.tb).datagrid('loadData', {total: data1.length, rows: data1});
    $(el.tb).datagrid('options').onClickRow = function (index) {
        onClickRow(index);
    }
});

/**
 * 加载数据表格
 */
function loadGrid() {
    var dataForm = $(el.form).outerHeight() + 20;
    var columns = [];
    var toolbar = [{
        iconCls: 'icon-add',
        handler: function () {
            $(el.tb).datagrid("appendRow", {inquiryMaterialSupplierId: inquiryMaterialSupplierId, source: 1});
        }
    }, '-', {
        iconCls: 'icon-delete',
        handler: function () {
            endEditing();
            var delRows = $(el.tb).datagrid("getChecked");
            delRows.reverse();
            $.each(delRows, function (idx, item) {
                var index = $(el.tb).datagrid("getRowIndex", item);
                $(el.tb).datagrid("deleteRow", index);
            });
            addMoney(0);
        }
    }];
    if (lookFlag){
        toolbar = [];
        columns = [
            {
                field: 'costTypeName',
                title: BJGL.BJGL__CBLX,
                width: 150,
            },
            {
                field: 'unitCode',
                title: BJGL.BJGL__DW,
                width: 110,
                formatter: function (value, row) {
                    return getDicName('unit',value);
                }
            },
            {
                field: 'consumeNum',
                title: BJGL.BJGL__XHDE,
                width: 120
            },
            {
                field: 'taxPrice',
                title: "单价(含税)",
                width: 100
            },
            {
                field: 'taxTotalPrice',
                title: BJGL.BJGL__JE,
                width: 100
            },
            {
                field: 'remark',
                title: BJGL.BJGL__BZ,
                width: 200
            }
        ];
    }else {
        columns = [
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'costTypeName',
                title: BJGL.BJGL__CBLX,
                width: 150,
                editor: {
                    type: 'textbox',
                    options: {
                        editable: !lookFlag,
                    }
                }
            },
            {
                field: 'unitCode',
                title: BJGL.BJGL__DW,
                width: 110,
                formatter: function (value, row) {
                    return getDicName('unit',value);
                },
                editor: {
                    type: 'combobox',
                    options: {
                        data: getDictList('unit'),
                        editable: !lookFlag,
                        limitToList: 'true',
                        panelHeight: 'auto',
                        prompt: '-- 请选择 --',
                        method: 'GET',
                        valueField: 'code',
                        textField: 'codeWithDesc',
                    }
                }
            },
            {
                field: 'consumeNum',
                title: BJGL.BJGL__XHDE,
                width: 120,
                editor: {
                    type: 'numberbox',
                    options: {
                        editable: !lookFlag,
                        min: 0,
                        precision: 2
                    }
                }
            },
            {
                field: 'taxPrice',
                title: "单价(含税)",
                width: 100,
                editor: {
                    type: 'numberbox',
                    options: {
                        editable: !lookFlag,
                        min: 0,
                        precision: precision
                    }
                }
            },
            {
                field: 'taxTotalPrice',
                title: BJGL.BJGL__JE,
                width: 100,
                editor: {
                    type: 'numberbox',
                    options: {
                        editable: !lookFlag,
                        min: 0,
                        precision: precision,
                        required: true,
                        onChange: function (value, old) {
                            addMoney(value);
                        }
                    }
                }
            },
            {
                field: 'remark',
                title: BJGL.BJGL__BZ,
                width: 200,
                editor: {
                    type: 'text',
                    options: {
                        editable: !lookFlag,
                    }
                }
            }
        ];
    }
    $(el.tb).datagrid({
        loadMsg: ALLCOMMON.LOADING,
        // url: g.ctx +'pc/inquiry/supplier/cost/quote/detail/rest/listByInquiryMaterialSupplierIdAndCostTemplateCode',
        singleSelect: true,
        pagination: false,
        height: el.bodyHeight - dataForm,
        rownumbers: true,
        // queryParams: {
        //     inquiryMaterialSupplierId: inquiryMaterialSupplierId,
        //     costTemplateCode: costTemplateCode,
        // },
        toolbar: toolbar,
        columns: [columns],
        onClickRow: function (index) {
            if (!lookFlag){
                onClickRow(index);
            }

        }
    });
}

/**
 * 每个成本构成的金额相加
 */
function addMoney(value) {
    var rows = $(el.tb).datagrid('getRows'), taxTotalPrice = 0;
    for (var i = 0; i < rows.length; i++) {
        if (el.editIndex !== i) {
            var item = rows[i];
            taxTotalPrice = Number(taxTotalPrice) + Number(item.taxTotalPrice);
        }
    }

    if (el.editIndex !== undefined) {
        taxTotalPrice = Number(taxTotalPrice) + Number(value);
    }
    $(el.taxTotalPrice).textbox('setValue', formatDecimal(Number(taxTotalPrice),precision));
}


/**
 * 结束行编辑
 *
 * @return {boolean} 结果
 */
function endEditing() {
    if (el.editIndex === undefined) {
        return true
    }
    if ($(el.tb).datagrid('validateRow', el.editIndex)) {
        $(el.tb).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickRow(rowIndex) {
    if (el.editIndex !== rowIndex) {
        if (endEditing()) {
            $(el.tb).datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
            el.editIndex = rowIndex;
        } else {
            $(el.tb).datagrid('selectRow', el.editIndex);
        }
    } else {
        $(el.tb).datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
        el.editIndex = rowIndex;
    }
}

/**
 * 获取父级页面暂存的成本报价数据
 *
 * @return {array} 结果
 */
function getParentCostDetailData() {
    var parentPage = self.parent.frames[parentFrameName],
        result = parentPage.getCostQuoteData(inquiryMaterialSupplierId);

    var material = result.material;
    $(el.materialName).textbox('setValue', material.materialName);
    $(el.materialCode).textbox('setValue', material.materialCode);
    $(el.taxTotalPrice).textbox('setValue', material.taxTotalPrice);
    var data = [];
    $.each(result.data, function (idx, itm) {
        data.push(itm);
    })
    if (data.length === 0) {
        $.ajax({
            url: g.ctx +'pc/inquiry/supplier/cost/quote/detail/rest/listByInquiryMaterialSupplierIdAndCostTemplateCode',
            type: 'POST',
            async: false,
            data: {
                inquiryMaterialSupplierId: inquiryMaterialSupplierId,
                costTemplateCode: costTemplateCode
            },
            success: function (rows) {
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i], item = {};
                    item.id = row.id;
                    item.inquiryMaterialSupplierId = row.inquiryMaterialSupplierId;
                    item.costTypeName = row.costTypeName;
                    item.unitCode = row.unitCode;
                    item.consumeNum = row.consumeNum;
                    item.taxPrice = row.taxPrice;
                    item.taxTotalPrice = row.taxTotalPrice;
                    item.remark = row.remark;
                    data.push(item);
                }
            },
            error: function (res) {
                console.log('获取成本构成模板数据报错', res);
            }
        });
    }
    $.each(data, function (idx, itm) {
        el.costTypeData.push({val: itm.costTypeName});
    });
    return data;
}

function saveCostQuote(callback){
    endEditing();
    addMoney(0);
    var rows = $(el.tb).datagrid('getRows');
    var taxTotalPrice = $(el.taxTotalPrice).textbox('getValue');
    var obj = {};
    obj.rows = rows;
    obj.taxTotalPrice = taxTotalPrice;
    callback(obj);

}