package com.backendsys.exception;

import com.backendsys.utils.response.Result;
import com.backendsys.utils.response.ResultEnum;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class DuplicateKeyExceptionHandler {

    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        System.out.println("****** DuplicateKeyException.class: ******");
        System.out.println(e);

        String errorMessage = e.getMessage();
        // Error selecting key or setting result to parameter object.
        // Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'a1' for key 'sys_user.username'\n;
        // Duplicate entry 'a1' for key 'sys_user.username'

        // [fieldName] 使用正则表达式提取 字段名
        Pattern pattern = Pattern.compile("for key '(.*?)'");
        Matcher matcher = pattern.matcher(errorMessage);
        String fieldName = matcher.find() ? matcher.group(1) : null;

        //// [yml] 读取配置文件中的字段名和友好提示的对应关系
        //Yaml yaml = new Yaml();
        //Map<String, Object> config = null;
        //try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.yml")) {
        //    config = yaml.load(inputStream);
        //} catch (IOException ex) {
        //    // 处理配置文件读取错误
        //    ex.printStackTrace();
        //}

        //// [friendlyMessage] 获得自定义友好提示 (application.yml -> fieldMappings)
        //String friendlyMessage = null;
        //if (config != null && config.containsKey("fieldMappings")) {
        //    Map<String, Object> fieldMappings = (Map<String, Object>) config.get("fieldMappings");
        //    for (Map.Entry<String, Object> entry : fieldMappings.entrySet()) {
        //        String fieldKey = entry.getKey();
        //        if (errorMessage.contains(fieldKey)) {
        //            friendlyMessage = (String) entry.getValue();
        //            break;
        //        }
        //    }
        //}

        // [fieldValue] 获得字段的入参
        String fieldValue = null;
        String patternFieldValue = "Duplicate entry '(.+)' for key '";
        Pattern regex = Pattern.compile(patternFieldValue);
        Matcher matcherFieldValue = regex.matcher(errorMessage);
        if (matcherFieldValue.find()) {
            fieldValue = matcherFieldValue.group(1).trim();
        }

        //return Result.error(ResultEnum.UNIQUE_FIELD.getCode(), friendlyMessage , fieldName + ": " + fieldValue);
        return Result.error(ResultEnum.UNIQUE_FIELD.getCode(), fieldValue + " 已存在" , fieldName + ": " + fieldValue);
    }
}
