var el = {
    form : '#form',
    optType : '#optType',
    tbMaterial : '#tb_material',
    tbSupplier : '#tb_supplier',
    id : '#id',
    beginTime: '#beginTime',
    purchaseFiles: '#purchaseFiles',
    files: '#files',
    endTime: '#endTime',
    purchaseGroupCode: '#purchaseGroupCode',
    purchaseOrgCode: '#purchaseOrgCode',
    templateCode: '#templateCode',
    companyCode: '#companyCode',
    inquiryType: '#inquiryType',
    quoteModel: '#quoteModel',
    purchaseType: '#purchaseType',
    purchaseCategoryCode: '#purchaseCategoryCode',
    supplierMaterialFlag: '#supplierMaterialFlag',
    purchaseRequestType: '#purchaseRequestType',
    editIndex: undefined,
    editSupplierIndex: undefined,
    exportFileds: [],
    self: this,
    bodyHeight: document.documentElement.clientHeight
};
var tmpData = {
    //成本构成数组
    costModuleData: [],
    //模板字段数组
    templateFieldData: [],
    //模板字段名称数组
    templateFieldNameData: [],
}
$(function () {
    initDict('currency,tax,payment_way,payment_method');
    initNecessaryDatas('pc/sys/company/rest/listAll,pc/sys/purchaseCategory/rest/listAll');
    initCombo();
});


function loadGrid(templateCode){
    // 在页面上申明一个新的表格DOM
    el.tbMaterial = $('<table id="tb_material" width="100%"></table>').appendTo($('.tb-material'));
    // 固定加载的列
    let existColumns = [
        {
            field: 'materialCode',
            title: '物料编码',
            width: 100
        },
        {
            field: 'materialName',
            title: '物料名称',
            width: 160,
            formatter: function (value, row) {
                return '<span title="'+value+'">'+value+'</span>';
            }
        },
        // {
        //     field: 'productName',
        //     title: '品名',
        //     width: 100
        // },
        {
            field: 'materialSpec',
            title: '详细规格参数',
            width: 100
        },
        // {
        //     field: 'brand',
        //     title: '品牌',
        //     width: 100
        // },
        {
            field: 'costFlag',
            title: '成本构成',
            width: 80,
            exportEnum:[
                {code:1,codeWithDesc:'是'},
                {code:0,codeWithDesc:'否'}
            ],
            formatter: function (value) {
                if (Number(value) === 1) {
                    return '是';
                } else {
                    return '否';
                }
            }
        },
        {
            field: 'costTemplateCode',
            title: '成本构成模板',
            width: 100,
            formatter: function (value, row) {
                for (let i = 0; i < tmpData.costModuleData.length; i++) {
                    if (tmpData.costModuleData[i].value === value) {
                        return tmpData.costModuleData[i].text;
                    }
                }
                return row['text'];
            }
        },
        {
            field: 'stagePriceFlag',
            title: '阶梯报价',
            width: 80,
            exportEnum:[
                {code:1,codeWithDesc:'是'},
                {code:0,codeWithDesc:'否'}
            ],
            formatter: function (value) {
                if (Number(value) === 1) {
                    return '是';
                } else {
                    return '否';
                }
            }
        },
        {
            field: 'purchaseBillCode',
            title: '采购订单号',
            width: 120
        },
        {
            field: 'purchaseBillItemCode',
            title: '采购行项目号',
            width: 120
        }
    ];
    loadTemplateFiled(templateCode,3,existColumns);
    $(el.tbMaterial).datagrid({
        iconCls: 'icon-list',
        title: '询价物料供应商',
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/inquiry/material/rest/listAll',
        height: el.bodyHeight - 300,
        singleSelect: false,
        rownumbers: true,
        pagination: false,
        queryParams: {inquiryId:$(el.id).val()},
        columns: [existColumns],
        toolbar: [
            {
                text: '导出',
                iconCls: 'icon-print',
                handler: function () {
                    var params = {
                        inquiryId:$(el.id).val()
                    };
                    xhrPostExport('pc/inquiry/material/rest/export',params,el.exportFileds)
                }
            }
        ],
        view: detailview,
        detailFormatter: function (index) {
            return '<div id="ddv-' + index + '" style="padding:5px"></div>';
        },
        onExpandRow: function (index, row) {
            initInquirySupplier(index, row);
        }
    });

    var opts = $(el.tbMaterial).datagrid('getColumnFields');
    var opts2 = $(el.tbMaterial).datagrid('getColumnFields', true);
    opts = opts2.concat(opts);
    for (var i = 0; i < opts.length; i++) {
        if (opts[i] === 'ck') continue;
        var option = $(el.tbMaterial).datagrid("getColumnOption", opts[i]);
        if (!option.hidden) {
            if (option.title === undefined) continue;
            if (option.exportHidden) continue;
            el.exportFileds.push({
                title: option.title.replace('<font color="red">*</font>', ""),
                field: opts[i],
                select: 1,
                width: Number(option.width),
                exportEnum: option.exportEnum,
                exportDateFormatter: option.exportDateFormatter
            })
        }
    }

    if ($(el.purchaseRequestType).combobox("getValue") === '01') {
        // 费用类
        // 待询价物料明细将列“采购数量“、“需求数量”、“工厂“、“物料组编码”移到“备注”后；
        moveFieldsAfter(el.tbMaterial, 'remark', [
            'purchaseNum',
            'number',
            'factoryCode',
            'materialGroupCode'
        ]);
        // 待询价物料明细新增列“采购申请编码“、”采购申请行号“
        $(el.tbMaterial).datagrid('showColumn', 'purchaseBillCode');
        $(el.tbMaterial).datagrid('showColumn', 'purchaseBillItemCode');
    }
}

