/**
 * js供应商注册模板管理detail
 * module/template/appointment.ftl
 * TemplateManagerController
 */

let el = {
    id: '#id',
    templateName: '#templateName',
    copyFlag: '#copyFlag',
    purchaseGroup: '#purchaseGroupCode',
    qualificationTemplate: '#qualificationTemplateCode',
    qualificationVersion: '#qualificationVersion',
    qualificationTable: '#qualificationTable',
    questionnaireTb: '#questionnaireTb',
    enableQuestionnaire: '#enableQuestionnaire',

    form: '#form'
};

$(function () {
    //编辑页面需要从后台查询模板数据
    let id = $(el.id).val();
    if (id) {
        initData(id);
    }

    initCombo();

    if ($(el.enableQuestionnaire).combobox('getValue') === 0) {
        $(el.questionnaireTb).hide();
    }

    $(el.enableQuestionnaire).combobox({
        onSelect: function (row) {
            if (row.value === 1) {
                $(el.questionnaireTb).show();
            } else {
                $(el.questionnaireTb).hide();
            }
        }
    })
});

$.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);
    });
};

/**
 * 初始化下拉框
 */
function initCombo() {
    //采购组
    $(el.purchaseGroup).combobox({
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        method: 'GET',
        valueField: 'purchaseGroupCode',
        textField: 'purchaseGroupName',
        panelHeight: 200,
        prompt: '-- 请选择 --',
        editable: true
    });
    initQualificationTemplate();
}

/**
 * 初始化资质模板下拉框
 */
function initQualificationTemplate() {
    $(el.qualificationTemplate).combogrid({
        idField: 'code',
        textField: 'name',
        method: 'GET',
        url: g.ctx + 'pc/supplier/qualification/rest/template/listAll?scene=1',
        panelHeight: 200,
        columns: [[{field: 'code', title: '编码', width: '30%'}, {
            field: 'name', title: '名称', width: '50%'
        }, {field: 'version', title: '版本', width: '20%'}]],
        prompt: '-- 请选择 --',
        editable: false,
        onSelect: function (index, row) {
            $(el.qualificationVersion).val(row.version);
            initQualification(row.code, row.version);
        }
    })
}

// 初始化数据，加载已配置的扩展字段或资质s
function initData(id) {
    $.ajax({
        url: g.ctx + 'pc/supplier/template/rest/getFields?templateId=' + id, type: "GET", success: function (data) {
            let fieldList = data.fieldList;
            $.each(fieldList, function (index, target) {
                let field_group = target.fieldGroup;
                let requiredTd = '<td><input type="checkbox" class="required" onclick="fieldRequired(this)" ></td>';
                if (target.required == 1) {
                    requiredTd = '<td><input type="checkbox" class="required" checked="checked" onclick="fieldRequired(this)" ></td>';
                }
                let field_alias = !target.fieldAlias ? '' : target.fieldAlias;
                let field = '<tr>' + '<td>' + '<input type="hidden" class="field_id" value="' + target.fieldId + '"/>' + '<input type="hidden" class="templateFieldId" value="' + target.templateFieldId + '"/>' + target.labelName + '</td>' + '<td><input class="field_alias"  value="' + field_alias + '" defaultAlias="' + field_alias + '"  onblur="fieldAlias(this)"/></td>' + requiredTd + '<td>' + '<a onclick="sort_up(this)" style="margin-right: 10px;">上</a>' + '<a onclick="sort_down(this)" style="margin-right: 10px;">下</a>' + '<a onclick="fieldDel(this)">删除</a>' + '</td>';
                // 根据分组加入到不同table中
                $("#fieldGroup_" + field_group).find("tbody").append(field);
                $("#fieldGroup_" + field_group).find("tbody").dragSort();
            });
        }, error: function (data) {
            topWin.layer.close(index);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2});
        }
    });

    let qualificationTemplateCode = $(el.qualificationTemplate).combobox('getValue');
    let qualificationTemplateVersion = $(el.qualificationVersion).val();

    initQualification(qualificationTemplateCode, qualificationTemplateVersion);

    /**
     * 初始化问卷调查项
     */

    $.ajax({
        url: g.ctx + 'pc/supplier/questionnaire/rest/listByTemplateId?templateId=' + id,
        type: "GET",
        success: function (data) {
            questionnaireSelectedBack(data);
        },
        error: function (data) {
            topWin.layer.close(index);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2});
        }
    });
}

