/**
 * 供应商详情查看页面
 * @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');
            }
            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: '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() {

}

/**
 * 加载供应商附件表
 */
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: '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 '认证报告'
            }
        }
    }]
    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 editIndex_item = undefined;

function uploadFile(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) {
}

// 供应商资质新增回调函数
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() {
}

/**
 * 初始化基本信息页表格参数
 */
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 openDemoDialog(id) {
}

function signUpRemark(call) {
}
