/**
 * 供应商详情查看页面
 * @author BOGON
 * @version 1.0
 */

let el = {
    supplierId: '#supplierId',
    type: '#type',
    tab: '#tab',
    signUpRemark: '#signUpRemark',
    account: '#accountTb',
    attachment: '#attachmentTb',
    sqesocreTb: '#sqesocreTb',
    supplierProductType: "#supplierProductTypeTb",
    purchaseOrgTb: "#purchaseOrgTb",
    sceneAuth: "#sceneAuthTb",
    templateFollowTable: '#templateFollowTable',
    supplierInviteDesc:"#supplierInviteDesc"
};

/**
 * 表格行编辑类型
 * {el 页面元素；editIndex 行编辑坐标}
 */
let tableType = {
    supplierTykm: {
        el: '#supplierTykmTb', editIndex: -1, template: 't_supplier_tykm', data: 'supplierTykmList'
    }, supplierContact: {//联系人
        el: '#supplierContactTb', editIndex: -1, template: 't_supplier_contacts', data: 'contactsList'
    }, bank: {//供应商银行
        el: '#bankTb', editIndex: -1, template: 't_supplier_bank', data: 'bankList'
    }
};

let selfData = {
    supplierId: null,
    type: null,
    height: 0,
    width: gridwidth - 30,
    followTable: {},
    bodyHeight: document.documentElement.clientHeight,
    templateTableField: [],
    templateTableSet: {},
};

$(function () {
    //初始化关键数据
    initDict('payment_method,controlling_accounts,currency,tax,supplier_role_type,payment_way,supplier_accetp_deadline')
    initNecessaryDatas("pc/sys/tax/rest/listAll,pc/sys/company/rest/listAll,pc/sys/purchaseOrg/rest/listAll")
    selfData.supplierId = $(el.supplierId).val();
    selfData.type = $(el.type).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;
            selfData.templateTableSet[e] = 1;
        }
    }

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

        }
    });

    let height = document.documentElement.clientHeight - $(el.tab).outerHeight() - 130;
    selfData.height = height > 300 ? height : 300;

    initDataGrid();

    layui.use('element', function () {
        let element = layui.element;
        loadGrid();

        element.on('tab(demo)', function (data) {

            let tbName = $(this).attr("ttname");
            if (tbName == 'attachmentTb') {
                loadAttachmentGrid();
                $(el.attachment).datagrid('resize');
            } else if (tbName == 'supplierProductTypeTb') {
                // 供应商品类列表
                loadSupplierProductTypeGrid();
            } else if (tbName == 'appraisalTb') {
                //初始化绩效考核数据
                initAppraisal()
                $("#appraisalTb").datagrid('resize');
            } else if (tbName == 'sqesocreTb') {
                //初始化SQE评分数据
                loadSqesocreGrid();
                $("#sqesocreTb").datagrid('resize');
            }
            for (let x in tableType) {
                if (selfData.templateTableSet[tableType[x]['template']]) setTimeout(function () {
                    $(tableType[x]['el']).datagrid('resize');
                }, 1)
            }
        });

        element.init();
        initFollowTableData();
    });

    // 审批初始化认证类型
    initFieldCertificationCodeCombo();

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


});

function initFieldCertificationCodeCombo() {
    $("#fieldCertificationCode").combobox({
        valueField: 'value',
        textField: 'label',
        data: [{label: '是', value: 1}, {label: '否', value: 2},],
        editable: false,
        panelHeight: 'auto',
        prompt: '-- 请选择 --'
    });
}

//加载表格
function loadGrid() {
    loadUserGrid();
    loadSupplierInviteDesc();
}

/**
 * 获取供应商关联表数据，用于表格数据初始化
 */
function initFollowTableData() {
    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']]});
            }
        }).error(function (data) {
            let msg = JSON.parse(data['responseText'])['message'];
            topWin.layer.msg('请求超时，获取表格数据时失败！ ' + msg);
        })
    }
}


/**
 * 加载供应商用户表格
 */
