
package com.lideeyunji.core.framework.config.validate;

import com.lideeyunji.core.framework.service.IFrameService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.core.framework.utils.FuncWeb;
import com.lideeyunji.tool.framework.exception.lideeYunJiException;
import com.lideeyunji.tool.framework.yunji.adapter.IlideeYunjiValidate;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import com.lideeyunji.tool.framework.yunji.utils.lideeYunJiUtils;
import com.lideeyunji.tool.framework.yunji.component.properties.lideeYunjiProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 复制时
 * 校验表名是否合法
 */
@Component
public class DbFormCopyValidate implements IlideeYunjiValidate {

    @Lazy
    @Autowired
    private IFrameService frameService;

    @Override
    public void validate(HttpServletRequest req) throws lideeYunJiException {
        Map<String, Object> parameterMap = FuncWeb.getParameterMap(req);
        String tableName = lideeYunJiUtils.getMap2Str(parameterMap, "tableName");

        if (FuncBase.isEmpty(tableName)) {
            throw new lideeYunJiException("表名不允许为空");
        }

        if (!Func.checkTableName(tableName)) {
            StringJoiner joiner = new StringJoiner(",");
            lideeYunjiProperties.getExcludeTableNames().forEach(joiner::add);
            String errorMsg = joiner.toString();
            throw new lideeYunJiException(String.format("表名称不允许以【%s】开头", errorMsg));
        }
        //校验表名是否重复
        if (frameService.checkTable(tableName)) {
            String errorStr = String.format("数据库表【%s】已存在", tableName);
            throw new lideeYunJiException(errorStr);
        }

    }
}
