package com.patzn.lims.common;

import com.patzn.lims.online.entity.PtOnlFormField;
import com.patzn.lims.online.entity.PtOnlFormHead;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.List;

public class Tf {
    public static String getCtf(PtOnlFormHead head, List<PtOnlFormField> fields){
        String tableName = head.getTableName();
        String tableText = head.getTableTxt();
        StringBuffer sqlString = new StringBuffer();
        sqlString.append(" CREATE TABLE ");
        sqlString.append(tableName).append("(");
        for (PtOnlFormField field:fields) {
            sqlString.append(field.getDbFieldName());
            if ("Long".equals(field.getDbType())){
                sqlString.append(" int8 ");
            }else if ("String".equals(field.getDbType())){
                sqlString.append(" varchar(").append(field.getDbLength()).append(") ").append(" COLLATE pg_catalog.default ");
            }else if ("Date".equals(field.getDbType())){
                sqlString.append(" timestamp(0) ");
            }else if ("Integer".equals(field.getDbType())){
                sqlString.append(" int2 ");
            }else if ("BigDecimal".equals(field.getDbType())){
                sqlString.append("  numeric( ").append(field.getDbLength()).append(" ) ");
            }else if ("text".equals(field.getDbType())){
                sqlString.append("  text COLLATE pg_catalog.default ");
            }
            if (null != field.getDbIsNull()&&1==field.getDbIsNull()){
                sqlString.append(" NOT NULL ");
            }
            String defaultValue= field.getDbDefaultVal();
            if (StringUtils.isNotBlank(defaultValue)){
                 if ("Long".equals(field.getDbType())||"Integer".equals(field.getDbType())||"BigDecimal".equals(field.getDbType())){
                     sqlString.append(" DEFAULT  ").append(defaultValue).append(" ,");
                 }else{
                     sqlString.append(" DEFAULT  '").append(defaultValue).append("' ,");
                 }
            }else{
                sqlString.append(" DEFAULT NULL,");
            }
        }
        if (sqlString.length()>0){
            sqlString = sqlString.deleteCharAt(sqlString.length()-1);
        }
        sqlString.append("   ); ");
        for (PtOnlFormField field:fields) {
            if (StringUtils.isNotBlank(field.getDbFieldTxt())){
                sqlString.append(" COMMENT ON COLUMN  ").append(tableName).append(".").append(field.getDbFieldName());
                sqlString.append(" IS ").append("'").append(field.getDbFieldTxt()).append("' ;");
            }
        }
        sqlString.append(" COMMENT ON TABLE  ").append(tableName).append(" IS ").append("'").append(tableText).append("' ;");
        sqlString.append(" ALTER TABLE   ").append(tableName).append(" ADD CONSTRAINT  ").append(tableName).append("_pkey").append("  PRIMARY KEY (id); ");
        return  sqlString.toString();
    }
}