function loadUserGrid() {
    let supplierId = $(el.supplierId).val();
    $(el.account).datagrid({
        url: g.ctx + 'pc/sys/user/list',
        method: "GET",
        singleSelect: true,
        pagination: true,
        height: selfData.height,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        remoteSort: true,
        striped: true,
        queryParams: {
            supplierId: supplierId
        },
        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'username', title: '用户名称', width: '15%', align: 'center'
        }, {
            field: 'accountName', title: '用户账号', width: '15%', align: 'center'
        }, {
            field: 'deleteStatus', title: '账号状态', width: '10%', align: 'center', formatter: function (data) {
                if (data === '0') return "正常"; else return "<font color='red'>禁用</font>"
            }
        }, {
            field: 'email', title: 'EMAIL', width: '14%', align: 'center'
        }, {
            field: 'dispatchRoles', title: '已分配角色', width: '10%', align: 'center'
        }]]
    });
}


function loadSupplierInviteDesc() {
    let supplierId = $(el.supplierId).val();
    $.ajax({
        url: g.ctx + 'pc/supplier/invitation/rest/find/list?supplierId=' + supplierId,
        type: 'POST',
        success: function (res) {
            $('#inviteDesc').textbox('setValue', res[0].inviteDesc);
            $('#specialRemark').textbox('setValue', res[0].specialRemark);

        }
    });
}

/**
 * 加载供应商附件表
 */
var attachmentGridEditIndex = -1

function loadAttachmentGrid() {
    let options = {
        width: selfData.width,
        url: g.ctx + 'pc/supplier/qualification/rest/supplierQualifications?typeStr=1,2,3',
        method: "GET",
        singleSelect: true,
        pagination: false,
        height: selfData.height,
        rownumbers: true,
        nowrap: true,
        remoteSort: true,
        striped: true,
        queryParams: {
            supplierId: selfData.supplierId
        },
        columns: [],
        rowStyler: function (index, row) {
            if (Number(row.custom_upload_flag) === 1) {
                return 'background-color:pink;';
            }
        },
        onClickRow: function (index, row) {
            if (Number(row.custom_upload_flag) === 1) {
                onClickRow_item(index);
            }
        }
    }
    let defaultColums = [{
        field: 'ck', checkbox: true
    }, {
        field: 'version', title: '版本', width: '40', align: 'left'
    }, {
        field: 'scene', title: '类型', width: '80', align: 'left',
        formatter: function (value, row) {
            switch (value) {
                case 1:
                    return '资质'
                case 2:
                    return '协议'
                case 3:
                    return '认证报告'
            }
        }
    }]
    if (typeStr === 'inviationApproval') {
        defaultColums.push({
            field: 'fileName', title: '资质证书名称', width: '20%', align: 'left', formatter: function (value, row) {
                //需要判断row.fileName文字长度是否超过了20个字符，如果超过则显示...
                let txt = ''
                if (value.length > 20) {
                    txt = value.substring(0, 20) + "..."
                } else {
                    txt = value
                }

                '<a href="#" onclick="previewFileForm(undefined,\'' + value + '\',\'' + row.fileId + '\')">预览</a>'

                return "<a title='" + value + "' href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + txt + "</a>" + '<a href="#" onclick="previewFileForm(undefined,\'' + value + '\',\'' + row.fileId + '\')">&nbsp;&nbsp;&nbsp;&nbsp;预览</a>'
            },
            editor: {
                type: 'textbox', options: {
                    editable: false,
                    buttonIcon: 'icon-upload',
                    onClickButton(e) {
                        $("#fileUpload .filebox-label").click();
                    }
                }
            }
        }, {
            field: 'qualificationNumber', title: '资质证书编码', width: '15%', align: 'left'
        }, {
            field: 'qualificationName', title: '资质名称', width: '20%', align: 'left'
        }, {
            field: 'availableStartDate', title: '证书生效时间', width: '15%', align: 'left'
        }, {
            field: 'availableEndDate', title: '证书失效时间', width: '15%', align: 'left'
        }, {
            field: 'createTime', title: '创建时间', width: '10%', align: 'left', formatter: function (value) {   //格式化时间
                if (value) {
                    return new Date(value).format("yyyy-MM-dd")
                }
                return value;
            }
        })
        options.onEdit = function (index, row) {
            attachmentGridEditIndex = index
            let fileNameTextBox = $(el.attachment).edatagrid('getEditor', {
                index: attachmentGridEditIndex,
                field: 'fileName'
            }).target;
            fileNameTextBox.textbox('readonly', false);
        }
        options['autoSave'] = true
        options['toolbar'] = [
            {
                text: '保存',
                iconCls: 'icon-save',
                handler: function () {
                    $(el.attachment).edatagrid("saveRow");
                    let rows = $(el.attachment).edatagrid("getRows");
                    //我需要判断row.scene是否等于3，如果等于3组装成新的数组
                    let newRows = []
                    for (let i = 0; i < rows.length; i++) {
                        newRows.push(rows[i])
                    }
                    if (newRows.length > 0) {
                        var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                        $.ajax({
                            url: g.ctx + 'pc/supplier/supplierQualification/rest/update',
                            type: 'POST',
                            data: JSON.stringify(newRows),
                            contentType: 'application/json',
                            complete: function (data) {
                                topWin.layer.close(loading);
                            },
                            error: function (data) {
                                topWin.layer.alert(JSON.parse(data.responseText).message);
                            },
                            success: function (res) {
                                topWin.layer.msg('保存成功');
                            }
                        })
                    }
                }
            }
        ]
        options.columns.push(defaultColums)
        $(el.attachment).edatagrid(options);
    } else {
        defaultColums.push({
            field: 'fileName', title: '资质证书名称', width: '20%', align: 'left', formatter: function (value, row) {
                return "<a href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>"
            }
        }, {
            field: 'qualificationNumber', title: '资质证书编码', width: '15%', align: 'left'
        }, {
            field: 'qualificationName', title: '资质名称', width: '20%', align: 'left'
        }, {
            field: 'availableStartDate', title: '证书生效时间', width: '15%', align: 'left', editor: {type: 'datebox'}
        }, {
            field: 'availableEndDate', title: '证书失效时间', width: '15%', align: 'left', editor: {type: 'datebox'}
        }, {
            field: 'createTime', title: '创建时间', width: '10%', align: 'left', formatter: function (value) {   //格式化时间
                if (value) {
                    return new Date(value).format("yyyy-MM-dd")
                }
                return value;
            }
        })
        options.columns.push(defaultColums)
        $(el.attachment).datagrid(options);
    }

}

