/**
 * 表单校验规则配置明细页面JS
 * Created by 陈天仕 on 2025/8/26.
 */
const el = {
    form:'#form',
    id: '#id',
    filedBase: '#filedBase',
    filedBank: '#filedBank',
    fieldType: '#fieldType',
    fieldId: '#fieldId',
    fieldName: '#fieldName',
    fieldName2: '#fieldName2',
    characterOptions: '#characterOptions',
    symbolOptions: '#symbolOptions',
    currencyType: '#currencyType',
    minLength: '#minLength',
    maxLength: '#maxLength',
    fixedLength: '#fixedLength',
    makeMessageWay: '#makeMessageWay',
    validationMsg: '#validationMsg'
};

$(function () {
    initCombobox();

    initDefaultStatus();
});

/**
 * 初始化下拉框
 */
function initCombobox() {
    $(el.currencyType).combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '人民币', value: 'CNY'},
            {label: '非人民币', value: '0'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });
    $(el.fieldName2).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=supplier_bank_filed',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
}

/**
 * 设置初始状态
 */
function initDefaultStatus() {
    const makeMessageWay = $(el.makeMessageWay).val();
    const filedType = $(el.fieldType).combobox('getValue');
    toggleFieldVisibility(filedType);
    if (makeMessageWay === "on") {
        $(el.validationMsg).prop('readonly', true);
    }
    // 事件委托方式绑定
    $(el.characterOptions).on('change', '.character-option', function() {
        autoCreateMessage();
    });
    $(el.symbolOptions).on('change', '.character-option', function() {
        autoCreateMessage();
    });
    $(el.minLength).numberbox({
        onChange: function () {
            autoCreateMessage();
        }
    })
    $(el.maxLength).numberbox({
        onChange: function () {
            autoCreateMessage();
        }
    })
    $(el.fixedLength).numberbox({
        onChange: function () {
            autoCreateMessage();
        }
    })
    $(el.makeMessageWay).switchbutton({
        onChange: function (value) {
            if (value) {
                $(el.validationMsg).prop('readonly', true);
                autoCreateMessage();
            } else {
                $(el.validationMsg).prop('readonly', '');
            }
        }
    });
}

/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function saveData(callback) {
    const validate = $(el.form).form('validate');
    if (!validate) {
        layer.msg(commonMsg.msg2);
        return false;
    }
    const selectedId = [];
    $('input[type="checkbox"]:checked').each(function() {
        if (this.dataset.type === 'character') {
            selectedId.push(this.dataset.id);
        }
    });
    if (selectedId.length === 0) {
        layer.msg("请至少选择一种字符");
        return false;
    }
    const data = $(el.form).serializeJson();
    data.characterIdList = selectedId;
    data.fieldType = $(el.fieldType).combobox("getValue");
    if (data.fieldType === "BASE") {
        data.fieldId = $(el.fieldId).val();
    } else if (data.fieldType === "BANK") {
        data.fieldId2 = $(el.fieldName2).combobox("getValue");
        data.fieldName = $(el.fieldName2).combobox("getText");
    }
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/validationRuleSetting/rest/insertOrUpdate',
        data: data,
        success: function () {
            callback('');
        },
        error: function (data) {
            callback(data.responseJSON);
        }
    });
}

/**
 * 搜索字段
 */
function searchProperty(){
    let url = g.ctx + 'pc/sys/validationRuleSetting/select/fields'
    const fieldSelectDialog = openDialog('fieldSelectDialog', url, {
        title: '选择字段',
        width: '420px',
        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) {
                        if(rows.length > 1) {
                            topWin.layer.msg("选择的明细大于1条，默认使用第一条");

                        }
                        $(el.fieldId).val(rows[0].id);
                        $(el.fieldName).textbox('setValue', rows[0].labelName);
                        fieldSelectDialog.dialog('close');
                    });
                }
            }, {
                text: itablei8n.close, handler: function () {
                    fieldSelectDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 自动生成校验消息
 */
function autoCreateMessage() {
    const makeMessageWay = $(el.makeMessageWay).val();
    if (makeMessageWay === "on") {
        let message = "请输入正确格式，只允许："
        const checkedList = $('input[type="checkbox"]:checked');
        for (let i = 0, count = 0; i < checkedList.length; i++) {
            const checkedItem = checkedList[i];

            // 排除id为makeMessageWay的复选框
            if (checkedItem.dataset.type !== 'character') {
                continue; // 跳过当前循环
            }

            // 只有非空时才添加顿号
            if (count > 0) {
                message += "、";
            }

            message += "[ " + $(checkedItem).next('span').text() + " ]";
            count++;
        }
        const minLength = $(el.minLength).numberbox('getValue');
        if (minLength) {
            message += "，最小长度为：" + minLength;
        }
        const maxLength = $(el.maxLength).numberbox('getValue');
        if (maxLength) {
            message += "，最大长度为：" + maxLength;
        }
        const fixedLength = $(el.fixedLength).numberbox('getValue');
        if (fixedLength) {
            message += "，长度只能为：" + fixedLength;
        }
        $(el.validationMsg).val(message);
    }
}

function toggleFieldVisibility(value) {
    if (value === "BASE") {
        $(el.filedBank).hide();
        $(el.filedBase).show()
        $(el.fieldName).searchbox("enableValidation")
        $(el.fieldName2).combobox("disableValidation")
    } else {
        $(el.filedBank).show();
        $(el.filedBase).hide()
        $(el.fieldName).searchbox("disableValidation")
        $(el.fieldName2).combobox("enableValidation")
    }
}