/**
 * 供应商注册页面
 * @Author NZhang
 * RegisterController
 * supplier/register/list.ftl
 */

let el = {
    firstPart: '#firstPart',
    secondPart: '#secondPart',
    thirdPart: '#thirdPart',
    fourthPart: '#fourthPart',
    fifth: '#fifth',
    enableQuestionnaire: '#enableQuestionnaire',

    supplierId: '#supplierId',
    supplierCode: '#supplierCode',
    agreementVersion: '#agreementVersion',
    agreementTextVersion: '#agreementTextVersion',

    stepDownBtn: '.stepDown-btn',
    stepUpBtn: '.stepUp-btn',

    supplierField: '#supplierField',
    questionField: '#questionField',
    fillFormField: '#fillFormField',
    businessBriefField: '#businessBriefField',
    qualityControlInfoField: '#qualityControlInfoField',
    technicalForceField: '#technicalForceField',

    form: '#form',
    supplierFieldForm: '#supplierFieldForm',
    questionFieldForm: '#questionFieldForm',
    fillFormFieldForm: '#fillFormFieldForm',
    businessBriefFieldForm: '#businessBriefFieldForm',
    qualityControlInfoFieldForm: '#qualityControlInfoFieldForm',
    technicalForceFieldForm: '#technicalForceFieldForm',

    attachmentForm: '#attachmentForm',
    btnFile: '#btn_file',

    supplierAttachmentTable: '#supplierAttachmentTable',

    country: '#country',
    province: '#province',
    city: '#city',

    qualificationTemplate: '#qualificationTemplate',
    qualificationVersion: '#qualificationVersion',

    questionnaireTable: '#questionnaireTable',

    supplierName: '#supplierName',

    templateFollowTable: '#templateFollowTable',
    requiredTemplateFollowTable: '#requiredTemplateFollowTable',
    requiredTemplateFollowTableChinese: '#requiredTemplateFollowTableChinese',
};

/**
 *  模板配置必填关联表对应字段
 */
let requiredAlias = {
    // 供应商质检人员
    t_supplier_quality_control_per: 'qualityControlPer', //供应商销售人员
    t_supplier_pur_org: 'purOrg', // 供应商联系人
    t_supplier_contacts: 'supplierContact', // 供应商银行
    t_supplier_bank: 'bank', // 供应商实验室关键设备
    t_supplier_key_laboratory_equipment: 'keyLaboratoryEquipment', // 产品技术质量执行标准
    t_supplier_product_execution_standard: 'productExecutionStandard', // 供应商主要代理物料
    t_supplier_main_agent_product: 'agentProduct', // 供应商销售情况
    t_supplier_sales_situation: 'salesSituation', // 供应商主要物料
    t_supplier_main_product: 'product', // 供应商主要客户、物料
    t_supplier_main_customer_product: 'customerProduct', // 供应商竞争对手
    t_supplier_competitor: 'competitor', // 供应商资本构成
    t_supplier_shareholder: 'shareholder', // 公司关系
    t_supplier_tykm: 'relationHolder', // 供应商人员统计
    t_supplier_personnel_statistics: 'personnelStatistics', // 供应商人员构成
    t_supplier_staff_constitute: 'staffConstitute', // 供应商行业经验
    t_supplier_industry_experience: 'industryExperience', // 产品生产信息表
    t_supplier_production_info: 'productionInfo', // 主要生产人
    t_supplier_main_producers: 'mainProducers', // 主要设备
    t_supplier_major_equipment: 'majorEquipment',

};

/**
 * 表格参数，在表格添加事件中，表单的name值、表单内容，根据参数渲染页面
 */
let param = {
    //供应商附件
    attachmentClass: {
        id: '',
        fileId: '',
        qualificationCode: '',
        qualificationName: '',
        qualificationNumber: '',
        availableStartDate: '',
        availableEndDate: '',
        remark: '',
        validity: '',//时间必填
        requery: '' //必填

    },

    /**
     * 表格的id列，提取出公共逻辑，用来显示数据是否已经保存
     */
    idColumn: {
        title: '状态', field: 'id', width: '8%', align: 'left', formatter: function (value) {
            if (value) {
                return '<span style="color: green">已保存</span>';
            } else {
                return '<span style="color: grey">未保存</span>';
            }
        }
    },
};

let selfData = {
    indexPart: 0, supplierId: '', attachmentEl: '', agreementVersion: '',

    legal: null, creditNo: null, followTable: {}, combo: {
        //学历
        education: [], //银行国家编码
        bankCountries: [], //银行联系人类型
        supplierRoleType: [], //员工类型、各类员工数量
        companyList: companyList, //公司信息
        supplierStaffType: [], //人员统计、近五年
        perStatisticsYears: [], //销售情况、近五年
        salesSituationYears: [], // 公司关系：公司编码
        borgList: [],
    }, templateTableField: [], templateTableSet: {},

    editType: '',//上一个行编辑的表格
    submitFlag: false,//用来限制提交按钮重复点击
};

/**
 * 表格行编辑类型
 * {el 页面元素；editIndex 行编辑坐标}
 */
let tableType = {
    supplierContact: {//联系人
        el: '#supplierContactTb',
        template: 't_supplier_contacts',
        data: 'contactsList',
        validateField: ['contactsName', 'contactsMobile', 'contactsTel', 'email', 'idCard', 'remark']
    }, bank: {//供应商银行
        el: '#bankTb',
        template: 't_supplier_bank',
        data: 'bankList',
        validateField: ['openingBankName', 'bankAccount', 'cardholderName', 'bankCode', 'companyName', 'companyCode','bankInterCode','bankAddress']
    }
};

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

$(function () {
    layui.use(["laydate", "layer"], function () {
        selfData.supplierId = $(el.supplierId).val();
        let templateField = $(el.templateFollowTable).val();
        let arr = templateField.replace('[', '').replace(']', '').split(',');
        for (let i = 0; i < arr.length; i++) {
            let e = arr[i].trim();
            selfData.templateTableField[i] = e;
            selfData.templateTableSet[e] = 1;
        }
        selfData.agreementVersion = $(el.agreementVersion).val();

        //根据当前时间 初始化人员统计、销售情况 年份下拉框数据
        let now = new Date();
        let year = now.getFullYear();
        for (let i = 0; i < 5; i++) {
            let row = {value: year};
            selfData.combo.perStatisticsYears.push(row);
            selfData.combo.salesSituationYears.push(row);
            year--;
        }
        if ($("#agreeFlag").val() == 1) {
            $(".wrap").eq(0).hide();
            $(".wrap").eq(1).show();
        }
        step1();

        initDictData();

        //初始化下拉框
        initSelector();

        //初始化事件绑定
        initEvent();

        //初始化日期控件
        initDateBox();

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

        initNecessaryData("pc/sys/company/rest/listAll");
        //供应商字段自动保存
        supplierFieldAutoSave();

    });

});

/**
 * 页面数据初始化
 */
