package net.tccn.meta;

import lombok.Getter;
import lombok.Setter;
import net.tccn.base.BaseEntity;
import net.tccn.base.dbq.table.Field;
import org.redkale.persistence.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 元数据
 *
 * @author: liangxianyou at 2018/10/17 12:58.
 */
@Getter
@Setter
@Entity
@Table(name = "mtable", comment = "TABLE记录表")
@Cacheable(value = true, interval = 60 * 60 * 1000, direct = true)
public class MTable extends BaseEntity {
    @Id
    @Column(comment = "[表ID]")
    private Integer tableid;

    @Column(length = 64, comment = "[表名称]")
    private String tablename;

    @Column(length = 15, unique = true, comment = "[表别名]全库唯一，程序自动生成")
    private String alias;

    @Column(comment = "[表字段]")
    private List<Field> items;

    @Column(length = 64, comment = "[表注释]")
    private String comment;

    @Column(comment = "[临时]")
    private int hv;

    @Column(comment = "[状态]0 默认， 9删除'")
    private int status;

    @Column(comment = "[所属系统平台]")
    private Integer platid;

    @Column(comment = "[所属数据平台]")
    private Integer dbid;

    @Column(length = 32, comment = "[所在database]")
    private String catalog;

    // ------------------------------------------------
    public static MTable toAs(net.tccn.base.dbq.table.Table table) {
        List<Field> fields = table.getColumns().stream().map(Field::toAs).collect(Collectors.toList());

        MTable _bean = new MTable();
        _bean.setTablename(table.getName());
        _bean.setComment(table.getComment());
        _bean.setCatalog(table.getCatalog());
        _bean.setItems(fields);

        return _bean;
    }

    // 方法名getPK 报错，
    public String[] pk() {
        List<String> pks = items.stream().filter(x -> x.getPk() != null && x.getPk()).map(x -> x.getName()).collect(Collectors.toList());

        if (pks.size() > 0) {
            return pks.toArray(new String[pks.size()]);
        }

        //存在id字段，取id
        Optional<Field> any = items.stream().filter(x -> x.getName().equalsIgnoreCase("id")).findAny();
        return any.isPresent() ? new String[]{"id"} : new String[0];
    }
}