function initQualification(templateCode, version) {
    $.ajax({
        url: g.ctx + 'pc/supplier/qualification/rest/template/item/listByTemplateCode?templateCode=' + templateCode + "&version=" + version,
        type: "GET",
        success: function (data) {
            if (data) {
                $.each(data, function (index, target) {
                    let field = '<tr>' + '<td>' + '<input type="hidden" class="id" value="' + target.id + '"/>' + target.code + '</td>' + '<td>' + target.name + '</td>';
                    if (target.requery === 0) {
                        field += '<td>非必填</td>'
                    } else {
                        field += '<td>必填</td>'
                    }
                    $("#qualificationTable").find("tbody").append(field);
                });
            }
        },
        error: function (data) {
            topWin.layer.close(index);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2});
        }
    });
}

// 选择字段
function selectField(field_group) {
    let url = g.ctx + 'pc/supplier/template/page/select/fields'
    const fieldSelectDialog = openDialog('fieldSelectDialog', url, {
        title: '选择字段',
        width: '400px',
        height: '600px',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            fieldSelectDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm, handler: function () {
                    topWin.frames['fieldSelectDialog'].page.getChecked(function (rows) {
                        fieldSelectDialog.dialog('close');
                        selectFieldCallBack(field_group, rows);
                    });
                }
            }, {
                text: itablei8n.close, handler: function () {
                    fieldSelectDialog.dialog('close');
                }
            }
        ]
    });
}

// 选择字段回调函数
function selectFieldCallBack(field_group, data) {
    if (!data) {
        return;
    }

    // layer.msg(data.length);
    let newFields = "";
    for (let i = 0; i < data.length; i++) {
        //去掉重复字段
        let isDuplicate = $("#fieldGroup_" + field_group).find("input.field_id[value='" + data[i].id + "']");
        if (isDuplicate.length > 0) {
            continue;
        }
        let field;
        if (field_group == 2) {
            field = '<tr>' + '<td><input type="hidden" class="field_id" value="' + data[i].id + '"/>' + data[i].labelName + '</td>' + '<td><input class="field_alias" placeholder="' + data[i].remark + '"/></td>' + '<td><input type="checkbox" checked 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 {
            field = '<tr>' + '<td><input type="hidden" class="field_id" value="' + data[i].id + '"/>' + data[i].labelName + '</td>' + '<td><input class="field_alias" placeholder="字段别名"/></td>' + '<td><input type="checkbox" checked 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>';
        }

        newFields += field;
    }
    $("#fieldGroup_" + field_group).find("tbody").append(newFields);
    $("#fieldGroup_1").find("tbody").dragSort();
}


/**
 * 打开问卷调查选择项
 */
