/**
 * 生成每个表的creat Table sql
 * 作者：郑向阳(zxy@xinshi.net)
 * 创建时间：2020-1-29
 **/

function getType(field){
    if(field.fieldType=='string'){
        return "varchar(" + field.fieldSize + ")";
    }
    else if(field.fieldType=='number'){
        return "numeric(" + field.fieldSize + ")";
    }
    else if(field.fieldType=='date'){
        return "datetime";
    }
    else {
        return "varchar(128)";
    }
}

function getRequired(field){
    let required = field.required;
    if(required){
        required = required.toLowerCase();
        if(required=='true' || required=='t'){
            return "not null";
        }
    }
    return "";
}

function getFieldStatement(field,parentKey){
        let fieldName = field.origKey;
        if(parentKey){
            fieldName = parentKey + field.origKey;
        }
        if(fieldName=='group'){
            fieldName = "`group`";
        }
        let statement = fieldName +  " " + getType(field) + " " + getRequired(field);

        let fieldDesc = {
            fieldName:fieldName,
            fieldType:field.fieldType,
            fieldSize:field.fieldSize
        }
        return [statement,fieldDesc];
}

function getFieldStatements(formSpec,parentKey){
    let fieldStatements = [];
    let fieldDescriptions = [];
    let fields = formSpec.fields;
    for(let i=0; i<fields.length; i++){
        let field = fields[i];
        if(field._ft=='field' && field.fieldType!='image'){
            let st = getFieldStatement(field,parentKey);
            if(st){
                fieldStatements.push(st[0]);
                fieldDescriptions.push(st[1]);
            }
        }

        else if(field._ft=='subform'){
            let newParentKey = field.origKey;
            if(parentKey){
                newParentKey = parentKey + "__" + newParentKey;
            }

            let subStatements = getFieldStatements(field,newParentKey);
            if(subStatements){
                fieldStatements = fieldStatements.concat(subStatements[0]);
                fieldDescriptions = fieldDescriptions.concat(subStatements[1])
            }
        }
    }
    return [fieldStatements,fieldDescriptions];
}

function getUniIndex(tableName,field){
    let unique = field.unique;
    if(unique){
        unique = unique.toLowerCase();
        if(unique=='true' || unique=='t'){
            /*
            create unique index t_order_order_code_uindex on t_order (order_code);
             */
            let sql = `create unique index ${tableName}_${field.origKey}_uindex on ${tableName} (${field.origKey});`
            return sql;
        }
    }
    return null;
}

function getUniIndexes(tableName,formSpec){
    let sqls = [];
    let fields = formSpec.fields;
    for(let i=0; i<fields.length; i++){
        let field = fields[i];
        if(field._ft=='field' && field.fieldType!='image'){
            let st = getUniIndex(tableName,field);
            if(st){
                sqls.push(st);
            }
        }
        else if(field._ft=='subform'){
            let subsqls = getUniIndexes(tableName,field);
            if(subsqls){
                sqls = sqls.concat(subsqls);
            }
        }
    }
    return sqls;
}



function genSubTables(tableName, formSpec){
    let sqls = [];
    let tables = [];

    let fields = formSpec.fields;
    for(let i=0; i<fields.length; i++){
        let field = fields[i];
        if(field._ft=='array'){

            let subtableInfos = genTableSql(tableName+"__" + field.origKey,field,true,tableName);
            if(subtableInfos){
                // tableInfos = tableInfos.concat(subtableInfos);
                sqls = sqls.concat(subtableInfos[0]);
                tables = tables.concat(subtableInfos[1]);

            }
        }
    }
    return [sqls, tables];
}


function  genTableSql(tableName, formSpec,isSubTable,parentTableName) {
    let fieldInfos = getFieldStatements(formSpec);
    let fieldStatements = fieldInfos[0];
    let fieldDescriptions = fieldInfos[1];

    if(isSubTable){
        fieldStatements.push("id varchar(64) not null");
        fieldStatements.push("parentId varchar(64) not null");
        fieldStatements.push(`constraint foreign key (parentId) references ${parentTableName} (id) on update cascade on delete cascade`)
    }
    fieldStatements.push("_v int not null");
    // fieldDescriptions.push(  {fieldName:"_v",
    //     fieldType:"number",
    //     fieldSize:10
    // });
    fieldStatements.push("deleted bool not null default false");
    fieldStatements.push("_lastModified datetime not null default CURRENT_TIMESTAMP");
    let str = "create table " + tableName + " ( \n\t" + fieldStatements.join(",\n\t") + "\n);";
    let sqls = [str];
    let tables = [];

    tables.push({
        tableName:tableName,
        fieldDescriptions:fieldDescriptions
    });

    //开始生成uniqueIndex 和 PK index
    let primaryIndex = "create unique index " + tableName + "_id_uindex on " + tableName + " (id);"
    sqls.push(primaryIndex);

    let addPrimaryKeyConstraint = `alter table ${tableName} add constraint ${tableName}_pk primary key (id);`;
    sqls.push(addPrimaryKeyConstraint);


    //针对每一个unique字段生成一个unique index
    sqls = sqls.concat(getUniIndexes(tableName,formSpec));

    let subTableInfos = genSubTables(tableName,formSpec);
    sqls = sqls.concat(subTableInfos[0]);
    tables = tables.concat(subTableInfos[1]);

    //生成从表的table sqls
    // return sqls.join("\n\n");
    return [sqls,tables];
}


module.exports = {
    genTableSql: genTableSql
}