package com.eversec.kit.dev;

import com.eversec.kit.creator.ICreator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 业务元数据管理实现：
 * 1、将业务属性统一存贮到 "属性元数据中"，
 * 2、每个实体记录 "元属性的属性id" 、属性中文名称、是否必填、描述、备注
 * 3、业务实体 对应着多种功能，记录每种功能的业务元属性{}
 *
 * @author: liangxianyou at 2018/10/11 14:47.
 */
public class ImportTable {

    public static List<Table> tables(){
        List<Table> tables = new ArrayList<>();
        ICreator.sheetNames().forEach(k->{
            try {
                List<Map> list = ICreator.readExcelSheet(k);
                tables.add(toTable(list));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        return tables;
    }

    private static Table toTable(List<Map> list){
        list.remove(1);//list[0] head info
        Map rowHead = list.remove(0);

        String comment = getComment(rowHead);//list[1] comment,
        String tableName = getTableName(rowHead);

        Table table = new Table(tableName, comment);
        List<Table.Column> columns = new ArrayList<>();
        list.forEach(x->{
            //String name, String type, boolean notNull,String comment
            Table.Column column = new Table.Column(x.get("field") + "", x.get("cate") + "",
                    ICreator.isMust(x), x.get("remark1") + "");
            columns.add(column);
        });

        table.setColumns(columns);
        return table;
    }

    public static String getTableName(Map rowHead) {
        String field = rowHead.get("field")+"";

        int s = field.indexOf("(");
        if (s > 0){
            return field.substring(0, s);
        }
        return field;
    }


    public static String getComment(Map rowHead){
        String field = rowHead.get("field")+"";

        int s = field.indexOf("(");
        int e = field.indexOf(")");
        if (s > 0){
            return field.substring(s+1, e > 0 ? e : field.length());
        }
        return "";
    }
}
