/**
 * 加载下拉框数据
 */
function initCombo() {
    $(el.endTime).datebox().datebox('calendar').calendar({
        validator: function (startDate) {
            return moment(startDate).format("YYYY-MM-DD") >= moment(new Date()).format("YYYY-MM-DD");
        }
    });
    hiddenPurchaseRequestType();
    //采购组
    $(el.purchaseGroupCode).combobox({
        valueField: 'purchaseGroupCode',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        onSelect: function (data) {
            // 当前询价单所属采购组编码
            let purchaseGroupCode = data.purchaseGroupCode;
            // 初始化询价模板下拉框
            $(el.templateCode).combobox({
                editable: false,
                limitToList: 'true',
                url: g.ctx + 'pc/inquiry/template/rest/getAllListByPurchaseGroupCode?purchaseGroupCode=' + purchaseGroupCode,
                valueField: 'templateCode',
                textField: 'templateName',
                prompt: '--- 请选择 ---',
                panelHeight: 200,
                onLoadSuccess: function (data) {
                    $(el.templateCode).combobox('setValue', $(el.templateCode).combobox('getValue')?$(el.templateCode).combobox('getValue'):data[0].templateCode);
                },
                onSelect: function (data) {
                    if (!lookFlag){
                        // 销毁现有的物料表格
                        $(el.tbMaterial).datagrid('getPanel').panel('destroy');
                        // 清空之前的模板列数据
                        tmpData.templateFieldData = [];
                        tmpData.templateFieldNameData = [];
                    }
                    hiddenPurchaseRequestType(data.templateCode);
                    // 加载模板表格
                    loadGrid(data.templateCode);
                }
            });

            // 获取成本构成模板数据
            getCostModuleData(purchaseGroupCode);
        }
    });
    //采购组织
    $(el.purchaseOrgCode).combobox({
        valueField: 'purchaseOrgCode',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseOrg/rest/listAll',
    });
    $(el.companyCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/company/rest/listAll'
    });

    // $(el.inquiryType).combobox({
    //     url: g.ctx + 'pc/sys/dict/getDicByType?type=inquiry_type',
    //     panelHeight: 'auto',
    //     limitToList: 'true',
    //     prompt: '-- 请选择 --',
    //     method: 'GET',
    //     valueField: 'code',
    //     textField: 'codeWithDesc',
    // });

    //报价模式
    $(el.quoteModel).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        value:1,
        data: [
            {'name': '价格比较', 'code': 1},
            // {'name': '竞价模式', 'code': 2}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    //采购类型
    $(el.purchaseType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '标准', 'code': '0'},
            {'name': '寄售', 'code': '2'},
            {'name': '委外', 'code': '3'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    //器件分类
    $(el.purchaseCategoryCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data:getNecessaryDataList('pc/sys/purchaseCategory/rest/listAll'),
    });

    //供方描述
    $(el.supplierMaterialFlag).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '长描述', 'code': '0'},
            {'name': '短描述', 'code': '1'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

}

/**
 * 加载询价模板设置字段
 *
 * @param templateCode 询价模板编码
 * @param fieldGroup 模板字段分组；0-基础字段；1-基础扩展；2-阶梯报价；3-自定义扩展字段
 * @param existColumns 已有的列
 */
