/**
 *
 * @author BOGON
 * @version 1.0
 */
/**
 * 表格参数，在表格添加事件中，表单的name值、表单内容，根据参数渲染页面
 */
let el = {
    supplierId: '#supplierId',
    changeVersionId: '#changeVersionId',
    tab: '#tab',
    form: '#form',
    supplierInfo: '#supplierInfo',
    authenticationType: '#authenticationTypeId',
    signUpRemark: '#signUpRemark',
    remark: '#remark',
    oaType: '#oaType',
    isFreeze: '#isFreeze',
    executionTime:'#executionTime',
    paymentTerms:'#paymentTerms',
    templateFollowTable: '#templateFollowTable',
    error: '#error',
    eliminateFlag:'#eliminateFlag',
    supplierNameFile: '#supplierNameFile',
    legalFile: '#legalFile',
    settlementMethodFile: '#settlementMethodFile',
    supplierBankFile: '#supplierBankFile',
    modifyFile: '#modifyFile'
};
let selfData = {
    supplierId: 0, templateTableField: []
};
let param = {
    /**
     * 表格的id列，提取出公共逻辑，用来显示数据是否已经保存
     */
    idColumn: {
        field: 'type', title: '状态', width: '6%', align: 'left', formatter: function (value) {
            switch (value) {
                case 1:
                    return '<span style="color:blue;">新建</span>';
                case 2:
                    return '<span style="color:green;">编辑</span>';
                case 3:
                    return '<span style="color:red;">删除</span>';
                default:
                    return '初始';
            }
        }
    },
};
let queryParam = {};
/**
 * 表格行编辑类型
 * {el 页面元素；editIndex 行编辑坐标}
 */
var changeVersionId = $(el.changeVersionId).val();
var purchaseCategoryUrl = g.ctx + 'pc/supplier/purchaseCategory/rest/listSupplier?state=3,6,7';
var qualificationTypeUrl = g.ctx + 'pc/supplier/qualification/rest/supplierQualifications?typeStr=1,2&codes=SRM_ZZ_002,SRM_ZZ_001,SRM_ZZ_006,SRM_ZZ_035,SRM_ZZ_036,SRM_ZZ_037,SRM_ZZ_038,SRM_ZZ_004,SRM_ZZ_017,SRM_ZZ_016,SRM_ZZ_039,SRM_ZZ_044,SRM_ZZ_045,,SRM_ZZ_046,SRM_ZZ_047,SRM_ZZ_048,SRM_ZZ_049,SRM_ZZ_050,SRM_ZZ_051,SRM_ZZ_052,SRM_ZZ_053,SRM_ZZ_054,SRM_ZZ_055,SRM_ZZ_056,SRM_ZZ_057,SRM_ZZ_058,SRM_ZZ_059,SRM_ZZ_060,SRM_ZZ_061,SRM_ZZ_062,SRM_ZZ_025,SRM_ZZ_019,SRM_ZZ_030';
if($(el.changeVersionId).val() != '' && $(el.changeVersionId).val() >0){
    purchaseCategoryUrl =  g.ctx +'pc/supplier/supplierChange/rest/supplierPurchaseCategoryVersionWholeList?changeVersionId=' + changeVersionId;
    qualificationTypeUrl =  g.ctx +'pc/supplier/supplierChange/rest/supplierQualificationVersionWholeList?changeVersionId=' + changeVersionId;
}
let tableType = {

    //联系人
    supplierContact: {
        el: '#supplierContactTb',
        editIndex: -1,
        template: 't_supplier_contacts',
        data: 'contactsList',
        url: g.ctx + '/supplier/contacts/rest/grid'
    },  //供应商银行
    bank: {
        el: '#bankTb', editIndex: -1, template: 't_supplier_bank', data: 'bankList', url: '/supplier/bank/rest/grid'
    }, supplierProductType: {
        el: '#supplierProductTypeTb',
        editIndex: -1,
        template: 't_supplier_product_type',
        data: 'supplierPurchaseCategoryList',
        url: purchaseCategoryUrl,
    }, supplierQualificationType: {
        el: '#qualificationTb',
        editIndex: -1,
        template: 'supplierQualifications',
        data: 'supplierQualificationsList',
        url: qualificationTypeUrl,
    }
};

/**
 * 表格校验提示信息
 * @type {Record<string, {
 *   domestic: string,
 *   foreign: string,
 *   current: string
 * }>}
 */
let validationMessages = {};

//重写4种类型的查询

/**
 * 初始化基本信息页表格参数
 */
