/**
 * 供应商资质信息补录
 * qualifications/apply/appointment.ftl
 * SupplierQualificationApplyRestController
 **/

let el = {
    supplierTb: '#supplierTb', detailTb: '#detailTb', id: '#id'
};

let selfData = {
    editType: '', height: '',
};

let tableType = {
    supplier: {
        el: '#supplierTb', editIndex: -1, url: ''
    }, detail: {
        el: '#detailTb', editIndex: -1, url: ''
    }
};

let param = {
    idColumn: {
        field: 'type', title: '状态', width: '6%', align: 'left', formatter: function (value) {
            switch (value) {
                case 1:
                    return '<span style="color:red;">删除</span>';
                default:
                    return '<span style="color:blue;">新建</span>';
            }
        }
    },
};

let query = {};
var type = $('#lookupFlag').val();
$(function () {
    query['applyId'] = $(el.id).val();
    if (query['applyId']) {
        tableType['supplier']['url'] = g.ctx + 'pc/supplier/supplierQualification/rest/applySupplierList'
        tableType['detail']['url'] = g.ctx + 'pc/supplier/supplierQualification/rest/applyQualificationList'
    }

    selfData.height = (gridheight - 100) / 2 > 200 ? (gridheight - 100) / 2 : 300;
    loadSupplierGrid();
    loadDetailGrid();
    if (convertFlag()) {
        $("#submitFlag").val(1)
    } else {
        $("#submitFlag").val(0)
    }
});

function convertFlag() {
    if (supplierCode !== '') {
        return true
    }
    return false
}

//供应商信息表
function loadSupplierGrid() {
    var toolbar = [];
    if (type !== 1 && !convertFlag()) {
        toolbar = [{
            text: '添加供应商', iconCls: 'icon-add', handler: function () {
                addSupplier();
            }
        }, {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                tableDelete('supplier')
            }
        }]
    }
    $(tableType['supplier']['el']).datagrid({
        url: tableType['supplier']['url'], queryParams: query, method: "GET", height: selfData.height, columns: [[{
            field: 'ck', checkbox: true
        }, param.idColumn, {
            field: 'supplierCode', title: '供应商编码', width: '40%',
        }, {
            field: 'supplierName', title: '供应商名称', width: '40%',
        }]], rownumbers: true, fitColumns: false, nowrap: false, striped: true, toolbar: toolbar
    })
    if (convertFlag()) {
        $(tableType['supplier']['el']).datagrid("appendRow", {
            supplierCode: supplierCode,
            supplierName: supplierName,
            supplierId: supplierId,
            type: 0
        });
    }
}

//资质详情表
function loadDetailGrid() {
    var toolbar = [];
    if (type != 1) {
        toolbar = [{
            text: '选择资质', iconCls: 'icon-add', handler: function () {
                addQualification()
            }
        }, {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                tableDelete('detail');
            }
        }];
    }
    $(el.detailTb).datagrid({
        url: tableType['detail']['url'],
        height: selfData.height,
        queryParams: query,
        method: "GET",
        rownumbers: true,
        fitColumns: false,
        nowrap: false,
        striped: true,
        columns: [[{
            field: 'ck', checkbox: true
        }, param.idColumn, {
            field: 'code', title: '资质编码', width: '40%'
        }, {
            field: 'name', title: '资质名称', width: '40%'
        }]],
        toolbar: toolbar
    })
}

/**
 * 删除选中的行
 */
function removeSelectRows($tb) {
    let rows = $tb.datagrid('getSelections');
    if (rows.length === 0) {
        layer.msg(tipsi18n.qxzxyscdh, {icon: 0});
        return false;
    }
    let delRowIndex = [];
    for (let i = 0; i < rows.length; i++) {
        delRowIndex.push(rows[i]);
    }
    for (let n = 0; n < delRowIndex.length; n++) {
        let index = $tb.datagrid('getRowIndex', delRowIndex[n]);
        $tb.datagrid('deleteRow', index);
    }
}

var submitFlag = 0

/**
 * 提交方法
 */
