import { mysqlDB } from "./mysqlInit";


/**
 * mysql数据表实体类
 */
export class mySqlTableClass {
    file;//字段对象
    tableName;//表名
    sql;//sql
    moreTableSql;//多表sql

    constructor(tableName:string, file?, sqlEnum?, moreSqlEnum?) {
        this.tableName = tableName;
        this.file = file || {};
        this.sql = sqlEnum || {};
        this.moreTableSql = moreSqlEnum || {};
    }

    /**
     * 查询单表
     * @param param 条件参数
     * @param res 指定返回
     */
    async find(param, res?) {
        let sqlStr = 'select ';
        if (!res) sqlStr += '* ';
        else {
            res.forEach((itemStr, index) => {
                sqlStr += itemStr;
                if (index == res.length - 1) sqlStr += ' ';
                else sqlStr += ', ';
            });
        }
        sqlStr += `from ${this.tableName} `;

        const KeyLength = Object.keys(param).length;
        
        let valueList = [];
        if ( KeyLength > 0) {
            sqlStr += 'where ';
            let index = 0;
            for (let key in param) {
                sqlStr += `${key} = ?`;
                valueList.push(param[key]);
                if (index < KeyLength - 1) sqlStr += ', ';
                else sqlStr += ' ';
                index += 1;
            }
        }

        return await mysqlDB.selectData(sqlStr, valueList);
    }

    /**
     * 查询单个
     * @param param 
     * @param res 
     * @returns 
     */
    async findOne(param, res?) {
        let sqlStr = 'select ';
        if (!res) sqlStr += '* ';
        else {
            res.forEach((itemStr, index) => {
                sqlStr += itemStr;
                if (index == res.length - 1) sqlStr += ' ';
                else sqlStr += ', ';
            });
        }
        sqlStr += `from ${this.tableName} `;

        const KeyLength = Object.keys(param).length;
        
        let valueList = [];
        if ( KeyLength > 0) {
            sqlStr += 'where ';
            let index = 0;
            for (let key in param) {
                sqlStr += `${key} = ?`;
                valueList.push(param[key]);
                if (index < KeyLength - 1) sqlStr += ', ';
                else sqlStr += ' ';
                index += 1;
            }
        }

        return await mysqlDB.findOne(sqlStr, valueList);
    } 

    /**
     * 修改
     * @param table 
     * @param param 
     * @param contition 
     * @returns 
     */
    async update(param:object, contition:object) {
        return await mysqlDB.updateData(this.tableName, param, contition);
    }

    /**
     * 删除
     * @param paramater 
     * @returns 
     */
    async delete(paramater:object) {
        return await mysqlDB.deleteData(this.tableName, paramater);
    }

    /**
     * 创建
     * @param param 
     * @returns 
     */
    async install(param:object) {
        return await mysqlDB.createData(this.tableName, param);
    }
}