function fileUpload() {
    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) {
            $(el.attachment).edatagrid("endEdit", attachmentGridEditIndex);
            $(el.attachment).edatagrid('updateRow', {
                index: attachmentGridEditIndex,
                row: {
                    fileId: result.id,
                    fileName: result.fileName
                }
            });
            topWin.layer.msg('上传成功', {icon: 1});
        },
        error: function (xhr, status, error) {
            topWin.layer.alert('文件上传失败', {icon: 2})
        }
    });
}

var editIndex_item = undefined;

function uploadFile(type) {
    layer.open({
        title: supplieri18n.scwj,
        type: 2,
        closeBtn: 0,
        area: ["340px", "200px;"],
        content: "/files/fileUploadUI?type=" + type
    });
}

function returnFileMessage(fileid, uploadFileName, uploadFilepath) {
    // endEditing_item();
    $('#tb').datagrid('acceptChanges');
    $(el.attachment).datagrid('updateRow', {
        index: editIndex_item, row: {
            file_id: fileid, file_path: uploadFilepath, file_name: uploadFileName
        }
    });
}


function endEditing_item() {
    if (editIndex_item == undefined) {
        return true
    }
    if ($(el.attachment).datagrid('validateRow', editIndex_item)) {
        $(el.attachment).datagrid('endEdit', editIndex_item);
        editIndex_item = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickRow_item(index) {
    if (editIndex_item != index) {
        if (endEditing_item()) {
            $(el.attachment).datagrid('selectRow', index)
                .datagrid('beginEdit', index);
            editIndex_item = index;
        } else {
            $(el.attachment).datagrid('selectRow', editIndex_item);
        }
    } else {
        $(el.attachment).datagrid('selectRow', index)
            .datagrid('beginEdit', index);
        editIndex_item = index;
    }

}

// 供应商资质新增回调函数
function supplierQualificationsSelectAllCallBack(data) {
    var rows = $(el.attachment).datagrid("getRows");
    $.each(data, function (index, value) {
        var has = false;
        for (var i = 0; i < rows.length; i++) {
            if (value.code == rows[i].qualifications_code) {
                has = true;
            }
        }
        if (!has) {
            $(el.attachment).datagrid('appendRow', {
                qualifications_id: "",
                qualifications_code: value.code,
                qualifications_name: value.name,
                qualifications_number: "",
                file_id: "",
                file_path: "",
                file_name: "",
                available_start_date: "",
                available_end_date: "",
                custom_upload_flag: 1,
                supplier_id: $("#supplier_id").val()
            });
        }
    });
}

// 加载现场认证列表

function loadSceneAuthGrid() {
    let columns = [[{field: 'ck', checkbox: true}, {
        field: 'status', title: '计划状态', width: '6%', align: 'left', formatter: function (value, row) {
            // if (value) {
            //     return getPlanStatusNameByDictId(value, "'supplier_audit_plan_status'");
            // }
            switch (value) {
                case "10":
                    return '<span style="color: red;">新建</span>';
                    break;
                case "11":
                    return '<span style="color: green;">已提交</span>';
                    break;
                case "12":
                    return '<span style="color: green;">计划通过</span>';
                    break;
                case "13":
                    return '<span style="color: red;">计划不通过</span>';
                    break;
                case "17":
                    return '<span style="color: green;">计划已发布</span>';
                    break;
                case "30":
                    return '<span style="color: #404e80;">稽核结果审批中</span>';
                    break;
                case "31":
                    return '<span style="color: #404e80;">稽核结果审批通过</span>';
                    break;
                case "32":
                    return '<span style="color: red;">稽核结果审批不通过</span>';
                    break;
                case "23":
                    return '<span style="color: #404e80;">稽核审批通过</span>';
                    break;
                case "33":
                    return '<span style="color: red;">已驳回</span>';
                    break;
                default:
                    return '<span style="color: red;">稽核审批不通过</span>';
                    break;

            }
        }, styler: function (value, row, index) {

        }
    }, {
        field: 'researchCode', title: '计划单号', width: '10%', align: 'left'
    }, {
        field: 'supplierCode', title: '供应商编码', width: '10%', align: 'center'
    }, {
        field: 'supplierName', title: '供应商名称', width: '18%', align: 'center'
    },
        {
            field: 'materialCategoryCode',
            title: '物料小类',
            width: '23%',
            align: 'center',
            hidden: true,
            formatter: function (value, row) {
                if (value == "-1") {
                    return "全部物料";
                } else {
                    return row.materialCategoryName;
                }
            }
        }, {
            field: 'provinceCity', title: '供方地点 ', width: '15%', align: 'center'
        }, {
            field: 'researchModeName', title: '稽核方式 ', width: '10%', align: 'center'
        }, {
            field: 'createTime', title: '创建日期', width: '8%', align: 'center', formatter: function (value) {
                if (value) {
                    return formatDateMS(value);
                }
            }
        }, {
            field: 'userName', title: '创建人', width: '8%', align: 'center'
        }, {
            field: 'planCreateTime', title: '计划实施日期', width: '8%', align: 'center', formatter: function (value) {
                if (value) {
                    return formatDateMS(value);
                }
            }
        }]];
    let supplierId = $(el.supplierId).val();
    $(el.sceneAuth).datagrid({
        url: '/supplierPlan/supplierPlanList',
        toolbar: [{
            text: "自评分数查看", iconCls: 'icon-find', id: 'selfDetailBtn', handler: function () {
                checkSupplierEvaluation(1);
            },
        }, {
            text: "审核分数查看", iconCls: 'icon-find', id: 'showDetailBtn', handler: function () {
                checkSupplierEvaluation(2);
            },
        }],
        singleSelect: true,
        pagination: true,
        height: selfData.height,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        remoteSort: true,
        striped: true,
        queryParams: {
            researchMode: 2, researchProperty: 2, supplierId: supplierId
        },
        columns: columns
    });
}

// 加载供应商品类列表
function loadSupplierProductTypeGrid() {
    let supplierId = $(el.supplierId).val();
    let toolbar = []
    if (typeStr === 'inviationApproval') {
    } else {
        toolbar = [{
            text: '品类添加', id: 'btn-product-auth', iconCls: 'icon-add', handler: function () {
                var rows = $('#supplierProductTypeTb').datagrid('getSelected');
                if(!rows || rows.length <= 0){
                    layer.msg("请勾选下方一条数据后再点击品类添加按钮！");
                    return false;
                }
                var id = '';
                    id = rows.id;
                var addPurchaseCategoryDialog = openDialog("addPurchaseCategoryDialog", g.ctx + 'pc/supplier/purchaseCategory/page/supplierAdd?supplierId=' + supplierId +'&id=' + id, {
                    title: "品类添加",
                    width: '600',
                    height: '800',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        addPurchaseCategoryDialog.dialog('destroy');
                    },
                    buttons: [
                        {
                            text: "确定",
                            handler: function () {
                                topWin.frames["addPurchaseCategoryDialog"].page.submit(function () {
                                    addPurchaseCategoryDialog.dialog('close');
                                    $(el.supplierProductType).datagrid("reload")
                                });
                            }
                        },
                        {
                            text: itablei8n.close,
                            handler: function () {
                                addPurchaseCategoryDialog.dialog('close');
                            }
                        }
                    ]

                })
            }
        }, {
            text: '物料认证添加', id: 'btn-product-auth', iconCls: 'icon-add', handler: function () {
                let rows = $(el.supplierProductType).datagrid("getChecked")
                if (rows.length !== 1) {
                    topWin.layer.msg("只能选中一条品类!")
                    return
                }
                var materialDemoDialog = openDialog("materialDemoDialog", g.ctx + 'pc/supplier/materialDemo/page/select?supplierId=' + supplierId, {
                    title: "物料认证添加",
                    width: '100%',
                    height: '100%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        materialDemoDialog.dialog('destroy');
                    },
                    buttons: [
                        {
                            text: "确定",
                            handler: function () {
                                let checked = topWin.frames["materialDemoDialog"].getChecked();
                                let ids = []
                                $.each(checked, function (idx, itm) {
                                    ids.push(itm.id)
                                })
                                $.ajax({
                                    method: 'POST',
                                    url: g.ctx + 'pc/supplier/purchaseCategory/rest/sumbmitDemoRel',
                                    data: {
                                        id: rows[0].id,
                                        demoIds: ids.join(",")
                                    },
                                    success: function (data) {
                                        topWin.layer.msg("操作成功", {icon: 1});
                                        materialDemoDialog.dialog('close');
                                        $(el.supplierProductType).datagrid('reload');
                                    },
                                    error: function (data) {
                                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                    }
                                })
                            }
                        },
                        {
                            text: itablei8n.close,
                            handler: function () {
                                materialDemoDialog.dialog('close');
                            }
                        }
                    ]

                })
            }
        }, {
            text: '优先设置', id: 'btn-product-auth', iconCls: 'icon-edit', handler: function () {
                let rows = $("#supplierProductTypeTb").datagrid('getSelections');
                if (rows.length != 1) {
                    topWin.layer.msg('请选择一条数据', {icon: 0});
                    return;
                }
                topWin.layer.confirm('确认设置为优先吗?', {icon: 3}, function (index) {
                    $.ajax({
                        url: g.ctx + 'pc/supplier/purchaseCategory/rest/updateFirst?id=' + rows[0].id,
                        type: 'POST',
                        success: function (d) {
                            topWin.layer.msg("操作成功!")
                            $(el.supplierProductType).datagrid("reload")
                        },
                        error(data) {
                            topWin.layer.msg(data.responseJSON.message);
                            topWin.layer.close(index);
                        }
                    });

                });
            }
        }]
    }
    $(el.supplierProductType).datagrid({
        url: g.ctx + 'pc/supplier/purchaseCategory/rest/listSupplier',
        method: "GET",
        singleSelect: true,
        pagination: false,
        height: selfData.height,
        loadMsg: "数据加载中......",
        nowrap: true,
        remoteSort: true,
        striped: true,
        queryParams: {
            supplierId: supplierId
        },
        toolbar: toolbar,
        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'isFreeze', title: '是否取消', width: '65', align: 'center',
            formatter: function (value, row) {
                return value === 1 ? "是" : "否"
            },
        }, {
            field: 'firstFlag',
            title: '优先标记',
            width: '3%',
            align: 'center',
            formatter: function (value, row, index) {
                if (value) {
                    return "<span style='color: darkgreen;'>是</span>";
                }
                return "否";
            }
        }, {
            field: 'state', title: '状态', width: '15%', align: 'center', formatter: function (value) {
                switch (value) {
                    case 1:
                        return '注册';
                    case 2:
                        return '潜在';
                    case 3:
                        return '正式';
                    case 4:
                        return '临时';
                    case 5:
                        return '退出';
                    case 6:
                        return '合格';
                    case 7:
                        return '小批量';
                    default:
                        return '';
                }
            }
        }, {
            field: 'purchaseCategoryCode', title: '品类编码', width: '15%', align: 'center'
        }, {
            field: 'purchaseCategoryName', title: '品类名称', width: '15%', align: 'center'
        }, {
            field: 'demoSize',
            title: '品类认证附件',
            width: '15%',
            align: 'center',
            formatter: function (value, row, index) {
                var title;
                if (value) {
                    title = "点击查看(" + value + ")"

                } else {
                    title = "无"
                }
                return "<a style='color: #108ee9' href='javascript:void(0)' onclick=\"openDemoDialog('" + row.id + "')\">" + title + "</a>";
            }
        }, {
            field: 'paymentTerms', title: '付款条件', width: '12%', align: 'center', formatter: function (value) {
                return getDicName("payment_method", value)
            }
        }, {
            field: 'paymentMethod', title: '付款方式', width: '12%', align: 'center', formatter: function (value) {
                return getDicName("payment_way", value)
            }
        }, {
            field: 'acceptanceMethod', title: '承兑期限', width: '90', formatter: function (value) {
                return getDicName('supplier_accetp_deadline', value)
            }
        }, {
            field: 'companyCode', title: '公司', width: '19%', align: 'center', formatter: function (value) {
                return getNecessaryDataName("pc/sys/company/rest/listAll", value)
            }
        }, {
            field: 'currencyCode', title: '币种', width: '5%', align: 'left', formatter: function (value, row) {
                return getDicName("currency", value)
            }
        }, {
            field: 'taxCode', title: '税率', width: '10%', align: 'center', formatter: function (value) {
                return getNecessaryDataName("pc/sys/tax/rest/listAll", value)
            }
        }, {
            field: 'controlSubject', title: ' 统御科目', width: '10%', align: 'center', formatter: function (value) {
                return getDicName("controlling_accounts", value)
            }
        }, {
            field: 'purchaseOrgCode', title: ' 采购组织', width: '10%', align: 'center', formatter: function (value) {
                return getNecessaryDataName('pc/sys/purchaseOrg/rest/listAll', value)
            }
        }, {
            field: 'smallTime', title: '转小批量时间', width: 160, align: 'center', formatter: function (value, row) {
                if (value) {
                    return new Date(value).format("yyyy-MM-dd hh:mm")
                }
                return value;
            }
        }, {
            field: 'qualifiedTime', title: '转合格时间', width: 160, align: 'center', formatter: function (value, row) {
                if (value) {
                    return new Date(value).format("yyyy-MM-dd hh:mm")
                }
                return value;
            }
        }]]
    });
}

