package com.ruoyi.web.modules.diagnosis.support;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.diagnosis.domain.BizConsultSession;
import com.ruoyi.web.modules.diagnosis.domain.VetConsultSendBody;

/**
 * 在线接诊（兽医）参数校验。
 */
public final class VetConsultValidation
{
    private static final String[] IMAGE_EXT = { ".jpg", ".jpeg", ".png", ".gif" };

    private static final String[] VIDEO_EXT = { ".mp4", ".mov" };

    private static final String[] VOICE_EXT = { ".mp3", ".m4a", ".wav" };

    private VetConsultValidation()
    {
    }

    public static void validateListQuery(BizConsultSession query, Boolean searchMode)
    {
        if (Boolean.TRUE.equals(searchMode))
        {
            String askerName = query != null ? StringUtils.trim(query.getAskerNameFilter()) : null;
            String keyword = query != null ? StringUtils.trim(query.getContentKeyword()) : null;
            if (StringUtils.isEmpty(askerName) && StringUtils.isEmpty(keyword))
            {
                throw new ServiceException("请输入筛选条件");
            }
        }
    }

    public static void validateSendBody(VetConsultSendBody body)
    {
        if (body == null || body.getMsgType() == null)
        {
            throw new ServiceException("请输入消息内容");
        }
        if (!ConsultSessionRules.isValidMsgType(body.getMsgType()))
        {
            throw new ServiceException("消息类型无效");
        }
        String content = StringUtils.trim(body.getContent());
        if (body.getMsgType() == ConsultSessionRules.MSG_TYPE_TEXT)
        {
            if (StringUtils.isEmpty(content))
            {
                throw new ServiceException("请输入消息内容");
            }
            return;
        }
        if (StringUtils.isEmpty(content))
        {
            throw new ServiceException("请上传文件");
        }
        validateMediaUrl(body.getMsgType(), content);
    }

    public static void validateMediaUrl(int msgType, String url)
    {
        String lower = url.toLowerCase();
        int q = lower.indexOf('?');
        if (q > 0)
        {
            lower = lower.substring(0, q);
        }
        String[] allowed;
        if (msgType == ConsultSessionRules.MSG_TYPE_IMAGE)
        {
            allowed = IMAGE_EXT;
        }
        else if (msgType == ConsultSessionRules.MSG_TYPE_VIDEO)
        {
            allowed = VIDEO_EXT;
        }
        else if (msgType == ConsultSessionRules.MSG_TYPE_VOICE)
        {
            allowed = VOICE_EXT;
        }
        else
        {
            throw new ServiceException("消息类型无效");
        }
        boolean ok = false;
        for (String ext : allowed)
        {
            if (lower.endsWith(ext))
            {
                ok = true;
                break;
            }
        }
        if (!ok)
        {
            throw new ServiceException("文件格式或大小不符合要求");
        }
    }
}