function initDataGrid() {
    //联系人
    let supplierContact = 'supplierContact';
    $(tableType[supplierContact]['el']).edatagrid({
        singleSelect: true, height: 200, striped: true, autoSave: true, columns: [[param.idColumn, {
            field: 'contactsType', title: '联系人类型', width: '15%', align: 'left', formatter: function (value, row) {
                return getDicName("supplier_role_type", value);
            }, editor: {
                type: 'combobox', options: {
                    required: true,
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '250',
                    editable: false,
                    data: getDictList("supplier_role_type")
                }
            }
        }, {
            field: 'contactsName', title: '姓名', width: '15%', align: 'left', editor: {
                type: 'textbox', options: {
                    required: true, validType: 'length[0,100]'
                }
            }
        },
            //     {
            //     field: 'contactsMobile', title: '手机', width: '15%', align: 'left', editor: {
            //         type: 'textbox', options: {
            //             validType: 'phoneRex'
            //         }
            //     }
            // },
            {
                field: 'contactsTel', title: '电话', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: true, validType: 'phoneRex'
                    }
                }
            }, {
                field: 'email', title: '邮箱', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        validType: 'email'
                    }
                }
            }]], toolbar: gridToolbar(supplierContact), onEdit: function (index) {
            tableType[supplierProductType].editIndex = index
        }, onSave: function (index, row) {
            if (row.type != 1) {
                $(tableType.supplierContact.el).datagrid('updateRow', {index: index, row: {type: 2}});
            }
        }
    });

    //供应商银行
    let bank = 'bank';
    $(tableType[bank]['el']).edatagrid({
        singleSelect: true, height: 200, striped: true, autoSave: true, columns: [[param.idColumn,
            {
                field: 'companyCode', title: '公司代码', width: '20%', align: 'left', formatter: function (value, row) {
                    return getNecessaryDataName("pc/sys/company/rest/listAll", value)
                }, editor: {
                    type: 'combobox', options: {
                        required: true,
                        valueField: 'companyCode', // 'dicId',
                        textField: 'companyName',  // 'dicTxt',
                        panelHeight: 'auto',
                        editable: false,
                        data: getNecessaryDataList('pc/sys/company/rest/listAll')
                    }
                }
            }
            , {
                field: 'companyName', title: '收款单位', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: '英文全称/外币交易中文全称',
                        required: true, validType: ['companyName']
                    }
                }
            }, {
                field: 'openingBankName', title: '收款银行', width: '12%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: true, validType:['openingBankName'], editable: true, icons: [{
                            iconCls: 'icon-search', handler: function () {
                                let rows = $(tableType[bank]['el']).datagrid("getRows");
                                let openingBankName = $(tableType[bank]['el']).datagrid('getEditor', {
                                    index: tableType[bank].editIndex, field: 'openingBankName'
                                }).target;
                                var inputBankName = openingBankName.textbox("getValue");
                                let url = g.ctx + 'pc/supplier/bankCategory/index?inputBankName=' + inputBankName;
                                var bankSelectDialog = openDialog("bankSelectDialog", url, {
                                    title: '银行信息选择',
                                    width: '80%',
                                    height: '80%',
                                    cache: false,
                                    modal: true,
                                    border: false,
                                    draggable: true,
                                    shadow: false,
                                    onClose: function () {
                                        bankSelectDialog.dialog('destroy');
                                    },
                                    buttons: [{
                                        text: itablei8n.save, handler: function () {
                                            topWin.frames['bankSelectDialog'].chooseRow(function (row) {
                                                bankSelectDialog.dialog('close');
                                                let bankCode1 = $(tableType.bank.el).datagrid('getEditor', {
                                                    index: tableType[bank].editIndex,
                                                    field: 'bankCode'
                                                }).target;
                                                bankCode1.textbox("setValue", row.interbankNumber)
                                                let openingBankName1 = $(tableType.bank.el).datagrid('getEditor', {
                                                    index: tableType[bank].editIndex,
                                                    field: 'openingBankName'
                                                }).target;
                                                openingBankName1.textbox("setValue", row.bankName);
                                                let bankAddress1 = $(tableType.bank.el).datagrid('getEditor', {
                                                    index: tableType[bank].editIndex,
                                                    field: 'bankAddress'
                                                }).target;
                                                bankAddress1.textbox("setValue", row.bankAddress)
                                            });
                                        }
                                    }, {
                                        text: itablei8n.close, handler: function () {
                                            bankSelectDialog.dialog('close');
                                        }
                                    }]
                                })
                            }
                        }]
                    }
                }
            }, {
                field: 'bankAccount', title: '银行账号', width: '13%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: true, validType:['bankAccount']
                    }
                }
            }, {
                field: 'bankCode', title: '银行行号', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: 'CNY交易必填',
                        required: false, validType: ['bankCode']
                    }
                }
            }, {
                field: 'bankAddress', title: '银行地址', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: '外币交易填写英文',
                        required: true, validType: ['bankAddress']
                    }
                }
            }, {
                field: 'bankInterCode', title: '银行国际代码 Swift Code', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: '外币交易必填',
                        required: false, validType: ['bankInterCode']
                    }
                }
            }
        ]], toolbar: gridToolbar(bank), onEdit: function (index) {
            tableType[bank].editIndex = index
        }, onSave: function (index, row) {
            if (row.type != 1) {
                $(tableType.bank.el).datagrid('updateRow', {index: index, row: {type: 2}});
            }
        }
    });

    let supplierProductType = "supplierProductType";
    $(tableType[supplierProductType]['el']).edatagrid({
        singleSelect: true,
        height: 200,
        autoSave: true,
        striped: true,
        method: "GET",
        url: tableType[supplierProductType]['url'] + '&supplierId=' + selfData.supplierId,
        toolbar: [{
            text: '新增', iconCls: 'icon-add', handler: function () {
                tableAddRow('supplierProductType');
            }
        }, {
            text: '删除', iconCls: 'icon-cancel', handler: function () {
                $(tableType[supplierProductType]['el']).edatagrid("cancelRow")
                let rows = $(tableType[supplierProductType]['el']).datagrid("getChecked")
                console.log(rows)
                if (rows.length <= 0) {
                    topWin.layer.msg("请选择要删除的行");
                    return
                }
                if (rows[0].type !== 1) {
                    topWin.layer.msg("请选择新建的行");
                    return
                }
                let rowIndex = $(tableType[supplierProductType]['el']).datagrid("getRowIndex", rows[0])
                $(tableType[supplierProductType]['el']).datagrid("deleteRow", rowIndex)
            }
        }],
        columns: [[{
            field: 'ck',
            checkbox: true
        }, param.idColumn,
            {
                field: 'isFreeze', title: '是否取消', width: '70', align: 'left', formatter: function (value, row) {
                    return parseFloat(value + "") === 1 ? "是" : "否"
                }, editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        required: true,
                        valueField: 'val', // 'dicId',
                        textField: 'txt',  // 'dicTxt',
                        panelHeight: 'auto',
                        editable: false,
                        data: [
                            {val: '1', txt: '是'},
                            {val: '0', txt: '否'}
                        ]
                    }
                }
            }, {
                field: 'purchaseCategoryCode', title: '品类编码', width: '15%', align: 'center', editor: {
                    type: 'textbox', options: {
                        required: true, editable: false, icons: [{
                            iconCls: 'icon-search', handler: function () {
                                //需要把已有的品类拿出来
                                let rows = $(tableType[supplierProductType]['el']).datagrid("getRows");
                                let categoryCodes = rows.map(row => row.purchaseCategoryCode).join(',');
                                let url = g.ctx + 'pc/sys/purchaseCategory/index?select=1';
                                url = url + '&inCodes=' + categoryCodes;
                                var purchaseCategoryDialog = openDialog("purchaseCategoryDialog", url, {
                                    title: '采购品类选择器',
                                    width: '80%',
                                    height: '80%',
                                    cache: false,
                                    modal: true,
                                    border: false,
                                    draggable: true,
                                    shadow: false,
                                    onClose: function () {
                                        purchaseCategoryDialog.dialog('destroy');
                                    },
                                    buttons: [{
                                        text: itablei8n.save, handler: function () {
                                            topWin.frames['purchaseCategoryDialog'].chooseRow(function (row) {
                                                purchaseCategoryDialog.dialog('close');
                                                let productTypeName = $(tableType.supplierProductType.el).datagrid('getEditor', {
                                                    index: tableType[supplierProductType].editIndex,
                                                    field: 'purchaseCategoryName'
                                                }).target;
                                                productTypeName.textbox("setValue", row.firstLevelPurchaseName)
                                                let productType = $(tableType.supplierProductType.el).datagrid('getEditor', {
                                                    index: tableType[supplierProductType].editIndex,
                                                    field: 'purchaseCategoryCode'
                                                }).target;
                                                productType.textbox("setValue", row.firstLevelPurchaseCode)
                                            });
                                        }
                                    }, {
                                        text: itablei8n.close, handler: function () {
                                            purchaseCategoryDialog.dialog('close');
                                        }
                                    }]
                                })
                            }
                        }]
                    }
                }
            }, {
                field: 'purchaseCategoryName', title: '品类名称', width: '15%', align: 'center', editor: {
                    type: 'textbox', options: {
                        readonly: true
                    }
                }
            }, {
                field: 'companyCode', title: '公司', width: '19%', align: 'center', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'companyCode', // 'dicId',
                        textField: 'companyName',  // 'dicTxt',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        data: getNecessaryDataList('pc/sys/company/rest/listAll'),
                        onChange: function (newVal) {
                            if ($(tableType.supplierProductType.el).datagrid('getEditor', {
                                index: tableType[supplierProductType].editIndex, field: 'purchaseOrgCode'
                            }) == null) {
                                return
                            }
                            let purchaseOrgCode = $(tableType.supplierProductType.el).datagrid('getEditor', {
                                index: tableType[supplierProductType].editIndex, field: 'purchaseOrgCode'
                            }).target;
                            initNecessaryData("pc/sys/purchaseOrg/rest/listAll", 'purchaseOrgCode', 'purchaseOrgDesc', {companyCodes: newVal + ',8000'})
                            purchaseOrgCode.combobox("loadData", getNecessaryDataList('pc/sys/purchaseOrg/rest/listAll'))
                            purchaseOrgCode.combobox("clear")
                            purchaseOrgCode.combobox("setValue", "8000");
                        }

                    }
                }, formatter: function (value) {
                    return getNecessaryDataName("pc/sys/company/rest/listAll", value)
                }
            }, {
                field: 'paymentTerms', title: '付款条件', width: '12%', align: 'center', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: true,
                        data: getDictList('payment_method')
                    }
                }, formatter: function (value) {
                    return getDicName('payment_method', value)
                }
            }, {
                field: 'paymentMethod', title: '付款方式', width: '12%', align: 'center', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: true,
                        data: getDictList('payment_way'),
                        onSelect: function (newVal) {
                            setTimeout(function() {
                                // 获取承兑期限编辑器
                                const editor = $(tableType.supplierProductType.el).datagrid('getEditor', {
                                    index: tableType.supplierProductType.editIndex,
                                    field: 'acceptanceMethod'
                                });

                                if (editor) {
                                    const acceptanceCombo = editor.target;
                                    const oldVal = acceptanceCombo.combobox("getValue");

                                    // 银行转账逻辑
                                    if (newVal.code === 'B') {
                                        // 1. 清除承兑期限的值
                                        acceptanceCombo.combobox("clear");
                                        // 2. 设置为非必填
                                        acceptanceCombo.combobox({ required: false });
                                        // 3. 禁用下拉框
                                        acceptanceCombo.combobox('disable');
                                    }
                                    // 承兑汇票逻辑（code='C'）
                                    else if (newVal.code === 'C') {
                                        acceptanceCombo.combobox({ required: true });
                                        acceptanceCombo.combobox('enable');
                                        acceptanceCombo.combobox("setValue", oldVal);
                                    }
                                    // 其他付款方式
                                    else {
                                        // 1. 清除承兑期限的值
                                        acceptanceCombo.combobox("clear");
                                        // 2. 设置为非必填
                                        acceptanceCombo.combobox({ required: false });
                                        // 3. 禁用下拉框
                                        acceptanceCombo.combobox('disable');
                                    }
                                }
                            }, 50);
                        }
                    }
                }, formatter: function (value) {
                    return getDicName('payment_way', value)
                }
            }, {
                field: 'acceptanceMethod', title: '承兑期限', width: '120', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: '200',
                        required: false,
                        editable: true,
                        data: getDictList('supplier_accetp_deadline')
                    }
                }, formatter: function (value) {
                    return getDicName('supplier_accetp_deadline', value)
                }
            }, {
                field: 'currencyCode', title: '币种', width: '7%', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        data: getDictList('currency')
                    }
                }, formatter: function (value) {
                    return getDicName('currency', value)
                }
            }, {
                field: 'taxCode', title: '税率', width: '10%', align: 'center', editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        data: getNecessaryDataList("pc/sys/tax/rest/listAll")
                    }
                }, formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll', value)
                }
            }, {
                field: 'controlSubject',
                title: '<span style="color: red;">*</span>统御科目',
                width: '10%',
                align: 'center',
                editor: {
                    type: 'combobox', options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        data: getDictList('controlling_accounts')
                    }
                },
                formatter: function (value) {
                    return getDicName('controlling_accounts', value)
                }
            }, {
                field: 'purchaseOrgCode', title: '<span style="color: red;">*</span>采购组织', width: '19%', editor: {
                    type: 'combobox', options: {
                        valueField: 'purchaseOrgCode',
                        limitToList: true,
                        textField: 'purchaseOrgDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        readonly: false,
                        data: getNecessaryDataList('pc/sys/purchaseOrg/rest/listAll')
                    }
                }, formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseOrg/rest/listAll', value)
                }
            }, {
                field: 'effectiveTime', title: '有效期', width: '19%', editor: {
                    type: 'datebox',
                    options: {
                        editable: false,
                        parser: function (value) {
                            if (value) {
                                return new Date(value);
                            } else {
                                return new Date();
                            }
                        }
                    }
                }, formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return ''
                }
            }]],
        onEdit: function (index, row) {
            tableType[supplierProductType].editIndex = index
            if (row.state !== 7) {
                if ($(tableType.supplierProductType.el).datagrid('getEditor', {
                    index: tableType[supplierProductType].editIndex, field: 'effectiveTime'
                }) == null) {
                    return
                }
                let effectiveTime = $(tableType.supplierProductType.el).datagrid('getEditor', {
                    index: tableType[supplierProductType].editIndex, field: 'effectiveTime'
                }).target;
                //    effectiveTime.datebox("readonly", true)
            }
        },
        onSave: function (index, row) {
            if (row.type != 1) {
                $(tableType.supplierProductType.el).datagrid('updateRow', {index: index, row: {type: 2}});
            }
        }

    });

    let supplierQualificationType = "supplierQualificationType";
    $(tableType[supplierQualificationType]['el']).edatagrid({
        singleSelect: true,
        height: 200,
        autoSave: true,
        striped: true,
        method: "GET",
        url: tableType[supplierQualificationType]['url'] + '&supplierId=' + selfData.supplierId,
        toolbar: [{
            text: '新增', iconCls: 'icon-add', handler: function () {
                const url = g.ctx + 'pc/supplier/qualification/index?selected=1&codes=SRM_ZZ_002,SRM_ZZ_001,SRM_ZZ_006,SRM_ZZ_035,SRM_ZZ_036,SRM_ZZ_037,SRM_ZZ_038,SRM_ZZ_004,SRM_ZZ_017,SRM_ZZ_016,SRM_ZZ_039,SRM_ZZ_044,SRM_ZZ_045,,SRM_ZZ_046,SRM_ZZ_047,SRM_ZZ_048,SRM_ZZ_049,SRM_ZZ_050,SRM_ZZ_051,SRM_ZZ_052,SRM_ZZ_053,SRM_ZZ_054,SRM_ZZ_055,SRM_ZZ_056,SRM_ZZ_057,SRM_ZZ_058,SRM_ZZ_059,SRM_ZZ_060,SRM_ZZ_061,SRM_ZZ_062,SRM_ZZ_025,SRM_ZZ_019,SRM_ZZ_030'
                const qualificationItemDialog = openDialog('qualificationItemDialog', url, {
                    title: '资质选择',
                    width: '90%',
                    height: '90%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        qualificationItemDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: itablei8n.confirm, handler: function () {
                            topWin.frames['qualificationItemDialog'].getChecked(function (rows) {
                                const tableRows = $(tableType[supplierQualificationType]['el']).datagrid("getRows")
                                const map = {}
                                $.each(tableRows, function (idx, itm) {
                                    map[itm.qualificationCode] = 1
                                })
                                $.each(rows, function (idx, itm) {
                                    let tmpRow = {
                                        qualificationName: itm.name,
                                        qualificationCode: itm.code,
                                        type: 1
                                    }
                                    if (map[itm.code] == undefined) {
                                        $(tableType[supplierQualificationType]['el']).datagrid("appendRow", tmpRow)
                                    }
                                })
                                qualificationItemDialog.dialog('close');
                            });
                        }
                    }, {
                        text: itablei8n.close, handler: function () {
                            qualificationItemDialog.dialog('close');
                        }
                    }]
                });
            }
        }, {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                $(tableType[supplierQualificationType]['el']).edatagrid("saveRow");
                var row = $(tableType[supplierQualificationType]['el']).datagrid("getSelections");
                if (row.length === 1 && row[0].type === 1) {
                    topWin.layer.confirm('您确定要删除吗?', {icon: 3}, function (index) {
                        var rdx = $(tableType[supplierQualificationType]['el']).datagrid("getRowIndex", row[0])
                        $(tableType[supplierQualificationType]['el']).datagrid("deleteRow", rdx)
                        topWin.layer.close(index)
                    })
                } else if (row.length === 1 && row.type !== 1) {
                    topWin.layer.alert("只允许删除新增的资质!", {icon: 2})
                } else {
                    topWin.layer.alert("请选中需要删除资质!", {icon: 2})
                }

            }
        }],
        columns: [[param.idColumn, {
            field: 'fileName', title: '资质证书名称', width: '20%', align: 'left', formatter: function (value, row) {
                if (!row.fileName) {
                    return ''
                }
                return "<a href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>"
            },
            editor: {
                type: 'textbox', options: {
                    editable: false,
                    buttonText: '选择文件',
                    onClickButton(e) {
                        $("#fileUpload .filebox-label").click();
                    }
                }
            }

        }, {
            field: 'qualificationNumber', title: '资质证书编码', width: '15%', align: 'left', editor: {type: 'textbox'}
        }, {
            field: 'qualificationName', title: '资质名称', width: '20%', align: 'left'
        }, {
            field: 'availableStartDate',
            title: '证书生效时间',
            width: '15%',
            align: 'left',
            editor: {type: 'datebox', editable: false}
        }, {
            field: 'availableEndDate',
            title: '证书失效时间',
            width: '15%',
            align: 'left',
            editor: {type: 'datebox', editable: false}
        }, {
            field: 'createTime', title: '创建时间', width: '10%', align: 'left', formatter: function (value) {   //格式化时间
                if (value) {
                    return new Date(value).format("yyyy-MM-dd")
                }
                return value;
            }
        }]],
        onEdit: function (index) {
            tableType[supplierQualificationType].editIndex = index
        },
        onSave: function (index, row) {
            if (row.type != 1) {
                $(tableType.supplierQualificationType.el).datagrid('updateRow', {index: index, row: {type: 2}});
            }
        }

    });

    $(tableType[bank]['el']).datagrid({
        onBeginEdit: function(index){
            const currencyCodeEl = $('#supplierInfo input[comboname="currencyCode"]');
            if (!currencyCodeEl.length) return;
            const currencyCode = currencyCodeEl.combobox('getValue');
            setBankInterCodeReadonly(index, currencyCode);
        }
    });
}

