package com.qmth.teachcloud.common.util;

import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

/**
 * @Description: 数据库异常解析
 */
public class JdbcErrorUtil {
    private final static Logger log = LoggerFactory.getLogger(JdbcErrorUtil.class);

    /**
     * 解析数据库异常
     *
     * @return
     */
    public static String parseErrorMsg(String error) {
        String content = null;
        String msg = "";
        // 唯一索引报错
        if (error.contains("Duplicate entry")) {
            int startIndex = error.lastIndexOf("for key");
            content = error.substring(startIndex + "for key".length());
            msg = "违反数据库唯一规则，请联系管理员处理";
        }
        // 字段不存在
        else if (error.contains("Unknown column")) {
            int startIndex = error.lastIndexOf("Unknown column");
            int endIndex = error.lastIndexOf("in 'field list'");
            content = error.substring(startIndex + "Unknown column".length(), endIndex);
            msg = "字段在数据库中不存在，请联系管理员处理";
        }
        // 字段超过最大长度
        else if (error.contains("Data too long")) {
            int startIndex = error.lastIndexOf("Data too long for column");
            int endIndex = error.lastIndexOf("at");
            content = error.substring(startIndex + "Data too long for column".length(), endIndex);
            msg = "字段值超过数据库最大长度";
        }
        // 必填项，没填值
        else if (error.contains("doesn't have a default value")) {
            int startIndex = error.lastIndexOf("Field");
            int endIndex = error.lastIndexOf("doesn't have a default value");
            content = error.substring(startIndex + "Field".length(), endIndex);
            msg = "字段数据库设置为必填，但实际值为空";
        }
        if (StringUtils.isNotBlank(content)) {
            return content.trim() + msg;
        } else {
            return error;
        }
    }

}