function loadTemplateFiled(templateCode,fieldGroup,existColumns){
    var loading = top.layer.msg('加载中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/template/rest/getFieldByTemplateCodeAndFieldGroup',
        type: 'GET',
        data: {templateCode: templateCode,fieldGroup:fieldGroup},
        async: false,
        complete: function() {
            top.layer.close(loading);
        },
        success: function (data) {
            if (data){
                debugger;
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    tmpData.templateFieldNameData.push(item.fieldName);
                    let title = (item.required === 1&&!lookFlag?'<span style="color:red">*</span>':'')
                        +(item.fieldAlias?item.fieldAlias:item.labelName)
                        +(item.copyFlag&&!lookFlag?'<button type="button" onclick="copy(\'' + item.fieldName + '\')" class="easyui-linkbutton">复制</button>':'')

                    let editor = {};
                    if (item.fieldType === 'dict'){
                        initDict(item.dictTypeCode);
                    }
                    // debugger
                    // if (item.fieldType === 'data'){
                    //     initNecessaryDatas(item.sqlSentence);
                    // }
                    if (!lookFlag){
                        if (item.fieldType === 'varchar'){
                            debugger
                            var ff = true;
                            //采购申请带出来的采购号，不可编辑
                            if (item.fieldName === 'purchaseBillItemCode' || item.fieldName === 'purchaseBillCode') {
                                ff = false
                            }
                            editor = {
                                type: 'textbox',
                                options: {
                                    editable: ff,
                                    panelHeight: 'auto'
                                }
                                // required:item.required === 1,
                            }
                        }else if (item.fieldType === 'init'){
                            editor = {
                                type: 'numberbox',
                                options: {
                                    editable: true,
                                    panelHeight: 'auto',
                                    min:0,
                                    precision:0
                                }
                            }
                        }else if (item.fieldType === 'number'){
                            debugger
                            var ff = true;
                            if (item.fieldName === 'enablePurchaseNum') {
                                ff = false;
                            }

                            editor = {
                                type: 'numberbox',
                                options: {
                                    editable: ff,
                                    panelHeight: 'auto',
                                    min:0,
                                    // required:item.required === 1,
                                    precision:2
                                }
                            }
                        }else if (item.fieldType === 'decimal'){
                            editor = {
                                type: 'numberbox',
                                options: {
                                    editable: true,
                                    panelHeight: 'auto',
                                    min:0,
                                    precision:priceHandle.precision
                                }
                            }
                        }else if (item.fieldType === 'date'){
                            editor = {
                                type: 'datebox',
                                options: {
                                    editable: false,
                                    panelHeight: 'auto',
                                    // required:item.required === 1
                                }
                            }
                        }else if (item.fieldType === 'dateTime'){
                            editor = {
                                type: 'datetimebox',
                                options: {
                                    editable: false,
                                    panelHeight: 'auto',
                                    // required:item.required === 1
                                }
                            }
                        }else if (item.fieldType === 'dict'){

                            editor = {
                                type: 'combobox',
                                options: {
                                    data: getDictList(item.dictTypeCode),
                                    editable: true,
                                    limitToList: 'true',
                                    panelHeight: 'auto',
                                    // required:item.required === 1,
                                    prompt: '-- 请选择 --',
                                    method: 'GET',
                                    valueField: 'code',
                                    textField: 'codeWithDesc',
                                }
                            }
                        }else if (item.fieldType === 'data'){
                            editor = {
                                type: 'combobox',
                                options: {
                                    url: g.ctx + item.sqlSentence,
                                    editable: true,
                                    limitToList: 'true',
                                    panelHeight: 'auto',
                                    // required:item.required === 1,
                                    prompt: '-- 请选择 --',
                                    method: 'GET',
                                    valueField: 'code',
                                    textField: 'codeWithDesc',
                                }
                            }
                        }else {
                            editor = {}
                        }
                    }
                    if (item.fieldName==='targetPriceType'){
                        existColumns.push({
                            field: item.fieldName,
                            title: title,
                            width: item.labelWidth,
                            formatter:function (value, row,rec) {
                                if (value&&item.fieldType === 'dict') {
                                    return getDicName(item.dictTypeCode,value)
                                }
                            },
                            editor:{
                                type: 'combobox',
                                options: {
                                    data: getDictList(item.dictTypeCode),
                                    editable: true,
                                    limitToList: 'true',
                                    panelHeight: 'auto',
                                    // required:item.required === 1,
                                    prompt: '-- 请选择 --',
                                    method: 'GET',
                                    valueField: 'code',
                                    textField: 'codeWithDesc',
                                    onSelect: function (data) {
                                        let cellEdit = $(el.tbMaterial).datagrid('getEditor', {index: el.editIndex, field: 'targetPrice'});
                                        let row = $(el.tbMaterial).datagrid('getRows')[el.editIndex];
                                        let $input = cellEdit.target;
                                        if (Number(data['code'])===2&&row['historyPrice']){
                                            $input.numberbox('setValue', row['historyPrice']);
                                        }else if (Number(data['code'])===3&&row['lastBidPrice']){
                                            $input.numberbox('setValue', row['lastBidPrice']);
                                        }else {
                                            $input.numberbox('setValue', '');
                                        }
                                    }
                                }
                            }
                        });
                    }else if (item.fieldName==='materialGroupCode'){
                        existColumns.push({
                            field: item.fieldName,
                            title: title,
                            width: item.labelWidth,
                            formatter:function (value, row,rec) {
                                return getNecessaryDataName('pc/sys/productGroup/rest/listAll',value)
                            },
                            editor:{
                                type: 'combobox',
                                options: {
                                    data: getNecessaryDataList('pc/sys/productGroup/rest/listAll'),
                                    editable: true,
                                    limitToList: 'true',
                                    panelHeight: '200',
                                    prompt: '-- 请选择 --',
                                    method: 'GET',
                                    valueField: 'code',
                                    textField: 'codeWithDesc',
                                    onSelect: function (data) {
                                        let row = $(el.tbMaterial).datagrid('getRows')[el.editIndex];
                                        row.materialGroupName = data.codeWithDesc
                                    }
                                }
                            }
                        });
                    }else {
                        existColumns.push({
                            field: item.fieldName,
                            title: title,
                            width: item.labelWidth,
                            exportEnum:item.fieldType === 'dict'?getDictList(item.dictTypeCode):[],
                            exportDateFormatter:item.fieldType === 'dateTime'?'dateTime':item.fieldType === 'date'?'date':'',
                            exportHidden:item.fieldType === 'files',
                            formatter:function (value, row,rec) {
                                if (value&&item.fieldType === 'number') {
                                    return formatNumber(value, item.decimalPoint, 0).toString().replace(/(?:\.0*|(\.\d+?)0+)$/,'$1');
                                }
                                if (value&&item.fieldType === 'decimal') {
                                    return formatterPrice(value);
                                }
                                if (value&&item.fieldType === 'dict') {
                                    return getDicName(item.dictTypeCode,value)
                                }
                                // if (value&&item.fieldType === 'data') {
                                //     return getNecessaryDataName(item.sqlSentence,value)
                                // }
                                if (!lookFlag&&item.fieldType === 'files') {
                                    return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '" data-fieldName="' + item.fieldName + '">上传/下载</a>';
                                }
                                if (lookFlag&&item.fieldType === 'files') {
                                    if (value){
                                        value.split(',').length
                                        return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '" data-fieldName="' + item.fieldName + '">查看('+value.split(',').length+')个附件</a>';
                                    }else {
                                        return '无附件';
                                    }

                                }
                                if (value&&item.fieldType === 'date') {
                                    return moment(value).format("YYYY-MM-DD");
                                }
                                if (value&&item.fieldType === 'dateTime') {
                                    return moment(value).format("YYYY-MM-DD HH:mm:ss");
                                }
                                return value;
                            },
                            editor:editor
                        });
                    }
                    debugger
                    // var requiredFlag = item.required;
                    // if(item.fieldName==='materialGroupCode'){
                    //     requiredFlag = 0;
                    // }
                    tmpData.templateFieldData.push({
                        fieldName: item.fieldName,
                        labelName: item.fieldAlias?item.fieldAlias:item.labelName,
                        required: item.required,
                        fieldId: item.fieldId
                    });
                }
            }
        },
        error: function (data) {
            layer.alert(JSON.parse(data.responseText).message);
        }
    });
}