function fileChange() {
    var files = $("#fileInput").filebox("files");
    if (files.length <= 0) {
        return
    }
    var formData = new FormData();
    formData.append('file', files[0]);//默认的文件数据名为“Filedata”
    var index_wait;
    $.ajax({
        url: g.ctx + 'pc/sys/file/rest/upload/file', //单文件上传
        type: 'POST',
        processData: false,
        contentType: false,
        data: formData,
        beforeSend: function () {
            index_wait = topWin.layer.load(0, {  //发送请求前调用load方法
                shade: [0.5, '#fff'],  //0.5透明度的白色背景
            });
        },
        complete: function () {
            topWin.layer.close(index_wait);
            $("#fileInput").filebox("clear");
        },
        success: function (result) {

            $(tableType["supplierQualificationType"].el).edatagrid("endEdit", tableType["supplierQualificationType"].editIndex);
            $(tableType["supplierQualificationType"].el).edatagrid('updateRow', {
                index: tableType["supplierQualificationType"].editIndex,
                row: {
                    fileId: result.id,
                    fileName: result.fileName
                }
            });
            topWin.layer.msg('上传成功', {icon: 1});
        },
        error: function (xhr, status, error) {
            // $(this).filebox('setText','');
            topWin.layer.alert('文件上传失败', {icon: 2})
        }
    });
}