/**
 * 加载报价供应商数据
 */
function initInquirySupplier(index, row) {
    $('#ddv-' + index).datagrid({
        url: g.ctx + 'pc/inquiry/material/supplier/rest/getListByInquiryIdAndInquiryMaterialId',
        rownumbers: true,
        loadMsg: '数据加载中......',
        width: screenWidth - 70,
        pagination: false,
        queryParams: {
            inquiryId: row.inquiryId,
            inquiryMaterialId: row.id
        },
        columns: [
            [
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 130
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 300
                },
                {
                    field: 'purchaseCategoryCode',
                    title: '采购品类编码',
                    width: 150
                },
                {
                    field: 'purchaseCategoryName',
                    title: '采购品类名称',
                    width: 150
                },
                {
                    field: 'companyCode',
                    title: '公司',
                    width: 260,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    field: 'joinQuoteFlag',
                    title: '参与报价',
                    width: 80,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '参与';
                        } else {
                            return '不参与';
                        }
                    }
                },
                {
                    field: 'quoteFlag',
                    title: '报价状态',
                    width: 110,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '<span style="color: green;">已报价</span>';
                        } else {
                            return '未报价';
                        }
                    }
                },
                {
                    field: 'bidFlag',
                    title: '是否定价',
                    width: 300,
                    formatter:function (value) {
                        if (Number(value) === 1){
                            return '<a style="color: red">是</a>'

                        }else {
                            return '<a style="color: black">否</a>'
                        }
                    }
                }
            ]
        ],
        onResize: function () {
            $(el.tbMaterial).datagrid('fixDetailRowHeight', index);
        },
        onLoadSuccess: function () {
            // $(el.tbMaterial).datagrid('fixDetailRowHeight', index);
            setTimeout(function () {
                $(el.tbMaterial).datagrid('fixDetailRowHeight', index);
            }, 0);
        }
    });
    $(el.tbMaterial).datagrid('fixDetailRowHeight', index);
}

function uploadFilesDialog(target){
    let rowIndex = $(target).data('index'), value = $(target).data('value'),fieldName = $(target).attr('data-fieldName');
    openFileUploadDialog('uploadFilesDialog',{
        title:'查看',
        fileIds : value,
        height: '75%',
        lookFlag: 1,
        callBack : function (fileId) {

            console.log(fileId)
        },
    });
}

/**
 * 获取成本构成模板数据
 *
 * @param purchaseGroupCode 采购组编码
 */
function getCostModuleData(purchaseGroupCode) {
    $.ajax({
        url: g.ctx + 'pc/inquiry/cost/template/rest/getAllListByPurchaseGroupCode',
        type: 'GET',
        async: false,
        data: {purchaseGroupCode: purchaseGroupCode},
        success: function (data) {
            console.log(data)
            // 清空
            tmpData.costModuleData = [];
            if (data && data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    tmpData.costModuleData.push({
                        value: data[i].templateCode,
                        text: data[i].templateName
                    });
                }
            }
        },
        error: function (data) {
            layer.alert(JSON.parse(data.responseText).message);
        }
    });
}