/**
 * 根据不同模板编码显示或隐藏询价类型下拉框
 * @param templateCode
 */
function hiddenPurchaseRequestType(templateCode) {
    const purchaseRequestTypeDiv = $(el.purchaseRequestTypeDiv);
    const purchaseRequestType = $(el.purchaseRequestType);
    const purchaseRequestTypeLabel = $(el.purchaseRequestTypeLabel);
    const purchaseRequestTypeNoLabel = $(el.purchaseRequestTypeNoLabel);

    const supplierDescDiv = $(el.supplierDescDiv);
    const supplierDescLabel = $(el.supplierDescLabel);
    const supplierDescNoLabel = $(el.supplierDescNoLabel);
    const supplierMaterialFlag = $(el.supplierMaterialFlag);

    if (lookFlag) {
        purchaseRequestType.combobox({
            url: g.ctx + 'pc/sys/dict/getDicByType?type=purchasing_business_type',
            valueField: 'code',
            textField: 'codeWithDesc',
            method: 'GET',
            panelHeight: 'auto',
            prompt: '-- 请选择 --'
        });
        return;
    }
    if (templateCode === 'PLATE_PRO_M002'){
        // MRO询价模板
        // 显示下拉框和标签
        purchaseRequestTypeDiv.removeAttr("hidden");
        purchaseRequestTypeLabel.removeAttr("hidden");
        purchaseRequestTypeNoLabel.attr("hidden", true);
        purchaseRequestType.combobox({
            url: g.ctx + 'pc/sys/dict/getDicByType?type=purchasing_business_type',
            valueField: 'code',
            textField: 'codeWithDesc',
            method: 'GET',
            panelHeight: 'auto',
            prompt: '-- 请选择 --',
            disabled: false,
            onSelect: purchaseRequestTypeChangeEvent
        });
        // 抬头栏位隐藏“供方描述”
        supplierDescDiv.attr("hidden", true);
        supplierDescLabel.attr("hidden", true);
        supplierDescNoLabel.removeAttr("hidden");
        supplierMaterialFlag.combobox({disabled: true});
    } else {
        // 隐藏下拉框和标签
        purchaseRequestTypeDiv.attr("hidden", true);
        purchaseRequestTypeLabel.attr("hidden", true);
        purchaseRequestTypeNoLabel.removeAttr("hidden");
        purchaseRequestType.combobox({disabled: true});

        // 抬头栏位显示“供方描述”
        supplierDescDiv.removeAttr("hidden");
        supplierDescLabel.removeAttr("hidden");
        supplierDescNoLabel.attr("hidden", true);
        supplierMaterialFlag.combobox({disabled: false})
    }
}