function initData() {
    /**
     * 供应商数据根据征信数据自动补全
     */
    let supplierNameEl = $('input[textboxname="supplier_name"]');
    if (supplierNameEl.length > 0) {
        let supplierName = supplierNameEl.textbox('getValue');
        if (supplierName) {
            //如果供应商社会信用代码没有值的时候才会调用自动填信息
            let creditNo = $('input[textboxname="credit_no"]');
            if (creditNo.length === 0 || !creditNo.textbox('getValue')) {
                getSupplierCredit(supplierName);
            }
        }
    }
    //对表格做自适应宽度，不然会导致列缩进
    var i = 0;
    for (let x in tableType) {
        if (selfData.templateTableSet[tableType[x]['template']]) {
            setTimeout(function () {
                $(tableType[x]['el']).datagrid('resize');
            }, 1);
        }
    }
}

/**
 * 获取供应商关联表数据，用于表格数据初始化
 */
function initFollowTableData(call) {
    /**
     * 判断供应商id是否有值，如果有值，则查找供应商关联表的数据
     */
    if (selfData.supplierId) {
        let query = {};
        query['supplierId'] = selfData.supplierId;
        query['templateTableField'] = selfData.templateTableField;

        $.post(g.ctx + 'pc/supplier/register/rest/follow/table', {
            query: JSON.stringify(query)
        }, function (data) {
            selfData.followTable = data;
            for (let x in tableType) {
                if (selfData.templateTableSet[tableType[x]['template']]) $(tableType[x]['el']).datagrid('loadData', {rows: data[tableType[x]['data']]});
            }
            if (call !== undefined) {
                call()
            }
        }).error(function (data) {
            let msg = JSON.parse(data['responseText'])['message'];
            layer.msg('请求超时，获取表格数据时失败！ ' + msg);
        })
    } else {
        //供应商id没有数据，不会走loadSuccess的方法，所以在这里加限制
        //“供应商联系人”业务联系人必填
        if ($(tableType.supplierContact['el']).length) {
            let rows = $(tableType.supplierContact['el']).datagrid('getRows');
            addSupplierConcat(rows);
        }
        if ($(tableType.bank['el']).length) {
            let rows = $(tableType.bank['el']).datagrid('getRows');
            addSupplierBank(rows);
        }
    }
}

function addSupplierBank(rows) {

    if (rows.length == 0) {
        tableAddRow('bank', {
            id: '',
            companyCode:'1000'
        });
        $(tableType['bank'].el).edatagrid("editRow", 0)
    }
}

function addSupplierConcat(rows) {

    let intArray = ["12", "1", "4", "10", "5", "2"];

    if (rows.length == 0) {
        for (let i = 0; i < intArray.length; i++) {
            tableAddRow('supplierContact', {
                id: '', contactsType: '12', contactsType: intArray[i]
            });

        }
        $(tableType['supplierContact'].el).edatagrid("editRow", 0)

    }
}

/**
 * 获取注册页面中的字典数据，用于下拉框渲染
 * 根据表格配置判断需要加载哪些字典数据
 */
function initDictData() {
    let obj = selfData.templateTableSet, query = {};
    let dictTypeList = [];
    //质检人员
    if (obj['t_supplier_quality_control_per']) {
        dictTypeList.push('education');//学历
    }
    if (obj['t_supplier_bank']) {
        dictTypeList.push('bankCountries');//银行国家
    }
    if (obj['t_supplier_contacts']) {
        dictTypeList.push('supplierRoleType');//联系人类型
    }
    if (obj['t_supplier_staff_constitute']) {
        dictTypeList.push('supplierStaffType');//员工类型、各类员工数量
    }
    query['dictTypeList'] = dictTypeList;
    $.post(g.ctx + 'pc/supplier/register/rest/dict/data', {
        query: JSON.stringify(query)
    }, function (data) {
        for (let x in data) {
            selfData.combo[x] = data[x];
        }
        initDataGrid();
    }).error(function (data) {
        let msg = JSON.parse(data['responseText'])['message'];
        layer.msg('请求超时，获取表格数据时失败！ ' + msg);
    }).complete(function () {
        if (selfData.agreementVersion) {
            $(".wrap").eq(0).hide();
            $(".wrap").eq(1).show();
            initData();
        }
        initFollowTableData();
    })
}

/**
 * 根据供应商名称带入征信信息
 * @param supplierName 供应商名称
 */
function getSupplierCredit(supplierName) {
    let query = [];
    query.push({code: "E_007_0501", requestParams: {entName: supplierName}},/*主数据*/
        {code: "E_007_0901", requestParams: {entName: supplierName, pageNo: 1, pageSize: 200}},/*股东信息*/
        {
            code: "E_007_0601", requestParams: {entName: supplierName, pageNo: 1, pageSize: 200}
        }/*主要成员*/);

    layer.load(0);
    $.ajax({
        type: "POST",
        url: '/credit/getCreditInfoByCodes',
        data: {query: JSON.stringify(query)},
        success: function (data) {
            if (data.data) {
                let supplierInfo = JSON.parse(data.data['E_007_0501']).data;
                let shareholder = JSON.parse(data.data['E_007_0601']).data;
                let members = JSON.parse(data.data['E_007_0901']).data;

                if (supplierInfo && credit) {
                    /**
                     * 法人信息需要额外保存起来。提交的时候不可以更改法人信息
                     */
                    selfData.legal = credit['legalName'];
                    selfData.creditNo = credit['creditCode'];
                    /**
                     * 把征信信息带入到主数据中
                     */
                    for (let e in credit) {
                        let name = credit[e];
                        if (name == "short_name") {
                            continue;
                        }
                        let text = supplierInfo[e];
                        //如果是省份，配置的是字典值，需要从系统的字典中取到字典值，做映射
                        if (name === 'province') {
                            if ($('input[textboxname="province"]').length > 0) {
                                $.post('/dic/getDicByType', {type: 'province'}, function (data) {
                                    for (let i = 0; i < data.length; i++) {
                                        let a = data[i];
                                        if (a['dicTxt'] === text) {
                                            $('input[textboxname="province"]').combobox('setValue', a['dicCode']);
                                            break;
                                        }
                                    }
                                })

                            }
                        } else {
                            if ($('input[textboxname="' + name + '"]').length > 0) {
                                $('input[textboxname="' + name + '"]').textbox('setValue', text);
                            }
                        }
                    }
                    /**
                     * 对时间格式额外处理
                     */
                    for (let e in creditDate) {
                        let name = creditDate[e];
                        let text = supplierInfo[e];
                        if ($('input[textboxname="' + name + '"]').length > 0 && text) {
                            $('input[textboxname="' + name + '"]').textbox('setValue', text.substring(0, 10));
                        }
                    }
                    /**
                     * 对文本格式额外处理
                     */
                    for (let e in creditText) {
                        let name = creditText[e];
                        let text = supplierInfo[e];
                        if ($('textarea[name="' + name + '"]').length > 0 && text) {
                            $('textarea[name="' + name + '"]').text(text);
                        }
                    }
                }
                if (shareholder && $(el.supplierContactTable).length > 0) {
                    let html = '';
                    for (let i = 0, length = shareholder['list'].length; i < length; i++) {
                        let obj = shareholder['list'][i];

                        html += '<tr>' + '<td><input type="checkbox"><input type="hidden" name="id"></td>' + '<td><input class="easyui-textbox" data-options="readonly:true" name="contactsType" value="' + obj['position'] + '"></td>' + '<td><input class="easyui-textbox" data-options="readonly:true" name="contactsName" value="' + obj['name'] + '"></td>' + '<td><input class="easyui-textbox" data-options="validType:\'phoneRex\'" name="contactsMobile" ></td>' + '<td><input class="easyui-textbox" name="contactsTel" data-options="validType:\'phoneRex\',required:true" ></td>' + '<td><input class="easyui-textbox" name="email" data-options="validType:\'email\',required:true" ></td>' + '<td><input class="easyui-textbox" data-options="validType:\'idCardRex\'" name="idCard" ></td>' + '</tr>'
                    }
                    $(el.supplierContactTable).find('tbody').html(html);
                    $.parser.parse($(el.supplierContactTable).find('tbody'));
                }
                if (members && $(el.shareholderTable).length > 0) {
                    let html = '';
                    for (let i = 0, length = members['list'].length; i < length; i++) {
                        let obj = members['list'][i];

                        html += '<tr>' + '<td><input type="checkbox"><input type="hidden" name="id"></td>' + '<td><input class="easyui-textbox" data-options="readonly:true" name="name" value="' + obj['shareName'] + '"></td>' + '<td><input class="easyui-numberbox" data-options="readonly:true" data-options="required:true,min:0,max:1000000000"' + ' name="supportMoney" value="' + obj['amount'] + '"></td>' + '<td><input class="easyui-numberbox" name="equity" data-options="required:true,min:0.1,max:100,precision:1"' + ' value="' + obj['capitalProportion'] + '"></td>' + '<td><input class="easyui-textbox" name="remark" ></td>' + '</tr>'
                    }
                    $(el.shareholderTable).find('tbody').html(html);
                    $.parser.parse($(el.shareholderTable).find('tbody'));
                }
            }

            layer.closeAll('loading');
        },
        error: function (data) {
            layer.closeAll('loading');
        }
    })
}

