var el = {
    form : '#form',
    optType : '#optType',
    id : '#id',
    templateCode : '#templateCode',
    templateName : '#templateName',
    purchaseGroupCode: '#purchaseGroupCode',
};


$(function () {
    initCombo();
});
function initCombo() {
    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        // panelHeight: 200,
        // panelWidth: 240,
        prompt: '--- 未选择则为全部采购组 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll'
    });
    $("#fieldGroup_1").find("tbody").dragSort();
    $("#fieldGroup_2").find("tbody").dragSort();
    $("#fieldGroup_3").find("tbody").dragSort();
}

/**
 * 字段向上排序
 *
 * @param obj 针对的页面DOM
 */
function sort_up(obj) {
    var _this = $(obj);
    var _index = _this.parent().parent().index();
    if (_index === 0) {
        layer.msg('已经是最前面了', {icon: 0});
    }
    var _moveObj = _this.parent().parent();
    var _prevObj = _this.parent().parent().prev();
    _moveObj.insertBefore(_prevObj);
}


/**
 * 字段向下排序
 *
 * @param obj 针对的页面DOM
 */
function sort_down(obj) {
    var _this = $(obj);
    var _index = _this.parent().parent().index();
    var length = _this.parent().parent().siblings("tr").length;
    if (_index === length) {
        layer.msg('已经是最后面了', {icon: 0});
    }
    var _moveObj = _this.parent().parent();
    var _nextObj = _this.parent().parent().next();
    _moveObj.insertAfter(_nextObj);
}

/**
 * 删除选中的字段
 *
 * @param obj 针对的页面DOM
 */
function del(obj) {
    $(obj).parent().parent().remove();
}

$.fn.dragSort = function () {
    let $tr, $tr_drag, $tr_drop;
    $tr = $(this).find("tr");
    $tr.prop("draggable", "true");
    $tr.on("dragstart", function () {
        $tr_drag = $(this);
    }).on("dragleave", function (e) {
        $tr_drop.removeClass("alert-success");
    }).on("dragover", function (e) {
        $tr_drop = $(e.target).parent("tr");
        $tr_drop.addClass("alert-success");
        e.preventDefault();
    }).on("drop", function (e) {
        $tr_drop.removeClass("alert-success");
        $(this).before($tr_drag);
    });
};


/**
 * 选择字段
 *
 * @param fieldGroup 字段分组
 */
function selectField(fieldGroup) {
    var selectFieldElement = openDialog("selectFieldDialog", g.ctx + 'pc/inquiry/template/field/select?fieldGroup=' + fieldGroup, {
        title: '选择字段',
        width: '30%',
        height: '75%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            selectFieldElement.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['selectFieldDialog'].selectField(function (data) {
                    var newFields = '';
                    for (var i = 0; i < data.length; i++) {
                        // 去掉重复字段
                        var isDuplicate = $('#fieldGroup_' + fieldGroup).find("input.fieldId[value='" + data[i].fieldId + "']");
                        if (isDuplicate.length > 0) {
                            continue;
                        }
                        var field = '';
                        if (Number(fieldGroup) === 2) {
                            field = '<tr>' +
                                '<td><input type="hidden" class="fieldId" value="' + data[i].fieldId + '"/>' + data[i].labelName + '</td>' +
                                '<td><input class="fieldAlias" placeholder="' + data[i].remark + '" value="'+data[i].remark+'"/></td>' +
                                '<td><input type="checkbox" class="required" value="1"></td>' +
                                '<td>' +
                                '<a onclick="sort_up(this)" style="margin-right: 10px;">上</a>' +
                                '<a onclick="sort_down(this)" style="margin-right: 10px;">下</a>' +
                                '<a onclick="del(this)">删除</a>' +
                                '</td>';
                        } else if (Number(fieldGroup) === 1){
                            field = '<tr>' +
                                '<td><input type="hidden" class="fieldId" value="' + data[i].fieldId + '"/>' + data[i].labelName + '</td>' +
                                '<td><input class="fieldAlias"/></td>' +
                                '<td><input class="labelWidth" type="number" value="'+data[i].labelWidth+'"/></td>' +
                                '<td><input type="checkbox" class="allowEditFlag" value="1"></td>' +
                                '<td><input type="checkbox" class="fixLookFlag" value="0"></td>' +
                                '<td><input type="checkbox" class="required" value="1"></td>' +
                                '<td><input type="checkbox" class="copyFlag" value="0"></td>' +
                                '<td>' +
                                '<a onclick="sort_up(this)" style="margin-right: 10px;">上</a>' +
                                '<a onclick="sort_down(this)" style="margin-right: 10px;">下</a>' +
                                '<a onclick="del(this)">删除</a>' +
                                '</td>';
                        }else if (Number(fieldGroup) === 3){
                            field = '<tr>' +
                                '<td><input type="hidden" class="fieldId" value="' + data[i].fieldId + '"/>' + data[i].labelName + '</td>' +
                                '<td><input class="fieldAlias"/></td>' +
                                '<td><input class="labelWidth" type="number" value="'+data[i].labelWidth+'"/></td>' +
                                '<td><input type="checkbox" class="supplierLookFlag" value="0"></td>' +
                                '<td><input type="checkbox" class="required" value="1"></td>' +
                                '<td><input type="checkbox" class="copyFlag" value="0"></td>' +
                                '<td>' +
                                '<a onclick="sort_up(this)" style="margin-right: 10px;">上</a>' +
                                '<a onclick="sort_down(this)" style="margin-right: 10px;">下</a>' +
                                '<a onclick="del(this)">删除</a>' +
                                '</td>';
                        }
                        newFields += field;
                    }
                    $('#fieldGroup_' + fieldGroup).find('tbody').append(newFields);
                    $("#fieldGroup_" + fieldGroup).find("tbody").dragSort();
                    selectFieldElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                selectFieldElement.dialog('close');
            }
        }]
    });
}


function saveOrUpdate(call) {
    if($(el.form).form('validate')){
        var optType = $(el.optType).val(), id = '';
        if(Number(optType) === 0||Number(optType) === 2){
            id = ''
        }else {
            id = $(el.id).val();
        }
        var formData = {
            id: id,
            templateCode: $(el.templateCode).textbox('getValue'),
            templateName: $(el.templateName).textbox('getValue'),
            purchaseGroupCode : $(el.purchaseGroupCode).combobox('getValue'),
            fields: []
        };
        var fields = [];

        var fieldArray = $('.fieldTable tbody tr');
        $.each(fieldArray, function (index, target) {
            var field = {};
            field.fieldId = $(this).find('.fieldId').val().replace(/,/g,'');
            field.fieldAlias = $(this).find('.fieldAlias').val();
            field.labelWidth = $(this).find('.labelWidth').val();
            field.fieldSort = index;
            if ($(this).find('.supplierLookFlag').is(':checked')) {
                field.supplierLookFlag = 1;
            } else {
                field.supplierLookFlag = 0;
            }
            if ($(this).find('.allowEditFlag').is(':checked')) {
                field.allowEditFlag = 1;
            } else {
                field.allowEditFlag = 0;
            }
            if ($(this).find('.fixLookFlag').is(':checked')) {
                field.fixLookFlag = 1;
            } else {
                field.fixLookFlag = 0;
            }
            if ($(this).find('.required').is(':checked')) {
                field.required = 1;
            } else {
                field.required = 0;
            }
            if ($(this).find('.copyFlag').is(':checked')) {
                field.copyFlag = 1;
            } else {
                field.copyFlag = 0;
            }
            fields.push(field);
        });

        formData.fields = fields;

        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/template/rest/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}