/**
 * 询价类型变更事件
 * @param data
 */
function purchaseRequestTypeChangeEvent(data) {
    // const supplierDescLabel = $(el.supplierDescLabel);
    // const supplierDescNoLabel = $(el.supplierDescNoLabel);
    // const supplierDescDiv = $(el.supplierDescDiv);
    // const supplierMaterialFlag = $(el.supplierMaterialFlag);
    if (data.code === '01') {
        // 费用类
        // 待询价物料明细将列“采购数量“、“需求数量”、“工厂“、“物料组编码”移到“备注”后；
        moveFieldsAfter(el.tbMaterial, 'remark', [
            'purchaseNum',
            'number',
            'factoryCode',
            'materialGroupCode'
        ]);
        // 待询价物料明细新增列“采购申请编码“、”采购申请行号“
        // $(el.tbMaterial).datagrid('showColumn', 'purchaseBillCode');
        // $(el.tbMaterial).datagrid('showColumn', 'purchaseBillItemCode');
        // 抬头栏位隐藏“供方描述”
        // supplierDescDiv.attr("hidden", true);
        // supplierDescLabel.attr("hidden", true);
        // supplierDescNoLabel.removeAttr("hidden");
        // supplierMaterialFlag.combobox({disabled: true});
    } else {
        // 非费用类
        loadGrid($(el.templateCode).combobox('getValue'), '1');
        // 抬头栏位显示“供方描述”
        // supplierDescDiv.removeAttr("hidden");
        // supplierDescLabel.removeAttr("hidden");
        // supplierDescNoLabel.attr("hidden", true);
        // supplierMaterialFlag.combobox({disabled: false});
    }
}

/**
 * 将指定列移动到某列后
 * @param dgId 表格ID
 * @param afterField
 * @param fieldsToMove
 */
function moveFieldsAfter(dgId, afterField, fieldsToMove) {
    const opts = $(dgId).datagrid('options');
    let cols = opts.columns[0];

    // 1. 先把这些字段从原位置删除
    let movingCols = [];
    fieldsToMove.forEach(f => {
        let idx = cols.findIndex(c => c.field === f);
        if (idx !== -1) {
            movingCols.push(cols.splice(idx, 1)[0]);
        }
    });

    // 2. 找到指定列的位置
    let afterIndex = cols.findIndex(c => c.field === afterField);
    if (afterIndex === -1) return;

    // 3. 插入到指定列后面
    cols.splice(afterIndex + 1, 0, ...movingCols);

    // 4. 重新设置
    $(dgId).datagrid({
        columns: [cols]
    }).datagrid('reload');
}