/**
 * 初始化事件绑定
 */
function initEvent() {

    var enableQuestionnaire = $(el.enableQuestionnaire).val();

    //点击下一步，进入下一个节点
    $(el.stepDownBtn).click(function () {
        switch (selfData.indexPart) {
            case 0:
                saveFollowTable(1);
                break;
            case 1:
                if (enableQuestionnaire == 1) {
                    saveFollowTable(2);
                } else {
                    saveFollowTable(3);
                }

                break;
            case 2:
                saveFollowTable(3);
                break;
            case 3:
                selfData.indexPart++;
                loadLayTab(selfData.indexPart, 1);
                break;
            default:
                selfData.indexPart++;
                loadLayTab(selfData.indexPart, 1);

        }
    });

    //点击上一步，回到上一个节点
    $(el.stepUpBtn).click(function () {
        selfData.indexPart--;
        loadLayTab(selfData.indexPart, 0);
    });

    //附件保存
    $(el.btnFile).change(function () {
        if ($(this).val) {

            let attachment = {};
            attachment.supplierId = selfData.supplierId;
            attachment.qualificationTemplateCode = $(el.qualificationTemplate).val();
            attachment.qualificationTemplateVersion = $(el.qualificationVersion).val();

            attachment.id = $(selfData.attachmentEl).find('input[name="id"]').val();
            attachment.fileId = $(selfData.attachmentEl).find('input[name="fileId"]').val();
            attachment.qualificationCode = $(selfData.attachmentEl).find('input[name="qualificationCode"]').val();
            attachment.qualificationName = $(selfData.attachmentEl).find('input[name="qualificationName"]').val();
            attachment.qualificationNumber = $(selfData.attachmentEl).find('input[name="qualificationNumber"]').val();
            attachment.availableStartDate = $(selfData.attachmentEl).find('input[name="availableStartDate"]').val();
            attachment.availableEndDate = $(selfData.attachmentEl).find('input[name="availableEndDate"]').val();

            let formData = new FormData();
            //⑥获取files
            let files = $(this)[0].files[0];
            //⑦将name 和 files 添加到formData中，键值对形式
            formData.append("file", files);
            formData.append('attachment', JSON.stringify(attachment));

            layer.load(0);
            $.ajax({
                url: g.ctx + 'pc/sys/file/rest/upload/file', type: 'POST', data: formData, processData: false,// ⑧告诉jQuery不要去处理发送的数据
                contentType: false, // ⑨告诉jQuery不要去设置Content-Type请求头
                beforeSend: function () {
                    //⑩发送之前的动作

                }, success: function (obj) {
                    $(selfData.attachmentEl).find('input[name="id"]').val(obj.id);
                    $(selfData.attachmentEl).find('input[name="fileId"]').val(obj.id);
                    let span = $(selfData.attachmentEl).find('.file-name');
                    span.html(obj.fileName);
                    span.attr('title', obj.fileName);

                    layer.closeAll('loading');
                }, error: function (responseStr) {
                    let message = responseStr['responseJSON']['message'];
                    if (message) {
                        layer.msg(message);
                    } else {
                        layer.msg('附件上传出错');
                    }
                    layer.closeAll('loading');
                }
            });

        }
    });

    //附件生效时间 > 失效时间设置
    $('#supplierAttachmentTable input[textboxname="availableStartDate"]').datebox({
        onSelect: function (beginDate) {
            let start = $(this);
            $(start.parents('tr').find('input[textboxname="availableEndDate"]')[0]).datebox('calendar').calendar({
                validator: function (date) {
                    return beginDate <= date;
                }
            })
        }
    });
    $('#supplierAttachmentTable input[textboxname="availableEndDate"]').datebox({
        onSelect: function (endDate) {
            let end = $(this);
            $(end.parents('tr').find('input[textboxname="availableStartDate"]')[0]).datebox('calendar').calendar({
                validator: function (date) {
                    return endDate >= date;
                }
            })
        }
    });
}

/**
 * 初始化基本信息页表格参数
 */
