'''
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import groovy.json.*

CONFIG_NAMESPACE = ""
CONFIG_SAVE_TO="D:\Work"

/*

  • Available context bindings:
  • SELECTION Iterable
  • PROJECT project
  • FILES files helper
    */

packageName = "com.sample;"
typeMapping = [
(~/(?i)integer/) : "int",
(~/(?i)bigint/) : "long",
(~/(?i)int/) : "int",//for mssql
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime|timestamp/) : "DateTime",
(~/(?i)date/) : "DateTime",
(~/(?i)time/) : "DateTime",
(~/(?i)numeric/) : "decimal",
(~/(?i)boolean/) : "Boolean",
(~/(?i)smallint/) : "short",
(~/(?i)/) : "string"

]

type2TypeScriptMapping = [
(~/(?i)integer/) : "number",
(~/(?i)bigint/) : "number",
(~/(?i)int/) : "number",//for mssql
(~/(?i)float|double|decimal|real/): "number",
(~/(?i)datetime|timestamp/) : "DateTime",
(~/(?i)date/) : "DateTime",
(~/(?i)time/) : "DateTime",
(~/(?i)numeric/) : "decimal",
(~/(?i)boolean/) : "bool",
(~/(?i)smallint/) : "number",
(~/(?i)/) : "string"

]

type2TypeScriptInitValueMapping = [
(~/(?i)integer/) : "0",
(~/(?i)bigint/) : "0",
(~/(?i)int/) : "0",//for mssql
(~/(?i)float|double|decimal|real/): "0",
(~/(?i)datetime|timestamp/) : "null",
(~/(?i)date/) : "null",
(~/(?i)time/) : "null",
(~/(?i)numeric/) : "0",
(~/(?i)boolean/) : "false",
(~/(?i)smallint/) : "0",
(~/(?i)/) : "''"

]

// FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
// SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
// }

SELECTION.filter { it instanceof DasTable }.each { generate(it, CONFIG_SAVE_TO) }

def generate(table, dir) {
def className = javaName(table.getName(), true)

def fields = calcFields(table)
new File(dir,className + "Model.cs").withPrintWriter("utf-8") //table.getName()
{ out ->

    out.println("namespace ${CONFIG_NAMESPACE};")
    out.println("")

    generate(out,table.getName(), className, fields)

    out.println("/**")

    generateEqaulCode(out,table.getName(),className,fields)
    generateInsertSql(out,table.getName(),className,fields)
    generateUpdateSql(out,table.getName(),className,fields)
    generateTypeScriptInterface(out,table.getName(),className,fields)


    generateComplex(out,table.getName(), className, fields)

    out.println("**/")

}
}

def generate(out,tableName, className, fields) {
out.println "using System;"
out.println "using Dapper.Contrib.Extensions;"
out.println ""
out.println ""
out.println "[Table(\"$tableName\")]"
out.println "public partial class " + className + "Model {"
out.println ""

fields.each() {

if (it.annos != "") out.println "  ${it.annos}"

if(it.col.comment){
    out.println " /// <summary>"
    out.println " /// ${it.col.comment}"
    out.println " /// </summary>"
}

if(it.isAutoKey){
    out.println " [Key]"
}

//不能为空
if(it.col.notNull) {

    if(it.type == "string"){
        out.println "  public ${it.type} ${it.name}  {get;set;} = null!; //${it.spec}"
    }
    else{
        out.println "  public ${it.type} ${it.name}  {get;set;}  //${it.spec} "
    }


}
else{
    out.println "  public ${it.type}? ${it.name}  {get;set;} //${it.spec}"
}

}
out.println ""

out.println "}"
}

//和 generate 类似,但会生成一个属性,描述column
def generateComplex(out,tableName, className, fields) {
out.println "using System;"
out.println "using Dapper.Contrib.Extensions;"
out.println ""
out.println ""
out.println "[Table(\"$tableName\")]"
out.println "public class " + className + "Model {"
out.println ""
fields.each() {

if (it.annos != "") out.println "  ${it.annos}"

if(it.col.comment){
    out.println " /// <summary>"
    out.println " /// ${it.col.comment}"
    out.println " /// </summary>"
}

if(it.isAutoKey){
    out.println " [Key]"
}

out.print " [Column("
out.print " Name=\"${it.col.name}\","
if (it.col.comment) out.print " Comment=\"${it.col.comment}\","
out.print " Position=${it.col.position},"
out.print " NotNull=${it.col.notNull},"
if (it.col.default) out.print " Default=\"${it.col.default}\""
out.print " )]"
out.println ""
out.println " public ${it.type} ${it.name}  {get;set;} //${it.spec}"

}
out.println ""

out.println "}"
}

def generateEqaulCode(out,table,className,fields){

//产生赋值语句
//左赋值
out.println ""
out.println ""
fields.each(){

out.println " model.${it.name}=data.${it.name};"

}

//右赋值
out.println ""
out.println ""
fields.each(){

out.println " data.${it.name}=model.${it.name};"

}
}

def generateTypeScriptInterface(out,table,className,fields){

//产生typescript 接口

out.println ""
out.println ""
out.println "interface " + className + "Model {"
fields.each(){

out.println "\t${it.name}:${it.typeScriptType};"

}
out.println "}"

out.println ""
out.println ""

//产生typescript 初始值

out.println ""
out.println ""
out.println "{"
fields.each(){

out.println "\t${it.name}:${it.typescriptTypeInitValue},"

}
out.println "}"

out.println ""
out.println ""

}

def generateInsertSql(out,table,className,fields){

//产生INSERT SQL语句
out.println ""
out.println ""
out.print " INSERT INTO ${table} ("

isFirst = true

fields.each(){

if(!isFirst){
    out.print ","
}else{
    isFirst = false
}



out.print " ${it.name}"

}
out.print " ) VALUES ("

isFirst = true
fields.each(){

if(!isFirst){
    out.print ","
}else{
    isFirst = false
}

out.print " @${it.name}"

}

out.print " ) "

}

def generateUpdateSql(out,table,className,fields){

//产生UPDATE SQL语句
out.println ""
out.println ""
out.print " UPDATE ${table} SET "

isFirst = true

fields.each(){

if(!isFirst){
    out.print ","
}else{
    isFirst = false
}


out.print " ${it.name} = @${it.name}"

}

out.print " WHERE "

}

def calcFields(table) {

//todo:获取col的key属性

DasUtil.getColumns(table).reduce([]) { fields, col ->

def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr =  typeMapping.find { p, t -> p.matcher(spec).find() }.value
def typescriptTypeStr = type2TypeScriptMapping.find { p, t -> p.matcher(spec).find() }.value
def typescriptTypeInitValue = type2TypeScriptInitValueMapping.find { p, t -> p.matcher(spec).find() }.value

fields += [[
             name : col.getName(),
             type : typeStr,
             typeScriptType:typescriptTypeStr,
             typescriptTypeInitValue:typescriptTypeInitValue,
             spec : spec,
             col  : col,
             isAutoKey : col.default ?  col.default.contains("nextval") : false,
             notNull : col.notNull,
             annos: ""]]

}
}

def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)

.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")

capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/*

col 可能有的属性,使用以下方法打印出来:

def mapProperties = it.col.getProperties()

    mapProperties.remove('class')//默认有自带class属性,移除减少数据传输量

    mapProperties.each(){
        out.println(it)
    }

以下为打印结果:

table=table:goods_category
presentation=column:category_id
visibilitySupported=false
dbParent=table:goods_category
caseSensitive=false
baseIcon=jar:file:/D:/Program%20Files/JetBrains/DataGrip%202019.1.2/plugins/DatabaseTools/lib/database-openapi.jar!/icons/col.svg
textOffset=0
presentableText=category_id
prevSibling=null
dasParent=table:goods_category
textLength=0
dependencies=[Ljava.lang.Object;@278f9448
metaData=column:category_id
containingFile=null
virtualFile=DB VirtualFile: column, gm_main.public.goods_category.category_id [gm_main@香港正式商城服务器] (Valid)
node=null
valid=true
dependences=[Ljava.lang.Object;@278f9448
default=nextval('goods_category_category_id_seq'::regclass)
language=Language: SQL
dataSource=root:gm_main@香港正式商城服务器
text=alter table goods_category

add category_id bigserial not null;

nextSibling=null
navigationElement=column:category_id
weight=10030
directory=false
locationString=gm_main.public.goods_category [gm_main@香港正式商城服务器]
firstChild=null
dataType=bigint
kind=column
textRange=null
position=1
comment=null
manager=com.intellij.psi.impl.PsiManagerImpl@23c13c2e
textRangeInParent=(0,0)
resolveScope=com.intellij.psi.search.ProjectScopeBuilderImpl$1@2
references=[Lcom.intellij.psi.PsiReference;@7b143e50
userDataEmpty=false
startOffsetInParent=0
context=table:goods_category
icon=Deferred. Base=jar:file:/D:/Program%20Files/JetBrains/DataGrip%202019.1.2/plugins/DatabaseTools/lib/database-openapi.jar!/icons/col.svg
lastChild=null
name=category_id
physical=false
originalElement=column:category_id
writable=true
tableName=goods_category
userDataString={CACHED_SMART_POINTER_KEY=com.intellij.reference.SoftReference@1e68b704}
userMap={CACHED_SMART_POINTER_KEY=com.intellij.reference.SoftReference@1e68b704}
delegate=category_id: column
notNull=true
typeName=column
useScope=com.intellij.psi.search.ProjectScopeBuilderImpl$1@2
documentation=

project=
*/
'''

标签: datagrip