/**
 * 提取表格公共的按钮方法
 * @param tbType 表格类型（枚举类）
 */
function gridToolbar(tbType) {
    return [{
        text: '新增', iconCls: 'icon-add', handler: function () {
            tableAddRow(tbType);
        }
    }, {
        text: '删除', iconCls: 'icon-remove', handler: function () {
            tableDelete(tbType);
        }
    }, {
        text: '取消删除', iconCls: 'icon-redo', handler: function () {
            tableCancel(tbType);
        }
    }]
}

/**
 * 表格删除行
 * @param tbType 表格行编辑参数
 */
function tableDelete(tbType) {
    let param = tableType[tbType];
    let tb = param['el'];
    let editIndex = param['editIndex']
    var a = $(tb).edatagrid('cancelRow');
    let row = $(tb).datagrid('getSelected');
    if (row) {
        let index = $(tb).datagrid('getRowIndex', row);
        //如果删除行的id有值，那么就需要调用后台删除方法删除
        if (row['type'] && row['type'] === 1) {
            $(tb).datagrid('deleteRow', index);
            //删除行的时候，要把编辑行的索引更新
        } else {
            $(tb).datagrid('updateRow', {index: index, row: {type: 3}});
        }
    }
    $(tb).datagrid('clearSelections');
}

