package cn.com.poc.common.utils;

import cn.com.poc.common.entity.BatchInsertResult;
import cn.com.yict.framemax.data.model.BaseModelClass;
import org.apache.commons.collections4.list.TreeList;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author alex.yao
 * @date 2024/1/8
 **/
public class SQLUtils {

    /**
     * 获取批量插入sql和参数
     *
     * @param modelClass
     * @param models
     * @return
     * @throws Exception
     */
    public static BatchInsertResult getInsertSql(Class<? extends BaseModelClass> modelClass, List<? extends BaseModelClass> models) throws Exception {
        //获取表名
        Table table = modelClass.getAnnotation(Table.class);
        String tableName = table.name();
        List<String> tableFieldList = new TreeList<>();
        List<String> modelGetMethodList = new TreeList<>();

        //获取实体类属性字段
        Method[] methods = modelClass.getMethods();
        for (Method method : methods) {
            if (!method.getName().startsWith("get")) {
                continue;
            }
            Column column = method.getAnnotation(Column.class);
            Id idAnnotation = method.getAnnotation(Id.class);
            if (idAnnotation != null || column == null) {
                continue;
            }
            tableFieldList.add(column.name());
            modelGetMethodList.add(method.getName());
        }
        BatchInsertResult result = new BatchInsertResult();
        //构造insert sql
        String fieldStr = tableFieldList.stream().collect(Collectors.joining(","));
        StringBuilder insertSQL = new StringBuilder();
        insertSQL.append("INSERT INTO ").append(tableName).append(" (").append(fieldStr).append(") VALUES ( ");
        for (int i = 0; i < tableFieldList.size(); i++) {
            if (i > 0) {
                insertSQL.append(", ");
            }
            insertSQL.append("?");
        }
        insertSQL.append(")");

        result.setInsertSQL(insertSQL.toString());

        //构造实体
        if (models != null) {
            List<Object[]> toInserteParams = new ArrayList<>(models.size());
            for (BaseModelClass model : models) {
                Object[] array = new Object[modelGetMethodList.size()];
                int i = 0;
                for (String getMethod : modelGetMethodList) {
                    Method method = modelClass.getMethod(getMethod);
                    array[i] = method.invoke(model);
                    i++;
                }
                toInserteParams.add(array);
            }
            result.setInsertParams(toInserteParams);
        }
        return result;
    }

}