/**
 * 初始化基本信息页表格参数
 */
function initDataGrid() {

    //联系人
    let supplierContact = 'supplierContact';
    $(tableType[supplierContact]['el']).datagrid({
        singleSelect: true,
        height: selfData.height,
        rownumbers: true,
        striped: true,
        data: selfData.followTable['contactsList'],
        columns: [[{
            field: 'contactsType', title: '联系人类型', width: '15%', align: 'left', formatter: function (value, row) {
                return getDicName("supplier_role_type", value);
            },
        }, {
            field: 'contactsName', title: '姓名', width: '15%', align: 'left',
        },
            //     {
            //     field: 'contactsMobile', title: '手机', width: '15%', align: 'left',
            // },
            {
                field: 'contactsTel', title: '电话', width: '15%', align: 'left',
            }, {
                field: 'email', title: '邮箱', width: '15%', align: 'left',
            }]],
    });


    //供应商银行
    let bank = 'bank';
    $(tableType[bank]['el']).datagrid({
        singleSelect: true,
        height: selfData.height,
        rownumbers: true,
        striped: true,
        data: selfData.followTable['bankList'],
        columns: [[
            {
                field: 'companyCode', title: '公司代码', width: '13%', align: 'left'
                , formatter: function (value) {
                    return getNecessaryDataName("pc/sys/company/rest/listAll", value)
                }
            }, {
                field: 'companyName', title: '收款单位', width: '20%', align: 'left',
            }, {
                field: 'openingBankName', title: '收款银行', width: '20%', align: 'left',
            }, {
                field: 'bankAccount', title: '银行账号', width: '15%', align: 'left',
            },
            {
                field: 'bankCode', title: '银行行号', width: '12%', align: 'left'
            }, {
                field: 'bankAddress', title: '银行地址', width: '20%', align: 'left',
            }, {
                field: 'bankInterCode', title: '银行国际代码', width: '12%', align: 'left'
            }]],
    });
}