/**
 * 获取供应商关联表数据，用于表格数据初始化
 */
function initFollowTableData() {
    var changeVersionId = $(el.changeVersionId).val();
    var supplierId = selfData.supplierId;
    if(changeVersionId != '' && changeVersionId > 0){
        //查询带银行信息version的数据
        let bankUrl = g.ctx + 'pc/supplier/supplierChange/rest/supplierBankVersionWholeList?changeVersionId=' + changeVersionId+'&supplierId='+supplierId;
        $.get(bankUrl, function (data) {
            $(tableType.bank.el).datagrid("loadData", data.rows);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            let responseText = jqXHR.responseText;
            try {
                let parsedResponse = JSON.parse(responseText);
                let msg = parsedResponse.message || '未知错误';
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + msg);
            } catch (e) {
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + responseText);
            }
        });
        //查询联系人version
        let contactsUrl = g.ctx + 'pc/supplier/supplierChange/rest/supplierContactsVersionWholeList?changeVersionId=' + changeVersionId+'&supplierId='+supplierId;
        $.get(contactsUrl, function (data) {
            $(tableType.supplierContact.el).datagrid("loadData", data.rows);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            let responseText = jqXHR.responseText;
            try {
                let parsedResponse = JSON.parse(responseText);
                let msg = parsedResponse.message || '未知错误';
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + msg);
            } catch (e) {
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + responseText);
            }
        });
        //变更附件
        let attachmentUrl = g.ctx + 'pc/supplier/supplierChange/rest/attachmentWholeList?changeVersionId=' + changeVersionId+'&supplierId='+supplierId+'&page=1&rows=10';
        $.get(attachmentUrl, function (data) {
            console.log(data);
            data.rows.forEach(function(item) {
                if(item.type == 1){//供应商名称变更附件
                    $('#supplierNameFileId').val(item.fileId);
                    $('#supplierNameFile').filebox('setText',item.fileName);
                    $('#supplierNameFile').parent('.ui-form-row-column').children('.validatebox-text').click(function () {
                        window.location.href =g.ctx + "pc/sys/file/rest/download/" + item.fileId;
                    })
                }
                if (item.type == 2) {//法人变更附件
                    $('#legalFileId').val(item.fileId);
                    $('#legalFile').filebox('setText',item.fileName)
                    $('#legalFile').parent('.ui-form-row-column').children('.validatebox-text').click(function () {
                        window.location.href =g.ctx + "pc/sys/file/rest/download/" + item.fileId;
                    })
                }
                if(item.type == 3){//结算方式变更附件
                    $('#settlementMethodFileId').val(item.fileId);
                    $('#settlementMethodFile').filebox('setText',item.fileName)
                    $('#settlementMethodFile').parent('.ui-form-row-column').children('.validatebox-text').click(function () {
                        window.location.href =g.ctx + "pc/sys/file/rest/download/" + item.fileId;
                    })
                }
                if(item.type == 4){// 银行信息变更附件
                    $('#supplierBankFileId').val(item.fileId);
                    $('#supplierBankFile').filebox('setText',item.fileName)
                    $('#supplierBankFile').parent('.ui-form-row-column').children('.validatebox-text').click(function () {
                        window.location.href =g.ctx + "pc/sys/file/rest/download/" + item.fileId;
                    })
                }
                if(item.type == 5){//供应商变更申请附件
                    $('#modifyFileId').val(item.fileId);
                    $('#modifyFile').filebox('setText',item.fileName)
                    $('#modifyFile').parent('.ui-form-row-column').children('.validatebox-text').click(function () {
                        window.location.href =g.ctx + "pc/sys/file/rest/download/" + item.fileId;
                    })
                }
            });
        }).fail(function (jqXHR, textStatus, errorThrown) {
            let responseText = jqXHR.responseText;
            try {
                let parsedResponse = JSON.parse(responseText);
                let msg = parsedResponse.message || '未知错误';
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + msg);
            } catch (e) {
                topWin.layer.msg('请求超时，获取表格数据时失败！ ' + responseText);
            }
        });
    }    else if (selfData.supplierId) {
        let query = {};
        //这里判断是否有变更id,有就走其他

        var supplierId = selfData.supplierId;
        query['changeId'] = $(el.changeVersionId).val();
        query['supplierId'] = selfData.supplierId;
        query['templateTableField'] = selfData.templateTableField;
        //查询详情
        $.post(g.ctx + 'pc/supplier/register/rest/follow/table', {
            query: JSON.stringify(query)
        }, function (data) {
            $(tableType.bank.el).datagrid("loadData", data.bankList)
            $(tableType.supplierContact.el).datagrid("loadData", data.contactsList)
        }).error(function (data) {
            let msg = JSON.parse(data['responseText'])['message'];
            topWin.layer.msg('请求超时，获取表格数据时失败！ ' + msg);
        })



    }

}

