import FaceUtils from "@/utils/FaceUtils";

const ChatUtils = {
    ErrorType: {
        TIMEOUT_ERROR: 9, //超时
        TOKEN_ERROR: 401, //token 失效错误
        PARAM_ERROR: 400, //参数错误
        FLUSH_TOKEN_ERROR: 7, //刷新token错误
        SERVER_ERROR: 500, //服务器错误
        NET_ERROR: "TypeError: Failed to fetch", //网络链接不通
    },
    // 生成uuid
    uuid: (): string => {
        return `${new Date().getTime()}`;
    },

    /**
     * 消息内容转换
     * @param content 要转换的内容
     */
    transform: (content: string) => {
        // 支持的html标签
        const fa = FaceUtils.faces()
        if (content) {
            content = content.replace(/face\[([^\s\\[\]]+?)]/g, function (face: string) {
                // 转义表情
                const alt = face.replace(/^face/g, '')
                return `<img data-face="true" alt="${alt}" src="${fa.get(alt)}">`
            })
        }
        return content
    },
    /**
     * 消息内容转换
     * @param content 要转换的内容
     */
    transformXss: (content: string,message:Data) => {
		if(!message.extend?.url){
			return content
		}

        // 支持的html标签
        const html = (end?: string) => {
            return new RegExp(
                '\\n*\\[' +
                (end || '') +
                '(code|pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)]\\n*',
                'g'
            )
        }
        const fa = FaceUtils.faces()
        if (content) {
            content = content
                .replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/'/g, '&#39;')
                .replace(/"/g, '&quot;') // XSS
                .replace(/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))/gi, (match) => `<a href="${match}"  target="_blank">${match}</a>`)

                .replace(/face\[([^\s\\[\]]+?)]/g, function (face: string) {
                    // 转义表情
                    const alt = face.replace(/^face/g, '')
                    return (
                        '<img alt="' + fa.get(alt) + '" title="' + fa.get(alt) + '" src="' + fa.get(alt) + '">'
                    )
                })
                .replace(html(), '<$1 $2>')
                .replace(html('/'), '</$1>') // 转移HTML代码
                .replace(/\n/g, '<br>') // 转义换行
				.replace(/@/g,function (content: string) {
				  return (
				    `<img src="${message.extend?.url}" style='vertical-align: middle;width:100px;height:60px;'>`
				  )
				})
        }
        return content
    }


};
export default ChatUtils;
