const system = require("../../../system");
const Dao = require("../../dao.base");
const when = require('when');
const bindCallback = require('when/node').bindCallback;

class ecloudsignDao extends Dao {
    constructor() {
        super(Dao.getModelName(ecloudsignDao));
    }
    //公共查询
    async selectFields(tableName, fieldArray, where) {

        var fieldString = null;
        if (fieldArray.length === 0)
            fieldString = '*';
        else {
            for (let i = 0; i < fieldArray.length; i++) {
                if (fieldString === null)
                    fieldString = fieldArray[i];
                else
                    fieldString = fieldString + "," + fieldArray[i]
            }
        }

        let whereKeys = Object.keys(where);
        let whereValues = Object.values(where);
        let whereString = null;

        for (let i = 0; i < whereKeys.length; i++) {
            let where = null;
            where = whereKeys[i] + " = " + whereValues[i];
            if (whereString === null)
                whereString = where;
            else
                whereString = whereString + " AND " + where;
        }

        let selectQuery = null;
        if (whereString === null)
            selectQuery = "SELECT " + fieldString + " FROM " + tableName;
        else
            selectQuery = "SELECT " + fieldString + " FROM " + tableName + " WHERE " + whereString;
        console.log(selectQuery);
        return this.customQuery(selectQuery);
    }

    //公共添加
    async addRecord(tableName, fieldList) {
        let keys = Object.keys(fieldList);
        let values = Object.values(fieldList);
        let fields = null;
        let field_values = null;
        for (let i = 0; i < keys.length; i++) {
            if (fields === null) {
                fields = keys[i];
            } else {
                fields = fields + "," + keys[i];
            }

            if (typeof values[i] === 'string') {
                if (field_values === null)
                    field_values = '"' + values[i] + '"';
                else
                    field_values = field_values + "," + '"' + values[i] + '"';
            } else {
                if (field_values === null)
                    field_values = values[i];
                else
                    field_values = field_values + "," + values[i];
            }
        }
        let insertQuery = "INSERT INTO " + tableName + " (" + fields + ") values (" + field_values + ")";
        console.log(insertQuery);
        return this.customInsert(insertQuery);
    }


}

module.exports = ecloudsignDao;