/**
 * 新增行，并触发行编辑事件
 * @param tbType 表格行编辑参数
 * @param dataRow 增加行数据内容
 */
function tableAddRow(tbType, dataRow) {
    let param = tableType[tbType];
    let tb = $(param['el']);
    debugger
    let data = dataRow ? dataRow : {type: 1,companyCode: '1000'};
    tb.datagrid('appendRow', data);
    let index = tb.datagrid('getRows').length - 1;
    tb.edatagrid("editRow", index)
}

var page = {
    //初始化省市下拉框
    initSelector: function () {
        /**
         * 判断模板中的国家下拉框、省份下拉框、城市下拉框
         */
        let country = $('#supplierInfo input[comboname="country"]');
        let province = $('#supplierInfo input[comboname="province"]');
        let city = $('#supplierInfo input[comboname="city"]');
        let distinct = $('#supplierInfo input[comboname="county"]');
        let currencyCode = $('#supplierInfo input[comboname="currencyCode"]');
        if (country.length) {
            if (province.length) {
                country.combobox({
                    onSelect: function (row) {
                        if (row['CODE']) {
                            province.combobox('clear');
                            province.combobox('setValue', '');
                            province.combobox({
                                prompt: '国家的二级联动框',
                                url: g.ctx + 'pc/sys/area/rest/query',
                                method: 'GET',
                                queryParams: {
                                    pCode: row['CODE']
                                }
                            })
                        }
                    }
                });

                province.combobox({
                    onSelect: function (row) {
                        if (row['code']) {
                            city.combobox('clear');
                            city.combobox('setValue', '');
                            if (city.length > 0) {
                                city.combobox({
                                    prompt: '省份的二级联动框',
                                    url: g.ctx + 'pc/sys/area/rest/query',
                                    method: 'GET',
                                    queryParams: {
                                        pCode: row['code']
                                    },
                                })
                            }
                        }
                    }
                });

                city.combobox({
                    onSelect: function (row) {
                        if (row['code']) {
                            distinct.combobox('clear');
                            distinct.combobox('setValue', '');
                            distinct.combobox({
                                prompt: '城市的二级联动框',
                                url: g.ctx + 'pc/sys/area/rest/query',
                                method: 'GET',
                                queryParams: {
                                    pCode: row['code']
                                },
                            })
                        }
                    }
                });
            }
        }
        if (country.length > 0 && country.combobox('getValue')) {
            province.combobox({
                prompt: '国家的二级联动框', url: g.ctx + 'pc/sys/area/rest/query', method: 'GET', queryParams: {
                    pCode: country.combobox('getValue')
                }
            });
        }

        if (province.length > 0 && province.combobox('getValue')) {
            city.combobox({
                prompt: '省份的二级联动框', url: g.ctx + 'pc/sys/area/rest/query', method: 'GET', queryParams: {
                    pCode: province.combobox('getValue')
                },
            })
        }

        if (currencyCode.length) {
            // 币种下拉框变更事件
            currencyCode.combobox({
                onChange: function(newValue) {
                    $(el.form).form('resetValidation');
                    const editIndex = $(tableType['bank']['el']).datagrid('getRowIndex', $(tableType['bank']['el']).datagrid('getSelected'));
                    if (editIndex >= 0) {
                        setBankInterCodeReadonly(editIndex, newValue);
                    }
                }
            });
        }
    }
}
var submitFlag = 0

/**
 * 供应商变更信息提交
 */
