var submitFlag = 0

$(function () {
    //初始化可滚动区域的高度
    $('#wrap').css('height', (screenHeight - 189) + 'px');
    initData();
});

// 初始化数据，加载已配置的扩展字段或资质
function initData() {
    $.ajax({
        url: g.ctx + 'pc/tender/template/rest/templateFieldList?id=' + id,
        type: 'get',
        success: function (data) {
            if (!data || data.length <= 0) {
                topWin.layer.msg("未查询到模板数据。");
                return;
            }
            var fieldList = data;
            var newFields = '';
            $.each(fieldList, function (index, target) {
                var field_group = target.defaultFlag;
                var requiredTd = '<input type="checkbox" class="required">';
                var editTd = '<input type="checkbox" class="edit">';
                var supplierShow = '<input type="checkbox" class="supplierShow">';
                var supplierEdit = '<input type="checkbox" class="supplierEdit">';
                var benchmarkingShow = '<input type="checkbox" class="benchmarkingShow">';
                var copyFlag = '<input type="checkbox" class="copyFlag">';
                if (target.required == 1) {
                    requiredTd = '<input type="checkbox" class="required" checked="checked">';
                }
                if (target.edit == 1) {
                    editTd = '<input type="checkbox" class="edit" checked="checked">';
                }
                if (target.supplierShow == 1) {
                    supplierShow = '<input type="checkbox" class="supplierShow" checked="checked">';
                }
                if (target.supplierEdit == 1) {
                    supplierEdit = '<input type="checkbox" class="supplierEdit" checked="checked">';
                }
                if (target.copyFlag == 1) {
                    copyFlag = '<input type="checkbox" class="copyFlag" checked="checked">';
                }
                if (target.benchmarkingShow == 1) {
                    benchmarkingShow = '<input type="checkbox" class="benchmarkingShow" checked="checked">';
                }
                var field_alias = !target.fieldAlias ? '' : target.fieldAlias;
                var remark = (target.remark) ? target.remark : '';
                //判断是否group为0,0表示基础字段
                if (field_group == 1) {
                    newFields += '<li>' +
                        '<table class="ui-form-table topline sort-area">' +
                        '<tr>' +
                        '<td width="5%" class="sort"></td>' +
                        '<td width="25%"><input type="hidden" class="field_id" value="' + target.fieldId + '"/>'
                        + '<input type="hidden" class="defaultFlag" value="' + target.defaultFlag + '"/>'
                        + target.labelName + '</td>' +
                        '<td width="15%"><input class="field_alias"  value="' + field_alias + '"/></td>' +
                        '<td width="7%">' + editTd + '</td>' +
                        '<td width="7%">' + requiredTd + '</td>' +
                        '<td width="8%">' + supplierShow + '</td>' +
                        '<td width="9%">' + supplierEdit + '</td>' +
                        '<td width="6%">' + copyFlag + '</td>' +
                        '<td width="5%">' + benchmarkingShow + '</td>' +
                        '<td width="8%">' + remark + '</td>' +
                        '<td width="5%"></td>' +
                        '</tr>' +
                        '</table>' +
                        '</li>';
                } else {
                    newFields += '<li>' +
                        '<table class="ui-form-table topline sort-area">' +
                        '<tr>' +
                        '<td width="5%" class="sort"></td>' +
                        '<td width="25%"><input type="hidden" class="field_id" value="' + target.fieldId + '"/>'
                        + '<input type="hidden" class="defaultFlag" value="' + target.defaultFlag + '"/>'
                        + target.labelName + '</td>' +
                        '<td width="15%"><input class="field_alias" value="' + field_alias + '"/></td>' +
                        '<td width="7%">' + editTd + '</td>' +
                        '<td width="7%">' + requiredTd + '</td>' +
                        '<td width="8%">' + supplierShow + '</td>' +
                        '<td width="9%">' + supplierEdit + '</td>' +
                        '<td width="6%">' + copyFlag + '</td>' +
                        '<td width="5%">' + benchmarkingShow + '</td>' +
                        '<td width="8%">' + remark + '</td>' +
                        '<td width="5%"><a onclick="del(this)">删除</a></td>' +
                        '</tr>' +
                        '</table>' +
                        '</li>';
                }
            });
            $('#data-list').append(newFields);

            //重新排序
            reSort();

            //初始化可拖动的函数
            $('#wrap').DDSort({
                target: 'li',
                floatStyle: {
                    'border': '1px solid #ccc',
                    'background-color': '#fff'
                }
            });
        },
        error: function () {
            topWin.layer.msg("查询模板数据出错了。");
        }
    });
}

