package cn.axzo.workflow.common.model.request.form;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 表单字段权限信息
 *
 * @author wangli
 * @since 2024-11-07 11:09
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class FormPermissionMetaInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 字段标识
     */
    private String fieldId;

    /**
     * 字段名称
     */
    private String fieldName;

    /**
     * 可编辑必填
     */
    @Builder.Default
    private Boolean required = false;

    /**
     * 可编辑非必填
     */
    @Builder.Default
    private Boolean editable = false;

    /**
     * 只读
     */
    @Builder.Default
    private Boolean readonly = true;

    /**
     * 隐藏
     */
    @Builder.Default
    private Boolean hidden = false;
    /**
     * 前端回显字段，后端不做任何消费逻辑
     */
    private String value;

    // 将对象的属性转换为对应的整数表示
    public int toBinary() {
        int binaryValue = 0;
        binaryValue |= (required ? 1 : 0) << 3;
        binaryValue |= (editable ? 1 : 0) << 2;
        binaryValue |= (readonly ? 1 : 0) << 1;
        binaryValue |= (hidden ? 1 : 0);
        return binaryValue;
    }

    // 从整数表示还原出对象
    public static FormPermissionMetaInfo fromBinary(String fieldId, String fieldName, int binaryValue) {
        boolean required = ((binaryValue >> 3) & 1) == 1;
        boolean editable = ((binaryValue >> 2) & 1) == 1;
        boolean readonly = ((binaryValue >> 1) & 1) == 1;
        boolean hidden = (binaryValue & 1) == 1;
        return new FormPermissionMetaInfo(fieldId, fieldName, required, editable, readonly, hidden, null);
    }

    public FormPermissionMetaInfo toReadonly() {
        if (required || editable || readonly) {
            setRequired(false);
            setEditable(false);
            setReadonly(true);
            setHidden(false);
        }
        return this;
    }

    public String toBinaryString() {
        return String.format("%04d", Integer.parseInt(Integer.toBinaryString(toBinary()), 10));
    }
}