//初始化省市下拉框
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"]');
    if (country.length) {
        if (province.length) {
            country.combogrid({
                onSelect: function (index, row) {
                    if (row['CODE']) {
                        province.combogrid('clear');
                        province.combogrid('setValue', '');
                        province.combogrid({
                            prompt: '国家的二级联动框',
                            url: g.ctx + 'pc/sys/area/rest/query',
                            method: 'GET',
                            queryParams: {
                                pCode: row['CODE']
                            }
                        })
                    }
                }
            });

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

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

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


/**
 * 初始化绩效考核的数据
 */
function initAppraisal() {
    $("#appraisalTb").datagrid({
        url: g.ctx + 'pc/spe/supAppraisePlan/rest/getSupplierAppraisePlan',
        singleSelect: true,
        pagination: true,
        height: selfData.height,
        method: "GET",
        rownumbers: true,
        fitColumns: true,
        nowrap: true,
        striped: true,
        queryParams: {
            supplierId: selfData.supplierId
        },
        pageSize: 5,
        pageList: [5],
        columns: [[{
            field: 'evaluationCycle', title: '考核周期', width: '5%', formatter: function (value) {
                if (!value) {
                    return '';
                }
                if (value === 1) {
                    return '年度';
                } else if (value === 2) {
                    return '季度';
                } else if (value === 3) {
                    return '月度';
                }
            }
        }, {
            field: 'date', title: '考核期间', width: '10%', align: 'left', formatter: function (value, row) {
                if (row.evaluationCycle === 1) {
                    return row.year + "年";
                } else if (row.evaluationCycle == 2) {
                    return row.year + "年第" + row.quarter + "季";
                } else if (row.evaluationCycle == 3) {
                    return row.year + "年" + row.month + "月";
                }
            }
        }, {
            field: 'companyName', title: '公司名称', width: '15%', align: 'left',
        }, {
            field: 'supplierCode', title: '供应商编码', width: '10%', align: 'left',
        }, {
            field: 'supplierName', title: '供应商名称', width: '30%', align: 'left'
        }, {
            field: 'score', title: '总分', width: '5%', align: 'left',
        }, {
            field: 'level', title: '评级', width: '5%', align: 'left',
        }]],
    });
}


/**
 * 初始化SQE评分的数据
 */
function loadSqesocreGrid() {
    let supplierId = $(el.supplierId).val();
    $("#sqesocreTb").datagrid({
        url: g.ctx + 'pc/supplier/sqescore/rest/list',
        method: "GET",
        singleSelect: true,
        pagination: false,
        height: selfData.height,
        rownumbers: true,
        fitColumns: true,
        nowrap: true,
        remoteSort: true,
        striped: true,
        queryParams: {
            supplierId: supplierId
        },
        columns: [[
            {
                field: 'id',
                hidden: true
            },
            {
                field: 'supplierLevel',
                title: "供应商等级",
                width: 130,
                align: 'left'
            },
            {
                field: 'supplierWeakness',
                title: "供应商劣势",
                width: 130,
                align: 'left'
            },
            {
                field: 'supplierStrength',
                title: "供应商优势",
                width: 130,
                align: 'left'
            },
            {
                field: 'qpaScore',
                title: "QPA评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'qsaScore',
                title: "QSA评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'purchasePriceScore',
                title: "采购价格评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'purchaseScore',
                title: "采购交期评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'nonManufacturerPurchaseScore',
                title: "非制造商采购评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'rdScore',
                title: "研发评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'totalScore',
                title: "总评分",
                width: 130,
                align: 'left'
            },
            {
                field: 'createName',
                title: "评分人",
                width: 130,
                align: 'left'
            }
        ]],
    });
}

function openDemoDialog(id) {
    var demoDialog = openDialog("demoDialog", g.ctx + "pc/supplier/purchaseCategory/page/demo?id=" + id, {
        title: "物料认证查看",
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            demoDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.close,
                handler: function () {
                    demoDialog.dialog('close');
                }
            }
        ]

    })
}

function signUpRemark(call) {
    call($("#signUpRemark").textbox("getValue"))
}