function questionnaireSelector() {
    let url = g.ctx + 'pc/supplier/questionnaire/page/index?select=1'
    const questionSelectDialog = openDialog('questionSelectDialog', url, {
        title: '选择问卷题目',
        width: '850px',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            questionSelectDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm, handler: function () {
                    topWin.frames['questionSelectDialog'].page.getChecked(function (rows) {
                        questionSelectDialog.dialog('close');
                        questionnaireSelectedBack(rows);
                    });
                }
            }, {
                text: itablei8n.close, handler: function () {
                    questionSelectDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 问卷调查选择回调函数
 * @param rows
 */
function questionnaireSelectedBack(rows) {
    if (rows.length !== 0) {
        let questionnaireTBody = $(el.questionnaireTb).find("tbody");
        let trRows = questionnaireTBody.find('tr');
        let obj = {};
        if (trRows.length !== 0) {
            for (let i = 0, length = trRows.length; i < length; i++) {
                let tr = $(trRows[i]).find('input[name="id"]');
                let code = $(tr).val();
                obj[code] = 1;
            }
        }
        let html = '';
        for (let i = 0, length = rows.length; i < length; i++) {
            let row = rows[i];
            if (!obj[row['id']]) {
                let required = row['required'] === 0 ? '非必填' : '必填';
                html += '<tr>' + '<td><input type="hidden" name="id" value="' + row['id'] + '">' + row['questionCode'] + '</td>' + '<td>' + row['questionDesc'] + '</td>' + '<td>' + required + '</td>' + '<td><a onclick="del(this)">删除</a></td>' + '</tr>'
            }
        }
        questionnaireTBody.append(html);
        questionnaireTBody.dragSort();
    }
}

function sort_up(obj) {
    let _this = $(obj);
    let _index = _this.parent().parent().index();
    if (_index == 0) {
        topWin.layer.msg("已经是最前面了");
    }
    let _moveObj = _this.parent().parent();
    let _prevObj = _this.parent().parent().prev();
    _moveObj.insertBefore(_prevObj);
}

function sort_down(obj) {
    let _this = $(obj);
    let _index = _this.parent().parent().index();
    let length = _this.parent().parent().siblings("tr").length;
    if (_index == length) {
        topWin.layer.msg("已经是最后面了");
    }
    let _moveObj = _this.parent().parent();
    let _nextObj = _this.parent().parent().next();
    _moveObj.insertAfter(_nextObj);
}

function del(obj) {
    $(obj).parent().parent().remove();
}

// 保存模板信息
function saveOrUpdate(call) {
    let validate = formValidate();
    if (!validate) {
        topWin.layer.msg('信息未填写完整');
        return;
    }
    let formData = {
        id: $(el.id).val(),
        copyFlag: $(el.copyFlag).val(),
        templateName: $(el.templateName).val(),
        purchaseGroupCode: $(el.purchaseGroup).combobox('getValue'),
        qualificationTemplateCode: $(el.qualificationTemplate).combobox('getValue'),
        enableQuestionnaire: $(el.enableQuestionnaire).combobox('getValue'),
        qualificationVersion: $(el.qualificationVersion).val(),
        fields: []
    };
    let fields = [];

    let fieldArray = $("#fieldGroup_1 tbody tr");
    $.each(fieldArray, function (index, target) {
        let field = {};
        field.fieldId = $(this).find(".field_id").val();
        field.fieldAlias = $(this).find(".field_alias").val();
        field.fieldSort = index;
        if ($(this).find(".required").is(':checked')) {
            field.required = 1;
        } else {
            field.required = 0;
        }
        fields.push(field);
    });

    /**
     * 获取问卷调查项目
     */
    let questionnaireList = [];
    let questionnaireTB = $(el.questionnaireTb).find('tbody tr');
    for (let i = 0, length = questionnaireTB.length; i < length; i++) {
        let tr = $(questionnaireTB[i]).find('input[name="id"]');
        let code = $(tr).val();
        if (code) {
            questionnaireList.push(code);
        }
    }
    formData.fields = fields;
    formData.questionnaireList = questionnaireList;
    $.ajax({
        url: g.ctx + "pc/supplier/template/rest/saveOrUpdate",
        method: "post",
        data: JSON.stringify(formData),
        contentType: 'application/json',
        async: false,
        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、字段、资质配置不能为空
     */
    let template_name = $(el.templateName).val();
    if (!template_name || template_name == "") {
        topWin.layer.msg("请填写模板名称。");
        return false;
    }
    let fieldArray = $(".fieldTable tbody tr");
    if (!fieldArray || fieldArray.length <= 0) {
        topWin.layer.msg("请选择字段信息。");
        return false;
    }
    let qualificationTemplate = $(el.qualificationTemplate).combobox('getValue');
    if (!qualificationTemplate) {
        topWin.layer.msg('请选择资质模板');
        return false;
    }

    return true;
}

// 选择字段必填性修改
function fieldRequired(obj) {
    let id = $(obj).parent().prev().prev().find(".templateFieldId").val();
    let required = $(obj).is(":checked") ? 1 : 0;
}

// 选择字段删除
function fieldDel(obj) {
    $(obj).parent().parent().remove();
    let id = $(obj).parent().prev().prev().prev().find(".templateFieldId").val();
}
