package com.keyware.shandan.dynacmicform.core.db.parser;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keyware.shandan.dynacmicform.config.spring.ContextHelper;
import com.keyware.shandan.dynacmicform.core.basic.entity.FormInfoPo;
import com.keyware.shandan.dynacmicform.core.db.enums.DbColumns;
import com.keyware.shandan.dynacmicform.core.db.pojo.Column;
import com.keyware.shandan.dynacmicform.core.db.pojo.Table;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库表解析器
 */
public class TableInfoParser {
    private static final String ALTER_ADD = "ALTER_ADD";
    private static final String ALTER_MODIFY = "ALTER_MODIFY";
    private static final String ALTER_DROP = "ALTER_DROP";

    public static Table parseTable(@NotNull FormInfoPo form) {
        Table table = Table.builder()
                .name(form.getFormId())
                .comment(form.getFormName())
                .build();

        String dbType = ContextHelper.getDatabaseType();
        DbColumns dbColumns = DbColumns.valueOf(dbType);
        Assert.notNull(dbColumns, "该数据库不支持：" + dbType);

        JSONArray fieldConfigJson = JSONArray.parseArray(form.getFieldConfig());
        Assert.isTrue(fieldConfigJson != null && fieldConfigJson.size() > 0, "表单解析失败，没有发现字段配置");

        List<Column> columns = new ArrayList<>();
        fieldConfigJson.forEach(obj -> {
            JSONObject json = (JSONObject) obj;
            Column col = dbColumns.getDbDefault().getDbColumn(json.getString("tag"));
            col = parseColumn(json, col);
            if (col.isPrimary()) {
                Assert.isTrue(table.getPrimaryKey() == null, "表单信息解析失败，只能有一个字段为主键");
                table.setPrimaryKey(col);
            }
            columns.add(col);
        });

        // 未指定主键，则添加自增主键列
        if (table.getPrimaryKey() == null) {
            Column col = newPrimaryCol();
            table.setPrimaryKey(col);
            columns.add(col);
        }
        table.setColumns(columns);

        return table;
    }

    public static Column parseColumn(@NotNull JSONObject json, Column dbColumn) {
        Integer length = json.getInteger("fieldLength");
        if (length == null) {
            length = dbColumn.getLength();
        }
        Integer precision = json.getInteger("precision");
        if (precision == null) {
            precision = dbColumn.getPrecision();
        }
        return Column.builder()
                .id(json.getString("id"))
                .name(json.getString("fieldId"))
                .comment(json.getString("label"))
                .type(dbColumn.getType())
                .length(length)
                .precision(precision)
                .defaultValue(json.getString("defaultValue"))
                .isPrimary(json.getBooleanValue("isPrimary"))
                .notNull(json.getBooleanValue("notNull"))
                .build();
    }

    private static Column newPrimaryCol() {
        return Column.builder()
                .isPrimary(true)
                .name("ID")
                .type("INTEGER")
                .comment("自增主键")
                .length(10)
                .precision(null)
                .defaultValue(null)
                .build();
    }

    static class Comparator {

    }
}