// 选择字段
function selectField() {
    var fieldSelectDialog = openDialog("fieldSelectDialog", g.ctx + "pc/tender/template/page/fieldSelector", {
        title: "模板字段选择",
        width: 300,
        height: 753,
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            fieldSelectDialog.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            handler: function () {
                topWin.frames['fieldSelectDialog'].page.getChecked(function (rows) {
                    selectFieldCallBack(rows)
                    fieldSelectDialog.dialog('close');
                });
            }
        }, {
            text: '关闭',
            handler: function () {
                fieldSelectDialog.dialog('close');
            }
        }]
    });
}

// 选择字段回调函数
// 选择字段回调函数
function selectFieldCallBack(data) {
    if (!data) {
        return;
    }
    // topWin.layer.msg(data.length);
    var newFields = "";
    for (var i = 0; i < data.length; i++) {
        //去掉重复字段
        var isDuplicate = $('#wrap').find("input.field_id[value='" + data[i].id + "']");
        if (isDuplicate.length > 0) {
            continue;
        }
        var remark = (data[i].remark) ? data[i].remark : '';
        newFields += '<li>' +
            '<table class="ui-form-table topline sort-area">' +
            '<tr>' +
            '<td width="5%" class="sort"></td>' +
            '<td width="25%"><input type="hidden" class="field_id" value="' + data[i].id + '"/>'
            + '<input type="hidden" class="defaultFlag" value="' + data[i].defaultFlag + '"/>'
            + data[i].labelName + '</td>' +
            '<td width="15%"><input class="field_alias"/></td>' +
            '<td width="7%"><input type="checkbox" class="edit" value="1"></td>' +
            '<td width="7%"><input type="checkbox" class="required" value="1"></td>' +
            '<td width="8%"><input type="checkbox" class="supplierShow" value="1"></td>' +
            '<td width="9%"><input type="checkbox" class="supplierEdit" value="1"></td>' +
            '<td width="6%"><input type="checkbox" class="copyFlag" value="1"></td>' +
            '<td width="5%"><input type="checkbox" class="benchmarkingShow" value="1"></td>' +
            '<td width="8%">' + remark + '</td>' +
            '<td width="5%"><a onclick="del(this)">删除</a></td>' +
            '</tr>' +
            '</table>' +
            '</li>';
    }
    $('#data-list').append(newFields);

    //重新排序
    reSort();
}

/**
 * 重新排序的方法
 */
function reSort() {
    $('.sort').each(function (index) {
        $(this).html(index + 1);
    });
}

function del(obj) {
    $(obj).parents('li').remove();
    reSort();
}

// 保存模板信息
function saveOrUpdate(call) {
    if (submitFlag == 1) {
        return
    }
    if (!formValidate()) {
        return;
    }
    var formData = {
        tenderTypeId: $('#type').combobox("getValue"),
        name: $('#name').val(),
        copyFlag: type == 1 ? true : false,
        fields: []
    };
    var url = g.ctx + "pc/tender/template/rest/saveOrUpdate";
    formData.id = $('#id').val();
    var fields = [];
    var fieldArray = $(".sort-area tr");
    $.each(fieldArray, function (index, target) {
        var field = {};
        field.fieldId = $(this).find(".field_id").val();
        field.defaultFlag = $(this).find(".defaultFlag").val();
        field.fieldAlias = $(this).find(".field_alias").val();
        field.fieldSort = $(this).find('.sort').html();
        if ($(this).find(".supplierShow").is(':checked')) {
            field.supplierShow = 1;
        } else {
            field.supplierShow = 0;
        }
        if ($(this).find(".supplierEdit").is(':checked')) {
            field.supplierEdit = 1;
        } else {
            field.supplierEdit = 0;
        }
        if ($(this).find(".edit").is(':checked')) {
            field.edit = 1;
        } else {
            field.edit = 0;
        }
        if ($(this).find(".copyFlag").is(':checked')) {
            field.copyFlag = 1;
        } else {
            field.copyFlag = 0;
        }
        if ($(this).find(".required").is(':checked')) {
            field.required = 1;
        } else {
            field.required = 0;
        }
        if ($(this).find(".benchmarkingShow").is(':checked')) {
            field.benchmarkingShow = 1;
        } else {
            field.benchmarkingShow = 0;
        }
        fields.push(field);
    });
    if (fields.length <= 0) {
        topWin.layer.msg("扩展字段不能为空!");
        return;
    }
    formData.fields = fields;
    submitFlag = 1
    $.ajax({
        url: url,
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(formData),
        complete: function () {
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                call()
            });

        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

// 校验
function formValidate() {
    /**
     * 1、校验模板名称必填
     * 2、校验采购组必填
     * 3、校验当前采购组下的模板名称不重复
     * 4、字段、资质配置不能为空
     */
    var template_name = $("#name").val();
    if (!template_name || template_name == "") {
        topWin.layer.msg("请填写模板名称。");
        return false;
    }

    var tenderType = $('#type').combobox("getValue");
    if (!tenderType || tenderType == "") {
        topWin.layer.msg("请选择招标类型。");
        return false;
    }
    return true;
}