function submitForm(callback) {
    if (submitFlag == 1) {
        return
    }
    //先结束行编辑
    let supplierList = $(tableType['supplier']['el']).datagrid("getRows");
    if (!supplierList.length) {
        topWin.layer.msg('请选择供应商数据', {icon: 2})
        return
    }
    let detailList = $(tableType['detail']['el']).datagrid("getRows");
    if (!detailList.length) {
        topWin.layer.msg('请选择资质数据', {icon: 2})
        return
    }
    let form = {}
    form['id'] = $(el.id).val();
    let purchaseCategoryCodes = $("input[comboname='purchaseCategoryCodes']").combobox("getValues")
    form['purchaseCategoryCodes'] = purchaseCategoryCodes.join(",")
    form['type'] = $("input[comboname='type']").combobox("getValue")
    form['supplierList'] = supplierList;
    form['submitFlag'] = $("#submitFlag").val();
    form['detailList'] = detailList;
    submitFlag = 1
    topWin.layer.load(1);
    $.ajax({
        url: g.ctx + 'pc/supplier/supplierQualification/rest/apply/saveOrUpdate',
        method: "post",
        contentType: 'application/json',
        data: JSON.stringify(form),
        complete: function () {
            topWin.layer.closeAll('loading')
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback()
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })
}

/**
 * 打开供应商选择器,添加供应商
 */
function addSupplier() {
    let purchaseCategoryCodes = $("input[comboname='purchaseCategoryCodes']").combobox("getValues");
    let status = $("input[comboname='type']").combobox("getValues");
    if(status == "3"){
        status = "";
    }
    let url = g.ctx + "pc/supplier/supplierSelect?single=0&categories="
    url = url + purchaseCategoryCodes.join(',') + "&state=" + status
    var supplierDialogElement = openDialog("supplierDialog", url, {
        title: "供应商选择",
        width: '650px',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            supplierDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择', iconCls: 'icon-save', handler: function () {
                topWin.frames['supplierDialog'].chooseRow(function (data) {
                    //需要排除重复数据
                    var tableRows = $(el.supplierTb).datagrid("getRows")
                    var map = {}
                    $.each(tableRows, function (idx, itm) {
                        map[itm.supplierId] = 1
                    })
                    $.each(data, function (idx, itm) {
                        if (map[itm.id] == undefined) {
                            itm['supplierId'] = itm.id
                            itm['type'] = 0
                            itm.id = undefined
                            $(el.supplierTb).datagrid("appendRow", itm)
                        }
                    })
                    supplierDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                supplierDialogElement.dialog('close');
            }
        }]
    })
}

/**
 * 打开资质模板选择器，添加资质
 */
function addQualification() {
    const url = g.ctx + 'pc/supplier/qualification/index?selected=1&single=0'
    const qualificationItemDialog = openDialog('qualificationItemDialog', url, {
        title: '资质选择',
        width: '90%',
        height: '90%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            qualificationItemDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.confirm, handler: function () {
                topWin.frames['qualificationItemDialog'].getChecked(function (rows) {
                    const tableRows = $(el.detailTb).datagrid("getRows")
                    const map = {}
                    $.each(tableRows, function (idx, itm) {
                        map[itm.qualificationId] = 1
                    })
                    $.each(rows, function (idx, itm) {
                        let tmpRow = {
                            qualificationId: itm.id,
                            name: itm.name,
                            type: 0,
                            exampleFileId: itm.exampleFileId,
                            code: itm.code,
                            remark: itm.remark
                        }
                        if (map[itm.id] == undefined) {
                            $(el.detailTb).datagrid("appendRow", tmpRow)
                        }
                    })
                    qualificationItemDialog.dialog('close');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                qualificationItemDialog.dialog('close');
            }
        }]
    });
}

/**
 * 表格删除行
 * @param tbType 表格行编辑参数
 */
function tableDelete(tbType) {
    let param = tableType[tbType];
    let tb = param['el'];
    let rows = $(tb).datagrid('getChecked');
    if (rows.length !== 0) {
        var rowIdx = []
        $.each(rows, function (idx, row) {
            let index = $(tb).datagrid('getRowIndex', row)
            if (row.id) {
                $(tb).datagrid('updateRow', {index: index, row: {type: 1}});
            } else {
                rowIdx.push(index)
            }
        })
        if (rowIdx.length > 0) {
            rowIdx.reverse()
            $.each(rowIdx, function (idx, row) {
                $(tb).datagrid('deleteRow', row);
            })
        }
    }
    $(tb).datagrid('clearSelections');
}