function initDataGrid() {
    //联系人
    let supplierContact = 'supplierContact';
    $(tableType[supplierContact]['el']).edatagrid({
        singleSelect: true,
        autoHeight: true,
        striped: true,
        autoSave: true,
        data: selfData.followTable['contactsList'],
        columns: [[param.idColumn, {
            field: 'contactsType', title: '联系人类型', width: '12%', align: 'left', formatter: function (value, row) {
                for (var i = 0; i < selfData.combo.supplierRoleType.length; i++) {
                    if (selfData.combo.supplierRoleType[i].code === value) {
                        return selfData.combo.supplierRoleType[i].name;
                    }
                }
                return '';
            }, editor: {
                type: 'combobox', options: {
                    required: true,
                    valueField: 'code',
                    textField: 'name',
                    panelHeight: '250',
                    limitToList: true,
                    editable: false,
                    data: selfData.combo.supplierRoleType
                }
            }
        }, {
            field: 'contactsName', title: '姓名', width: '20%', align: 'left', editor: {
                type: 'textbox', options: {
                    required: true, prompt: '请输入联系人姓名', validType: 'length[0,100]'
                }
            }
        },
            //     {
            //     field: 'contactsMobile', title: '手机', width: '15%', align: 'left', editor: {
            //         type: 'textbox', options: {
            //             required: true, validType: 'phoneRex'
            //         }
            //     }
            // },
            {
                field: 'contactsTel', title: '电话', width: '20%', align: 'left', editor: {
                    type: 'textbox', options: {
                        validType: 'phoneRex', required: true,
                        onChange:function(value){
                            var _trim = $.trim(value);
                            $("#contactsTel").textbox("setValue", _trim);

                        }
                    }
                }
            }, {
                field: 'email', title: '邮箱', width: '20%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: true, validType: 'email',
                        onChange:function(value){
                            var _trim = $.trim(value);
                            $("#email").textbox("setValue", _trim);
                        }
                    }
                }
            },  {
                field: 'remark', title: '备注', width: '20%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: false, prompt: '请输入联系人备注', validType: 'length[0,100]'
                    }
                }
            }]],
        height: 250,
        toolbar: gridToolbar(supplierContact),
        onEdit: function (index) {
            tableType[supplierContact]['editIndex'] = index;
        },
        onSave: function () {
            tableType[supplierContact]['editIndex'] = -1;
        },
        onLoadSuccess: function (data) {
            addSupplierConcat(data["rows"]);

        }
    });

    //供应商银行
    let bank = 'bank';
    $(tableType[bank]['el']).edatagrid({
        singleSelect: true, autoHeight: true, striped: true, autoSave: true, columns: [[param.idColumn, {
            field: 'companyCode',title: '公司代码', width: '20%', align: 'left', formatter: function (value, row) {
                for (var i = 0; i < selfData.combo.companyList.length; i++) {
                    if (selfData.combo.companyList[i].companyCode === value) {
                        return selfData.combo.companyList[i].companyName;
                    }
                }
                return '';
            }, editor: {
                type: 'combobox', options: {
                    required: true,
                    valueField: 'companyCode',
                    textField: 'codeWithDesc',
                    limitToList: true,
                    panelHeight: '250',
                    editable: false,
                    data: selfData.combo.companyList
                    // data:getNecessaryDataName('pc/sys/company/rest/listAll')
                }
            }
        }, {
            field: 'companyName', title: '收款单位', width: '15%', align: 'left', editor: {
                type: 'textbox', options: {
                    prompt: '英文全称/外币交易中文全称',
                    required: true, validType: ['length[0,100]', 'companyName']
                }
            }
        },/* 初始手动输入{
            field: 'openingBankName', title: '收款银行', width: '12%', align: 'left', editor: {
                type: 'textbox', options: {
                    prompt:'外币交易填写英文',
                    required: true, validType: 'length[0,100]'
                }
            }
        }*/
            {
                field: 'openingBankName', title: '收款银行', width: '12%', align: 'left', editor: {
                    type: 'textbox', options: {
                        required: true, validType:['openingBankName'], editable: true, icons: [{
                            iconCls: 'icon-search', handler: function () {
                                let openingBankName = $(tableType[bank]['el']).datagrid('getEditor', {
                                    index: tableType[bank]['editIndex'], field: 'openingBankName'
                                }).target;
                                var inputBankName = openingBankName.textbox("getValue");

                                layer.open({
                                    title: "银行信息选择",
                                    type: 2,
                                    area: ['600px', '550px'],
                                    content: g.ctx + 'pc/supplier/bankCategory/index?inputBankName=' + inputBankName,
                                    btn: ['选择', '关闭'],
                                    yes: function (index, layero) {
                                        //   var body = layer.getChildFrame('body', index);

                                        var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("bankNameHidden").value;
                                        var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("codeHidden").value;
                                        var bankAddr = $(layero).find("iframe")[0].contentWindow.document.getElementById("bankAddressHidden").value;

                                        if (name != undefined && code != '') {

                                            let bankCode = $(tableType[bank]['el']).datagrid('getEditor', {
                                                index: tableType[bank]['editIndex'], field: 'bankCode'
                                            }).target;
                                            bankCode.textbox("setValue", code);
                                            let bankName = $(tableType[bank]['el']).datagrid('getEditor', {
                                                index: tableType[bank]['editIndex'], field: 'openingBankName'
                                            }).target;
                                            bankName.textbox("setValue", name);

                                            let address = $(tableType[bank]['el']).datagrid('getEditor', {
                                                index: tableType[bank]['editIndex'], field: 'bankAddress'
                                            }).target;
                                            address.textbox("setValue", bankAddr);

                                            layer.close(index);
                                        } else {
                                            layer.alert("未选择", {icon: 2})
                                        }
                                    },
                                });
                            }
                        }]
                    }
                }
            }
            , {
                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: ['length[0,100]', 'bankCode'],
                        readonly:true
                    }
                }
            }, {
                field: 'bankAddress', title: '银行地址', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: '外币交易填写英文',
                        required: true, validType: ['length[0,100]','bankAddress']
                    }
                }
            }, {
                field: 'bankInterCode', title: '银行国际代码 Swift Code', width: '15%', align: 'left', editor: {
                    type: 'textbox', options: {
                        prompt: '外币交易必填',
                        required: false, validType: ['length[0,100]','bankInterCode']
                    }
                }
            }
        ]],
        height: 250,
        toolbar: gridToolbar(bank), onEdit: function (index) {
            tableType[bank]['editIndex'] = index;
        }, onSave: function () {
            tableType[bank]['editIndex'] = -1;
        }, onLoadSuccess: function (data) {
            var rows = $(tableType[bank]['el']).datagrid('getRows');
            if (rows.length == 0) {
                $(tableType[bank]['el']).datagrid('appendRow', {
                    id: ''
                });
                setTimeout(function () {
                    $(tableType[bank]['el']).datagrid("resize")
                }, 100)
            }
        }
    });

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

// 手动验证指定行中的指定字段
function validateField(table) {
    var isValid = $(tableType[table]['el']).datagrid('validateRow', tableType[table]['editIndex']);
    if (isValid) {
        if (tableType[table]['editIndex'] !== -1 && tableType[table]['editIndex'] !== undefined) {
            $.each(tableType[table]['validateField'], function (idx, itm) {
                if (!isValid) {
                    return false
                }
                var value = $(tableType[table]['el']).datagrid('getEditor', {
                    index: tableType[table]['editIndex'],
                    field: itm
                }).target;
                isValid = $(value).validatebox('isValid');
            })
        }
    }
    return isValid;
}

/**
 * 供应商字段自动保存
 */
function supplierFieldAutoSave() {
    $('#supplierField input.easyui-textbox').textbox({
        onChange: function (newValue, oldValue) {
            if ($(this).textbox('isValid')) supplierInfoAutoSave(this, newValue, oldValue);
        }
    });
    $('#supplierField input.easyui-combobox').combobox({
        onChange: function (newValue, oldValue) {
            if ($(this).combobox('isValid')) supplierInfoAutoSave(this, newValue, oldValue);
        }
    });

    $('#supplierField input.easyui-combogrid').combogrid({
        onChange: function (newValue, oldValue) {
            if ($(this).combobox('isValid')) supplierInfoAutoSave(this, newValue, oldValue);
        }
    });

    $('#supplierField input.easyui-numberbox').numberbox({
        onChange: function (newValue, oldValue) {
            if ($(this).numberbox('isValid')) supplierInfoAutoSave(this, newValue, oldValue);
        }
    });
    $('#supplierField input.easyui-datebox').datebox({
        onChange: function () {
            if ($(this).datebox('isValid')) supplierInfoAutoSave(this);
        }
    });

    $('#supplierField textarea').change(function (x) {
        let fieldName = $(this).attr("name")
        let fieldValue = $(this).val();
        let supplierId = selfData.supplierId;
        $.ajax({
            url: g.ctx + 'pc/supplier/register/rest/auto/save', type: 'post', data: {
                supplierId: supplierId, fieldName: fieldName, fieldValue: fieldValue
            }, success: function (data) {

            }, error: function (data) {
                let obj = data.responseText;
                layer.msg(JSON.parse(obj).message);
            }
        })
    });
}

