-- 字符脱敏处理

SET GLOBAL log_bin_trust_function_creators = 1;

CREATE 
	FUNCTION text_mask(text varchar(100), head_len int, tail_len int)
	RETURNS varchar(100)
BEGIN
	DECLARE t_len, m_len, mid_len int;
	DECLARE ret varchar(100);
	SET t_len = LENGTH(text);
	
	IF t_len = 0 THEN 
		SET ret = ''; 
	ELSEIF t_len = 1 THEN 
		SET ret = text; 
	ELSEIF t_len = 2 THEN 
		SET ret = CONCAT(LEFT(text, 1), '*');
	ELSE
		SET m_len = head_len + tail_len;
	
		IF m_len < t_len THEN 
			SET ret = CONCAT(LEFT(text, head_len), REPEAT('*', t_len - m_len), RIGHT(text, tail_len));
		ELSEIF m_len = t_len THEN 
			SET ret = CONCAT(LEFT(text, CASE WHEN head_len > 0 THEN head_len - 1 ELSE head_len END), '*', RIGHT(text, CASE WHEN head_len > 0 AND tail_len > 0 THEN tail_len ELSE tail_len - 1 END));
		ELSEIF head_len > t_len THEN 
			SET ret = CONCAT(LEFT(text, t_len - 1), '*'); 
		ELSEIF tail_len > t_len THEN 
			SET ret = CONCAT('*', RIGHT(text, t_len - 1)); 
		ELSE
			SET mid_len = CEIL(t_len / 2);
			SET ret = CONCAT(LEFT(text, mid_len - 1), REPEAT('*', t_len - (mid_len - 1) * 2), RIGHT(text, mid_len - 1)); 
		END IF;
	END IF;
	
	RETURN ret;
END;

SET GLOBAL log_bin_trust_function_creators = 0;