function submitForm(callback) {
    debugger;
    if (submitFlag == 1) {
        return
    }
    if ($(el.form).form('validate')) {
        let obj = selfData.templateTableSet;
        let changeFollowTable = {};

        //先结束所有的行编辑，不然获取不到表格数据
        for (let x in tableType) {
            $(tableType[x]['el']).edatagrid("saveRow")
        }
        for (let x in tableType) {
            if ($(tableType[x]['el']).length > 0) {
                changeFollowTable[tableType[x]['data']] = $(tableType[x]['el']).datagrid('getRows');
            }
        }
        //需要判断changeFollowTable.contactsList数组中的contactsType,contactsName,contactsTel是否都填了，如果有没有填的需要提示
        if (changeFollowTable.contactsList) {
            for (let i = 0; i < changeFollowTable.contactsList.length; i++) {
                if (!changeFollowTable.contactsList[i].contactsType || !changeFollowTable.contactsList[i].contactsName || !changeFollowTable.contactsList[i].contactsTel) {
                    topWin.layer.msg('联系人信息中，联系人类型、联系人姓名、联系人电话不能为空！');
                    return
                }
            }
        }
        //需要判断changeFollowTable.bankList数组中的companyCode,companyName,openingBankName,bankAccount,bankAddress是否都填了，如果有没有填的需要提示
        if (changeFollowTable.bankList) {
            for (let i = 0; i < changeFollowTable.bankList.length; i++) {
                if (!changeFollowTable.bankList[i].companyCode || !changeFollowTable.bankList[i].companyName || !changeFollowTable.bankList[i].openingBankName || !changeFollowTable.bankList[i].bankAccount || !changeFollowTable.bankList[i].bankAddress) {
                    topWin.layer.msg('银行信息中，公司代码、收款单位、收款银行、银行账号、银行地址不能为空！');
                    return
                }
            }
        }
        if($(el.changeVersionId).val() != '' && $(el.changeVersionId).val() >0){
            changeFollowTable.changeVersionId =  $(el.changeVersionId).val();
        }
        changeFollowTable.supplier = $(el.form).serializeJson();
        changeFollowTable.remark = $(el.remark).val();
        if ($(el.oaType).length > 0) {
            changeFollowTable.oaType = $(el.oaType).combobox('getValue');
        }
        if ($(el.isFreeze).length > 0) {
            changeFollowTable.isFreeze = $(el.isFreeze).combobox('getValue');
        }
        if($(el.eliminateFlag).length > 0 ){
            changeFollowTable.eliminateFlag = $(el.eliminateFlag).combobox('getValue');
        }
        if($(el.paymentTerms).length > 0){
            //这里有问题，没有取到值，是空的，是否取值方式不对，要用输入框和的方式取而不是combobox的方式？
            var paymentTerms_ = $(el.paymentTerms).combobox('getValue');
            if(paymentTerms_ == "2"){
                topWin.layer.msg('请选择是否变更供应商账期或者付款方式！');
                return
            }
            changeFollowTable.paymentTerms  = $('#paymentTerms').val();
            // changeFollowTable.paymentTerms = $(el.paymentTerms).combobox('getValue');
            changeFollowTable.executionTime = $(el.executionTime).combobox('getValue');
            if (changeFollowTable.paymentTerms === "1"&& !$('#settlementMethodFileId').val()){
                topWin.layer.alert('请上传结算方式变更附件附件！', {icon: 0});
                return false;
            }
        }
        const curr = changeFollowTable.supplier.currencyCode;
        const bst=changeFollowTable.bankList;
        const isValid = bst.every((bank, index) => {
            if (curr === 'CNY') {
                return bank.bankCode && bank.bankCode.trim() !== '';
            } else {
                return bank.bankInterCode && bank.bankInterCode.trim() !== '';
            }
        });
        if (!isValid) {
            topWin.layer.msg('银行信息验证失败：CNY货币必须填写银行代码，其他货币必须填写银行国际代码');
            return
        }

//把附件全部取出来
        const files = []
        $.each($(".fileId"), function (idx, itm) {
            files.push({
                fileId: $(itm).val(), type: $(itm).data('type')
            })
        })
        changeFollowTable.files = files
//需要校验资质的数据
        const changeFollowTableElement = changeFollowTable[tableType.supplierQualificationType.data];
        let msg = []
        $.each(changeFollowTableElement, function (idx, itm) {
            if (!itm.fileId) {
                msg.push(itm.qualificationName + "附件必须上传")
            }
        })
        if (msg.length > 0) {
            topWin.layer.alert(msg.join("<br>"))
        }
        topWin.layer.load(0, {shade: [0.6, '#fff']});
        submitFlag = 1
        $.ajax({
            url: g.ctx + 'pc/supplier/supplierChange/rest/saveOrUpdate',
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify(changeFollowTable),
            processData: false,
            success: function () {
                topWin.layer.msg('保存成功');
                callback();
            },
            error: function (data) {
                topWin.layer.msg(data.responseJSON.message, {icon: 2});
            },
            complete: function () {
                submitFlag = 0
                topWin.layer.closeAll('loading');

            }
        });
    }

}

$(function () {
    //需要初始化文件框
    var fileInputArray = ['supplierNameFile', 'legalFile', 'settlementMethodFile', 'supplierBankFile', 'modifyFile']
    $.each(fileInputArray, function (idx, itm) {
        singleFileUpload(itm, itm + 'Id')
    })
    selfData.supplierId = $(el.supplierId).val();
    let templateField = $(el.templateFollowTable).val();

    if (templateField != null && templateField != '') {
        let arr = templateField.replace('[', '').replace(']', '').split(',');
        for (let i = 0; i < arr.length; i++) {
            let e = arr[i].trim();
            selfData.templateTableField[i] = e
        }
    }
    initDict('payment_method,controlling_accounts,currency,supplier_role_type,payment_way,supplier_accetp_deadline')
    initNecessaryData("pc/sys/tax/rest/listAll")
    initNecessaryData("pc/sys/company/rest/listAll", 'companyCode', 'companyName')
    initNecessaryData("pc/sys/purchaseOrg/rest/listAll", 'purchaseOrgCode', 'purchaseOrgDesc')
    queryParam = {id: $(el.supplierId).val()};
    page.initSelector()
    // 原始数据
    var originalData = [
        {"code":0,"name":"否"},
        {"code":1,"name":"是"},
        {"code":2,"name":"请选择"}
    ];

// 对数据进行排序（倒序）
    var sortedData = originalData.sort(function(a, b) {
        return b.code - a.code; // 按code字段倒序排序
    });
    $('#paymentTerms').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        value: 2,
        data: sortedData, onLoadSuccess: function () {
            $("#test11").hide();
            $("#test22").hide();
            $("#executionTime").textbox({required:false});
        },
        onSelect:function (d){
            if(d.code == 1){
                $("#executionTimeTd").show();
                $("#executionTimeTd1").show();
                $("#executionTime").textbox({required:true});
                $('#executionTime').combobox("setValue", 0);

                // executionTime
                //  $("#executionTime").textbox("setValue", 1);

            }else{
                $("#executionTimeTd").hide();
                $("#executionTimeTd1").hide();
                $("#executionTime").textbox({required:false});
            }
        }
    });
    initFollowTableData()
    initDataGrid()
    //对表格做自适应宽度，不然会导致列缩进
    layui.use('element', function () {
        let element = layui.element;
        element.on('tab(demo)', function () {
            for (let x in tableType) {
                setTimeout(function () {
                    $(tableType[x]['el']).datagrid('resize')
                }, 2);
            }
        });

        element.init();
    });

    //初始化表单校验规则
    initValidation();
})