/**
 * 供应商信息自动保存
 * @param dom dom元素
 * @param newValue 新值
 * @param oldValue 旧值
 */
function supplierInfoAutoSave(dom, newValue, oldValue) {

    //供应商id为空，不发送请求
    let supplierId = selfData.supplierId;
    if (supplierId && supplierId !== '') {
        let fieldName = $(dom.nextElementSibling).find('input')[1].name;
        let fieldValue = dom.value;
        if (fieldValue) {
            $.ajax({
                url: g.ctx + 'pc/supplier/register/rest/auto/save', type: 'post', data: {
                    supplierId: supplierId, fieldName: fieldName, fieldValue: fieldValue
                }, success: function (data) {

                }, error: function (data) {
                    let obj = data.responseText;
                    layer.msg(JSON.parse(obj).message);
                    $(dom).textbox('setValue', oldValue);
                }
            })
        }
    }
}

/**
 * 供应商相关信息自动保存，此方法通过实体类做映射
 * @param dom 传入元素this
 * @param url 后台请求地址
 */
function supplierFollowAutoSave(dom, url) {
    let obj = {};
    //供应商id为空，不调用自动保存方法
    let supplierId = selfData.supplierId;
    if (supplierId && supplierId !== '') {
        let fieldName = $(dom.nextElementSibling).find('input')[1].name;
        let fieldValue = dom.value;
        obj.supplierId = supplierId;
        obj[fieldName] = fieldValue;
        if (fieldValue) {
            $.ajax({
                url: url, type: 'post', data: obj, success: function (data) {

                }, error: function (data) {
                    let obj = data.responseText;
                    layer.msg(JSON.parse(obj).message);
                }
            })
        }
    }
}

//初始化省市下拉框
// function initSelector() {
//     /**
//      * 判断模板中的国家下拉框、省份下拉框、城市下拉框
//      */
//     let province = $('#supplierField input[comboname="province"]');
//     let city = $('#supplierField input[comboname="city"]');
//
//
// }

/**
 * 控制lay tab页显示隐藏
 * @param pagIndex 当前lay tab页索引
 * @param type 0 向上翻页，1 向下翻页
 */
function loadLayTab(pagIndex, type) {
    let lis = $('.step li');
    if (type === 1) {
        $(lis.eq(pagIndex)).addClass('on');
    } else {
        $(lis.eq(pagIndex + 1)).removeClass('on');
    }

    var enableQuestionnaire = $(el.enableQuestionnaire).val();
    switch (pagIndex) {
        case 0:
            if (enableQuestionnaire == 1) {
                $(el.thirdPart).hide();
                $(el.secondPart).show();
            } else {
                $(el.fourthPart).hide();
                $(el.secondPart).show();
            }

            break;
        case 1:

            if (enableQuestionnaire == 1) {
                $(el.fourthPart).hide();
                $(el.secondPart).hide();
                $(el.thirdPart).show();
            } else {
                $(el.fourthPart).show();
                $(el.secondPart).hide();
            }
            break;
        case 2:

            if (enableQuestionnaire == 1) {
                $(el.thirdPart).hide();
                $(el.fifth).hide();
                $(el.fourthPart).show();
            } else {
                $(el.fourthPart).hide();
                $(el.fifth).show();
            }
            break;
        case 3:

            if (enableQuestionnaire == 1) {
                $(el.fourthPart).hide();
                $(el.fifth).show();
            } else {
                $(el.fifth).hide();
                $(el.fourthPart).show();
            }

            break;
        case 4:

            if (enableQuestionnaire == 1) {
                $(el.fifth).hide();
                $(el.fourthPart).show();
            } else {
                $(el.fifth).hide();
                $(el.fourthPart).show();
            }
        default:

    }

}

function step1() {
    $(".step1-btn").click(function () {
        $(".wrap").eq(0).hide();
        $(".wrap").eq(1).show();
    });

    $(".my-checkbox").change(function () {
        if ($(this).is(':checked')) {
            $(".step2-btn").removeClass("layui-btn-disabled");
            $(".step2-btn").on("click", function () {
                if (selfData.supplierId) {
                    let agreementTextVersion = $(el.agreementTextVersion).val();
                    layer.load(2);
                    $.post(g.ctx + 'pc/supplier/register/rest/agreement', {
                        id: selfData.supplierId, version: agreementTextVersion
                    }, function (data) {
                        layer.closeAll('loading');
                        $(".wrap").eq(0).hide();
                        $(".wrap").eq(1).show();

                        //页面数据初始化
                        initData();

                        $('#tab').tabs({
                            border: false, plain: true, onSelect: function (title) {

                            }
                        });
                    });
                } else {
                    $(".wrap").eq(0).hide();
                    $(".wrap").eq(1).show();
                    selfData.agreementVersion = $(el.agreementTextVersion).val();
                    //页面数据初始化
                    initData();
                    $('#tab').tabs({
                        border: false, plain: true, onSelect: function (title) {
                        }
                    });
                }

            });
        } else {
            $(".step2-btn").off("click");
            $(".step2-btn").addClass("layui-btn-disabled");
        }
    });
}

/**
 * 保存相关表
 * @param step
 */
function saveFollowTable(step) {
    let supplierId = $(el.supplierId).val();
    if (step === 3) {
        if (selfData.submitFlag) {
            return;
        }
        selfData.submitFlag = true;
    }

    let formData = {};
    formData.supplierId = supplierId;
    formData.agreementVersion = selfData.agreementVersion;
    formData.qualificationTemplate = $(el.qualificationTemplate).val();
    formData.qualificationVersion = $(el.qualificationVersion).val();
    let result = {};

    switch (step) {
        case 1:
            //第一步 保存基础字段、填表人、商务简述、供应商联系人、竞争对手、主要代理物料、主要客户物料、
            //主要物料、人员统计、销售情况、资质构成、人员构成、银行、销售人员
            result = supplierFollowTableStep(formData, 1);
            break;
        case 2:
            //第二步 保存问卷调查
            result = supplierFollowTableStep(formData, 2);
            break;
        case 3:
            //第三步 保存附件
            result = supplierFollowTableStep(formData, 3);
            break;
        default:
            break;
    }
    if (!result || result.flag === false) {
        return;
    }

    //供应商id为空的情况：type=1.当前页面作为模板查看页面，没有传入供应商id
    //针对这种情况，调用者请遮蔽提交方法
    if (!supplierId && type === 1) {
        if (step === 3) {
            //将步骤状态改成4，并且把第一页和第二页中的数据也取出来
            step = 4;
            supplierFollowTableStep(formData, 1);
            supplierFollowTableStep(formData, 2);
        } else {
            selfData.indexPart++;
            loadLayTab(selfData.indexPart, 1);
            return;
        }
    }
    layer.load(2);
    $.ajax({
        url: g.ctx + 'pc/supplier/register/rest/save/follow', type: 'post', data: {
            supplierFollow: JSON.stringify(formData), step: step
        }, success: function (data) {
            selfData.indexPart++;
            selfData.supplierId = data
            $(el.supplierId).val(selfData.supplierId);
            //需要增加银行和联系人的刷新
            initFollowTableData(function () {
                loadLayTab(selfData.indexPart, 1);
                layer.closeAll('loading');
                selfData.submitFlag = false;
            })

        }, error: function (data) {
            let obj = data.responseText;
            layer.alert(JSON.parse(obj).message);
            layer.closeAll('loading');
            selfData.submitFlag = false;
        }
    });
}

