using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
    public static class StringEx
    {
        /// <summary>
        /// 时间格式转换
        /// </summary>
        /// <returns>格式(MM-dd)</returns>
        public static string ToSymbolMarkString(this string str)
        {
            return GetSymbolMark(str, '*', 3);
        }

        /// <summary>
        /// 特殊字符遮罩部分字符
        /// </summary>
        /// <param name="str">需要特殊符号遮罩处理的字符串</param>
        /// <param name="symbol">特殊符号</param>
        /// <param name="len">首尾正常显示长度</param>
        /// <returns></returns>
        public static string GetSymbolMark(string str, char symbol, int len)
        {
            if (!string.IsNullOrEmpty(str))
            {
                int dotLastIndex = str.LastIndexOf('.');
                if (dotLastIndex > -1)
                {
                    //邮箱地址
                    var prefix = str.Substring(0, dotLastIndex);
                    var suffix = str.Substring(dotLastIndex);
                    str = GetMarkHandle(prefix, symbol, len) + suffix;
                }
                else
                {
                    //普通字符串
                    str = GetMarkHandle(str, symbol, len);
                }
            }
            return str;
        }

        /// <summary>
        /// 对字符串直接遮罩
        /// </summary>
        /// <param name="str">需要特殊符号遮罩处理的字符串</param>
        /// <param name="symbol">特殊符号</param>
        /// <param name="len">首尾正常显示长度</param>
        /// <returns></returns>
        private static string GetMarkHandle(string str, char symbol, int len)
        {
            int strLength = str.Length;
            if (strLength < 5)
            {
                string symbolToString = symbol.ToString();
                switch (strLength)
                {
                    case 1: { return str = symbolToString; }
                    case 2: { return str = symbolToString + symbolToString; }
                    case 3: { return str = symbolToString + symbolToString + symbolToString; }
                    case 4: { return str = symbolToString + str.Substring(1, 2) + symbolToString; }
                    default: { break; }
                }
                return str;
            }

            int symbolStrLength = strLength - len * 2;
            if (symbolStrLength < 1)
            {
                len = 2;
            }
            string symbolStr = string.Empty;
            for (int n = 0; n < symbolStrLength; n++)
            {
                symbolStr += symbol.ToString();
            }
            str = str.Substring(0, len) + symbolStr + str.Substring(symbolStrLength + len);
            return str;
        }

    }
}
