
import { Op, Sequelize } from "sequelize";
import { mysqlModelMap } from "../model/sqlModelBind";


/**
 * where条件查询参数
 * @param param 
 * %like%：模糊查询 {列名: {"%like%": }}
 * %gt%：大于 {列名: {"%gt%": }}
 * %gte%：大于等于 {列名: {"%gte%": }}
 * %lt%：小于 {列名: {"%lt%": }}
 * %lte%：小于等于 {列名: {"%lte%": }}
 * %between%：查询范围内数据 {列名: {"%between%": ["开始参数", "结束参数"]}} ---BETWEEN 开始参数 AND 结束参数
 * %notBetween%：查询不在范围内数据 {列名: {"%notBetween%": ["开始参数", "结束参数"]}} ---NOT BETWEEN 开始参数 AND 结束参数
 * %orderDesc%: order by DESC {"%orderDesc%": "列名"}
 * %limit%: {"%limit%": 数量}
 * @returns 
 */
function analysisParamToWhere(param) {
    let where = {};
    let order = [];
    let limit = 0;
    for (let key in param) {  
        if (typeof param[key] == "object") {
            where[key] = {};
            for (let whereKey in param[key]){
                switch(whereKey) {
                    case "%like%":
                        where[key][Op.like] = `%${param[key]["%like%"]}%`;
                    break;
                    case "%gt%":
                        where[key][Op.gt] = param[key]["%gt%"];
                    break;
                    case "%gte%":
                        where[key][Op.gte] = param[key]["%gte%"];
                    break;
                    case "%lt%":
                        where[key][Op.lt] = param[key]["%lt%"];
                    break;
                    case "%lte%":
                        where[key][Op.lte] = param[key]["%lte%"];
                    break;
                    case "%between%":
                        where[key][Op.between] = param[key]["%between%"];
                    break;
                    case "%notBetween%":
                        where[key][Op.notBetween] = param[key]["%notBetween%"];
                    break;
                    case "%in%":
                        where[key][Op.in] = param[key]["%in%"];
                    break;
                    case "%notIn%":
                        where[key][Op.notIn] = param[key]["%notIn%"];
                    break;
                }
            }
        }else {
            switch (key) {
                case "%orderDesc%":
                    order = [[Sequelize.col(param[key]), "DESC"]];
                break;
                case "%orderAsc%":
                    order = [[Sequelize.col(param[key]), "ASC"]];
                break;
                case "%limit%":
                    limit = param[key];
                break;
                default: where[key] = param[key];
            }
        }
    }

    let selectParam:any = {where};
    if (order && order.length) selectParam.order = order;
    if (limit) selectParam.limit = limit;
    return selectParam;
}


export async function updateManyData(tableName, param:object, data:object) {
    let tableModel = mysqlModelMap[tableName];
    let where = analysisParamToWhere(param);

    await tableModel.update(data, where);

    return {isSuccess:true};
}