$.extend($.fn.validatebox.defaults.rules, {
    /**
     * 手机号码验证
     */
    mobileRex: {
        validator: function (value) {
            let rex = /^1[0-9]\d{9}$/;
            if (rex.test(value)) {
                return true;
            } else {
                return false;
            }
        }, message: '请输入正确手机格式'
    },

    /**
     * 电话号码验证（非严格限制）
     */
    phoneRex: {
        validator: function (value) {
            let rex = /^[0-9-+\s/(/)]{7,20}$/;
            if (rex.test(value)) {
                return true;
            } else {
                return false;
            }
        }, message: '请输入正确电话或手机格式'
    },

    //身份证号码校验
    idCardRex: {
        validator: function (val) {
            let p = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
            if (p.test(val)) {
                return true;
            }
            return false;
        }, message: '请输入正确的身份证号码'
    },

    //传真校验
    numberRex: {
        validator: function (val) {
            let p = /^[A-Za-z0-9]+$/;
            if (p.test(val)) {
                return true;
            }
            return false;
        }, message: '请输入正确的银行账号'
    },
    faxRex: {
        validator: function (val) {
            let p = /^(\d{3,4}-)?\d{7,8}$/;
            if (p.test(val)) {
                return true;
            }
            return false;
        }, message: '请输入正确的传真'
    }
});

/**
 * 设置银行国际代码 Swift Code不可编辑
 * @param index 行下标
 * @param currencyCode 币种
 */
function setBankInterCodeReadonly(index, currencyCode) {
    let editors = $(tableType['bank']['el']).datagrid('getEditors', index);
    editors.forEach(function(editor) {
        if (editor.field === 'bankInterCode') {
            if (currencyCode === "CNY") {
                // 清空值并禁用
                $(editor.target).textbox('clear').textbox('readonly');
            } else {
                $(editor.target).textbox('readonly', false);
            }
        }
    });
}

/**
 * 初始化校验规则
 */
function initValidation() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/validationRuleSetting/rest/getAllValidationBySupplierId',
        data: {
            supplierId: $('#supplierId').val()
        },
        success: function (data) {
            const validationList = transformFieldList(data);
            initValidationRules(validationList);
        },
        error: function (data) {
            layer.msg(data);
        }
    });
}

/**
 * 将字段列表转换为分组后的对象结构
 * @param {Array} fieldList - 原始字段列表
 * @returns {Object} 分组后的字段对象
 */
function transformFieldList(fieldList) {
    const result = {};

    fieldList.forEach(item => {
        const fieldName = item.fieldName;
        const currencyType = item.currencyType || '0'; // 默认设为'0'类型

        // 初始化fieldName对象
        if (!result[fieldName]) {
            result[fieldName] = {};
        }

        // 添加货币类型数据
        result[fieldName][currencyType] = {
            pattern: item.pattern,
            validationMsg: item.validationMsg,
            fixedLength: item.fixedLength,
            maxLength: item.maxLength,
            minLength: item.minLength
            // 可以添加其他需要的属性
        };
    });

    return result;
}

/**
 * 注册所有验证规则
 * @param configs 验证规则
 */
function initValidationRules(configs) {
    // 先储存校验信息
    Object.keys(configs).forEach(fieldName => {
        const currencies = configs[fieldName];
        let validationMessage = {
            domestic: "",
            foreign: "",
            current: ""
        };
        if (currencies["CNY"]) {
            validationMessage.domestic = currencies["CNY"].validationMsg;
        }
        if (currencies["0"]) {
            validationMessage.foreign = currencies["0"].validationMsg;
        }
        validationMessages[fieldName] = validationMessage;
    });
    // 注册规则
    Object.keys(configs).forEach(fieldName => {
        const currencies = configs[fieldName];

        $.fn.validatebox.defaults.rules[fieldName] = {
            validator: function(value) {
                const currencyCodeEl = $('#supplierInfo input[comboname="currencyCode"]');
                if (!currencyCodeEl.length) return true; // 元素不存在则跳过验证
                const currencyCode = currencyCodeEl.combobox('getValue');
                if (!currencyCode) return true; // 如果币种没选先跳过验证

                // 供应商全称含有英文字符时，特殊校验，提交表单时验证
                const supplierEnglishName = $('#supplierInfo input[textboxname="supplierNameEn"]');
                if (fieldName === "supplier_name" && /[a-zA-Z]/.test(value) && supplierEnglishName) {
                    const supplierEnglishNameStr = supplierEnglishName.textbox('getValue');
                    if (supplierEnglishNameStr && supplierEnglishNameStr !== value) {
                        validationMessages[fieldName].current = "此栏使用英文时，需要与英文名称一致"
                        return false;
                    }
                }
                let objKey = "";
                let message = "";
                // 当前币种
                if (currencyCode === "CNY") {
                    // 人民币
                    objKey = "CNY";
                    message = validationMessages[fieldName].domestic;
                } else {
                    // 非人民币
                    objKey = "0";
                    message = validationMessages[fieldName].foreign;
                }
                if (currencies[objKey]) {
                    // 如果有设置校验规则
                    validationMessages[fieldName].current = message;
                    const pattern = "^[" + currencies[objKey].pattern + "]+$"
                    const result = new RegExp(pattern).test(value);
                    if (!result) {
                        return false;
                    }
                    // 前后不允许出现空格
                    // 供应商中文名称、英文名称、简称
                    const notAllowedSideBlankList = ["supplier_name", "short_name", "supplier_name_en"]
                    if (notAllowedSideBlankList.includes(fieldName) && value !== value.trim()) {
                        validationMessages[fieldName].current = "前后不允许有空格";
                        return false;
                    }
                    // 最小长度校验
                    if (currencies[objKey].minLength && value.length < currencies[objKey].minLength) {
                        validationMessages[fieldName].current = "至少输入" + currencies[objKey].minLength + "个字符";
                        return false;
                    }
                    // 最大长度校验
                    if (currencies[objKey].maxLength && value.length > currencies[objKey].maxLength) {
                        validationMessages[fieldName].current = "至多输入" + currencies[objKey].maxLength + "个字符";
                        return false;
                    }
                    // 固定长度校验
                    if (currencies[objKey].fixedLength && value.length !== currencies[objKey].fixedLength) {
                        validationMessages[fieldName].current = "只能" + currencies[objKey].fixedLength + "个字符";
                        return false;
                    }
                }
                // 当前币种未设置时不校验
                return true;

            },
            get message() {
                return validationMessages[fieldName].current || validationMessages[fieldName].domestic;
            }
        };
    });
}