/**
 * 获取供应商相关表数据
 * @param formData 接收数据
 * @param step 步骤，根据页面第几个“提交”按钮触发事件判断返回哪些数据
 */
function supplierFollowTableStep(formData, step) {
    let result = {
        flag: true
    };
    switch (step) {
        case 1:
            /**
             * 如果法人信息是根据征信带过来的，那么就不能更改
             */
            let legalEl = $('input[name="legalName"]');
            if (legalEl.length > 0 && selfData.legal) {
                let legalName = legalEl.prev().textbox('getValue');
                if (legalName !== selfData.legal) {
                    layer.msg('法人代表已征信中为准,不可更改!', {icon: 0});
                    result.flag = false;
                    break;
                }
            }
            /**
             * 如果信用代码不可更改
             */
            let creditNoEl = $('input[name="creditNo"]');
            if (creditNoEl.length > 0 && selfData.creditNo) {
                let creditNo = creditNoEl.prev().textbox('getValue');
                if (creditNo !== selfData.creditNo) {
                    layer.msg('信用代码已征信中为准,不可更改!', {icon: 0});
                    result.flag = false;
                    break;
                }
            }

            //第一步 保存基础字段、填表人、商务简述、供应商联系人、竞争对手、主要代理物料、主要客户物料、
            //主要物料、人员统计、销售情况、资质构成、人员构成、行业经验、质检人员信息、实验室关键设备、产品技术质量执行标准
            //产品生产信息、技术力量、质检信息
            if ($(el.supplierField)) {
                if (!$(el.supplierFieldForm).form('validate')) {
                    layer.msg('基础信息未填写完整!', {icon: 0});
                    result.flag = false;
                    break;
                }
            }

            if ($(el.fillFormField)) {
                if (!$(el.fillFormFieldForm).form('validate')) {
                    layer.msg('供应商填表人未填写完整!', {icon: 0});
                    result.flag = false;
                    break;
                }
                formData.fillFormPer = $(el.fillFormFieldForm).serializeJson();
            }

            if ($(el.businessBriefField)) {
                if (!$(el.businessBriefFieldForm).form('validate')) {
                    layer.msg('供应商商务简述信息未填写完整!', {icon: 0});
                    result.flag = false;
                    break;
                }
                formData.businessBrief = $(el.businessBriefFieldForm).serializeJson();
            }

            //技术力量
            if ($(el.technicalForceField).length > 0) {
                if (!$(el.technicalForceFieldForm).form('validate')) {
                    layer.msg('供应商技术力量信息未填写完整!', {icon: 0});
                    result.flag = false;
                    break;
                }
                formData.technicalForce = $(el.technicalForceFieldForm).serializeJson();
            }

            //质检信息
            if ($(el.qualityControlInfoField).length > 0) {
                if (!$(el.qualityControlInfoFieldForm).form('validate')) {
                    layer.msg('供应商质检信息信息未填写完整!', {icon: 0});
                    result.flag = false;
                    break;
                }
                formData.qualityControlInfo = $(el.qualityControlInfoFieldForm).serializeJson();
            }

            /**
             * 如果供应商id为空，说明是新增的，需要把所有供应商表格数据传到后台
             * 否则，关联表本身就有行编辑保存功能，不需要再向后台传递数据
             */

            let flag = validateField("supplierContact")
            if (!flag) {
                layer.alert("联系人信息不完整")
                result.flag = false
                return result;
            }
            flag = validateField("bank")
            if (!flag) {
                layer.alert("银行信息不完整")
                result.flag = false
                return result;
            }

            result = parseOtherTable();
            // 获取模板必填的关联表数据信息
            let requiredTemplateFollowTable = $('#requiredTemplateFollowTable').val();
            let followTableArr = requiredTemplateFollowTable.split(',');
            let requiredTemplateFollowTableChinese = $('#requiredTemplateFollowTableChinese').val();
            let followTableChineseArr = requiredTemplateFollowTableChinese.split(',');

            if (followTableArr.length > 0) {
                for (var i = 0; i < followTableArr.length; i++) {
                    var tableField = followTableArr[i];
                    var tableFieldChinese = followTableChineseArr[i];
                    var tableId = requiredAlias[tableField];
                    if (tableId != undefined) {
                        var tableRows = $(tableType[tableId].el).datagrid('getRows');
                        // 单独判断供应商银行数据
                        if (tableRows.length == 0) {
                            layer.msg('【' + tableFieldChinese + '】至少填写一条信息哦，请检查！', {icon: 0});
                            result.flag = false;
                            break;
                        }
                    }
                }
            }


            let bankList = result['bankList'];
            let bank_Flag = false;
            for (let i = 0; i < bankList.length; i++) {
                let e = bankList[i];
                if(isEmpty(e['companyCode'])){
                    bank_Flag = true;
                    break;
                }
            }
            if(bank_Flag){
                layer.msg('供应商银行有空明细行需要填写数据');
                return;
            }
            let banCode_Flag = false;
            let currencyCodeEl = $('#supplierField input[comboname="currencyCode"]');
            if (!currencyCodeEl.length) return ;
            const currencyCode = currencyCodeEl.combobox('getValue');
            for (let i = 0; i < bankList.length; i++) {
                let e = bankList[i];
                // CNY货币验证
                if (currencyCode === 'CNY') {
                    if (!e['bankCode'] || e['bankCode'].trim() === '') {
                        banCode_Flag = true;
                        break;
                    }
                }else{
                    if (!e['bankInterCode'] || e['bankInterCode'].trim() === '') {
                        banCode_Flag = true;
                        break;
                    }
                }
            }
            if(banCode_Flag){
                layer.msg('银行信息验证失败：CNY货币必须填写银行代码，其他货币必须填写银行国际代码');
                return;
            }



            let contactsList = result['contactsList'];
            if (!contactsList) {
                layer.msg('联系人中的业务接口人必须添加!');
                result.flag = false;
                return;
            } else {
                let zongFg = true;
                let yeFlag = true;
                let fg = true;
                let pb_Flag = true; //品保联系人 1
                let cw_Flag = true; //财务人员 4
                let qzry_Flag = true;//签章人员 10
                let ywjl_Flag = true;//5, "业务经理"
                let null_Flag = false;//为空校验
                for (let i = 0; i < contactsList.length; i++) {
                    let e = contactsList[i];
                    if(isEmpty(e['contactsType'])){
                        null_Flag = true;
                        break;
                    }
                    if (e['contactsType'] == '2') {
                        zongFg = false;
                        continue;
                    }

                    if (e['contactsType'] == '11') {
                        fg = false;
                        continue;
                    }

                    if (e['contactsType'] == '12') {
                        yeFlag = false;
                        continue;
                    }
                    if (e['contactsType'] == '1') {
                        pb_Flag = false;
                        continue;
                    }
                    if (e['contactsType'] == '4') {
                        cw_Flag = false;
                        continue;
                    }
                    if (e['contactsType'] == '10') {
                        qzry_Flag = false;
                        continue;
                    }
                    if (e['contactsType'] == '5') {
                        ywjl_Flag = false;
                        continue;
                    }

                }
                if(null_Flag){
                    layer.msg('供应商联系人有空明细行需要填写数据');
                    return;
                }
                if (yeFlag) {
                    layer.msg('供应商联系人请添加业务对接人数据');
                    return;
                }
                if (zongFg) {
                    layer.msg('供应商联系人请添加品质经理人员数据');
                    return;
                }
                if (pb_Flag) {
                    layer.msg('供应商联系人请添加品保联系人员数据');
                    return;
                }
                if (cw_Flag) {
                    layer.msg('供应商联系人请添加财务人员数据');
                    return;
                }
                if (qzry_Flag) {
                    layer.msg('供应商联系人请添加签章人员数据');
                    return;
                }
                if (ywjl_Flag) {
                    layer.msg('供应商联系人请添加业务经理人员数据');
                    return;
                }
            }
            for (let x in result) {
                formData[x] = result[x];
            }

            formData.supplier = $(el.supplierFieldForm).serializeJson();
            formData.supplier.id = $(el.supplierId).val();

            break;
        case 2:
            //第二步 保存问卷调查
            if ($(el.questionFieldForm)) {
                let table = $(el.questionnaireTable).find('tbody tr');
                let array = [];
                for (let i = 0; i < table.length; i++) {
                    let obj = {};
                    let tr = table[i];
                    //需要先判断必填项是否填写
                    let questionAnswer = $(tr).find('input.questionAnswer');
                    //需要单独查找选中
                    let answer = $(tr).find('input.questionAnswer:checked');
                    let answer1 = $(tr).find('textarea');
                    let required = $(tr).find('input[name="required"]').val();
                    let answerType = $(tr).find('input[name="answerType"]').val();
                    if (answerType === '3') {
                        if (required === '1' && answer1.length <= 0) {
                            layer.msg(($(tr).find('input[name="questionContent"]').val()) + '未答复');
                            result.flag = false;
                            break;
                        }
                    } else {
                        if (required === '1' && answer.length <= 0) {
                            layer.msg(($(tr).find('input[name="questionContent"]').val()) + '未答复');
                            result.flag = false;
                            break;
                        }
                    }
                    if (answerType === '3') {
                        if (answer1.length > 0) {
                            obj['questionAnswer'] = answer1.val();
                            obj['id'] = $(tr).find('input[name="answerId"]').val();
                            obj['questionCode'] = answer1.attr("name");
                            obj['supplierId'] = selfData.supplierId;
                            array.push(obj);
                        }
                    } else {
                        if (answer.length > 0) {
                            //如果多个是多选，单个是单选，如果是多选需要合并答案
                            if (answer.length > 1) {
                                const vals = []
                                $.each(answer, function (idx, itm) {
                                    vals.push($(itm).val())
                                })
                                obj['questionAnswer'] = vals.join(",");
                            } else {
                                obj['questionAnswer'] = answer.val();
                            }
                            obj['id'] = $(tr).find('input[name="answerId"]').val();
                            obj['questionCode'] = answer.attr("name");
                            obj['supplierId'] = selfData.supplierId;
                            array.push(obj);
                        }
                    }

                }
                formData.questionnaireAnswer = array;
            }
            break;
        case 3:
            //第三步 保存附件
            let attachmentList = getTableRow(el.supplierAttachmentTable, param.attachmentClass);
            let list = [];
            if (attachmentList) {
                attachmentList.some(function (item) {
                    if (item.requery && item.requery === '1') {
                        if (!item.fileId) {
                            layer.msg(item.qualificationName + '必须要上传', {icon: 0});
                            result.flag = false;
                            selfData.submitFlag = false;
                            return true;
                        }
                    }
                    if (item['validity'] && item['validity'] === '1' && item['longTerm'] !== '是') {
                        if (!item['availableStartDate'] || !item['availableEndDate']) {
                            layer.msg(item.qualificationName + '有效时间必填', {icon: 0});
                            result.flag = false;
                            selfData.submitFlag = false;
                            return true;
                        }
                    }
                    if (item.fileId) {
                        list.push(item);
                    }
                });
            }
            formData.attachmentList = list;
            break;
        default:
            break;
    }
    return result;
}
function isEmpty(value) {
    return value == null; // 检查值是否为 null 或 undefined
}
/**
 * 获取表格数据
 * @param elTable 页面表格元素
 * @param paramClass 实体类参数
 * @returns {Array} 返回list
 */
function getTableRow(elTable, paramClass) {
    let list = [];
    let table = $(elTable).find('tbody tr');
    $.each(table, function (index, item) {
        let row = {};
        for (let x in paramClass) {
            let fileValue = $(item).find('input[name="' + x + '"]').val();
            if (fileValue) {
                row[x] = fileValue;
            } else {
                row[x] = $(item).find('select[name="' + x + '"]').val();
            }
        }
        list.push(row);
    });
    return list;
}

/**
 * 文件上传
 */
function uploadFile(type, btn) {

    selfData.attachmentEl = $(btn).parent().parent();
    // 找到包含上传按钮的父节点 <td>
    var td = btn.parentNode;
    // 获取所有 <td> 元素
    var tds = td.parentElement.querySelectorAll('td');
    // 找到第二个 <td> 元素并添加 class="hh"
    tds[1].classList.add('hh');
    // td.classList.add('hh');
    $(el.btnFile).val('');
    $(el.btnFile).click();
}

//上传附件添加新行
function addFile() {
    $('.file-table').append($('#tpl_qualifiTr').html());

    // 添加日期控件
    let laydate = layui.laydate;
    $('.file-table tr:last [name="certificate_effective_time"]').each(function () {
        let self = $(this);
        laydate.render({
            elem: this, trigger: 'click', done: function () {
                self.removeClass('v_error');
            }
        });
    });

    $('.file-table tr:last [name="certificate_expiration_time"]').each(function () {
        let self = $(this);
        laydate.render({
            elem: this, trigger: 'click', done: function () {
                self.removeClass('v_error');
            }
        });
    });
}

/**
 * 初始化日期控件
 */
function initDateBox() {
    let laydate = layui.laydate;
    $('.file-table tr:last [name="certificate_effective_time"]').each(function () {
        let self = $(this);
        laydate.render({
            elem: this, trigger: 'click', done: function () {
                self.removeClass('v_error');
            }
        });
    });

    $('.file-table tr:last [name="certificate_expiration_time"]').each(function () {
        let self = $(this);
        laydate.render({
            elem: this, trigger: 'click', done: function () {
                self.removeClass('v_error');
            }
        });
    });
}

/**
 * 删除资质行
 */
function deleteFile(obj) {
    layui.use('layer', function () {
        layer.confirm('确定删除？', {
            btn: ['是', '否']
        }, function (index, layero) {
            $(obj).parent().parent("tr").remove();
            layer.msg('删除成功', {icon: 1});
        }, function (index) {
            //按钮【否】的回调
        });
    });
}

/**
 *  上传成功返回文件信息
 */
let imgSuffixArray = ['.jpg', '.jpeg', '.png', '.webservice', '.gif', '.pdf'];

//初始化省市下拉框
function initSelector() {
    /**
     * 判断模板中的国家下拉框、省份下拉框、城市下拉框
     */
    let country = $('#supplierField input[comboname="country"]');
    let province = $('#supplierField input[comboname="province"]');
    let city = $('#supplierField input[comboname="city"]');
    let distinct = $('#supplierField input[comboname="county"]');
    let currencyCode = $('#supplierField 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) {
                            console.info(city.combobox('getValue'));
                            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) {
                debugger;
                $(el.supplierFieldForm).form('resetValidation');
                const editIndex = $(tableType['bank']['el']).datagrid('getRowIndex', $(tableType['bank']['el']).datagrid('getSelected'));
                if (editIndex >= 0) {
                    setBankInterCodeReadonly(editIndex, newValue);
                }
            }
        });
    }
}

//获取关系表的数据
function parseOtherTable() {
    let result = {};
    let obj = selfData.templateTableSet;
    //先结束所有的行编辑，不然获取不到表格数据
    for (let x in tableType) {
        let tb = tableType[x];
        if (tb['editIndex'] !== -1) {
            tableEndEdit(x);
        }
    }
    for (let x in tableType) {
        if (obj[tableType[x]['template']]) {
            result[tableType[x]['data']] = $(tableType[x]['el']).datagrid('getRows');
        }
    }

    return result;
}

$.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: '请输入正确的传真'
    }
});

$.fn.serializeJson = function () {
    let serializeObj = {};
    let array = this.serializeArray();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};

/**
 * 新增行，并触发行编辑事件
 * @param tbType 表格行编辑参数
 * @param dataRow 增加行数据内容
 */
function tableAddRow(tbType, dataRow) {
    debugger;
    let param = tableType[tbType];
    let tb = $(param['el']);
    let data ;
    if(tbType == "bank"){
        data = dataRow ? dataRow : {id: '', companyCode:'1000'};
    }else{
        data = dataRow ? dataRow : {id: ''};
    }

    tb.datagrid('appendRow', data);
    let index = tb.datagrid('getRows').length - 1;
}

/**
 * 表格删除行
 * @param tbType 表格行编辑参数
 */
function tableDelete(tbType) {
    let param = tableType[tbType];
    let tb = param['el'];
    let editIndex = param['editIndex']
    let row = $(tb).datagrid('getSelected');
    if (row) {
        let index = $(tb).datagrid('getRowIndex', row);
        //如果删除行的id有值，那么就需要调用后台删除方法删除
        if (row['id']) {
            //在表格编辑行上增加遮罩层，防止用户在数据保存中更改数据
            tableRowLoading(tb, index);
            $.post(g.ctx + 'pc/supplier/register/rest/follow/table/remove', {
                'id': row['id'], 'tableType': tbType
            }, function () {
                $(tb).datagrid('deleteRow', index);
                $('.datagrid-mask-msg').remove();
            }).error(function (data) {
                let msg = JSON.parse(data['responseText'])['message'];
                layer.msg(msg);
                return false;
            })
        } else {
            //否则直接删除即可
            $(tb).datagrid('deleteRow', index);
        }

        //删除行的时候，要把编辑行的索引更新
        if (index < editIndex) {
            tableType[tbType]['editIndex']--;
        } else if (index === editIndex) {
            tableType[tbType]['editIndex'] = -1;
        }
    }
    $(tb).datagrid('clearSelections');
}

/**
 * 新增行，并触发行编辑事件
 * @param tbType 表格行编辑参数
 * @param dataRow 增加行数据内容
 */
function tableCopy(tbType, dataRow) {
    let param = tableType[tbType];
    let tb = $(param['el']);
    let row = tb.datagrid('getSelected');
    if (!row) {
        layer.msg('请选中一条数据', {icon: 0});
        return;
    }
    row.id = '';
    let data ;
    if(tbType == "bank"){
        data = row ? row : {id: '', companyCode:'1000'};
    }else{
        data = row ? row : {id: ''};
    }

    tb.datagrid('appendRow', data);
}
/**
 * 表格关闭行编辑
 * @param tbType 表格行编辑参数
 */
function tableEndEdit(tbType) {
    let param = tableType[tbType];
    let tb = $(param['el']);
    $(tb).edatagrid("saveRow");
}

function reloadPage() {
    var a = selfData.supplierId;
    // 获取当前浏览器的 URL 地址
    var url = window.location.href;
// 添加参数
    if (url.indexOf("supplierId") == -1) {
        var newUrl = url + "&supplierId=" + a;
        // 重新加载页面
        window.location.href = newUrl;
    } else {
// 重新加载页面
        window.location.href = url;
    }


}

/**
 * 自定义表格元素遮罩层
 * @param tb 吸附元素
 * @param rowNumber 遮蔽行数
 */
function tableRowLoading(tb, rowNumber) {
    let bTable = $(tb).datagrid('getPanel').find('.datagrid-view').find('.datagrid-btable');
    let tBody = $(bTable[bTable.length - 1]);
    let height = $(tBody).find('tr[datagrid-row-index=0]')[0].offsetHeight;
    let top = 20 + height * (rowNumber + 1);
    $('<div class="datagrid-mask-msg"></div>').html('数据正在保存,请勿操作此数据。。。').appendTo(tBody)
        .css({
            display: "block",
            width: "100%",
            height: height + 'px',
            left: '0',
            top: top + 'px',
            opacity: '0.6',
            border: 'none'
        });
}

/**
 * 提取表格公共的按钮方法
 * @param tbType 表格类型（枚举类）
 */
function gridToolbar(tbType) {
    if(tbType == "bank"){
        return [{
            text: '新增', iconCls: 'icon-add', handler: function () {
                tableAddRow(tbType);
            }
        }, {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                tableDelete(tbType);
            }
        }, {
            text: '复制行', iconCls: 'icon-plan-copy', handler: function () {
                tableCopy(tbType);
            }
        }]
    }else{
        return [{
            text: '新增', iconCls: 'icon-add', handler: function () {
                tableAddRow(tbType);
            }
        }, {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                tableDelete(tbType);
            }
        }]
    }
}

/**
 * get属性给预览使用的
 */
function getSelfData() {
    return selfData;
}

function deleteItem(button) {
    // 在这里添加删除逻辑
    var td = button.parentElement;
    var fileIdInput = td.querySelector('input[name="fileId"]');
    if (fileIdInput) {
        fileIdInput.value = ''; // 设置fileId的值为空字符串
    }
    var fileName = td.querySelector('span[class="file-name"]');
    if (fileName) {
        fileName.innerText = ''; // 设置fileName的值为空字符串
    }
    // 删除td元素的class属性为hh
    td.classList.remove('hh');
}

/**
 * 设置银行国际代码 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/supplier/register/rest/getFieldValidationList',
        data: {
            templateId: $('#templateId').val(),
            type: $('#type').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 = $('#supplierField input[comboname="currencyCode"]');
                if (!currencyCodeEl.length) return true; // 元素不存在则跳过验证
                const currencyCode = currencyCodeEl.combobox('getValue');
                if (!currencyCode) return true; // 如果币种没选先跳过验证

                // 供应商全称含有英文字符时，特殊校验，提交表单时验证
                const supplierEnglishName = $('#supplierField 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;
            }
        };
    });
}