package com.kingdee.eas.custom.integration.dingtalk.service.detection;

import com.kingdee.eas.custom.integration.base.bizEnum.DeviceType;
import com.kingdee.eas.custom.integration.base.service.detection.PlatformDetector;
import org.springframework.stereotype.Component;

/**
 * 钉钉客户端检测器，区分移动端和桌面端。
 *
 * <p>移动端 UA 特征：DingTalk 且含 Mobile / Android / iPhone / iPad / iOS</p>
 * <p>桌面端 UA 特征：DingTalk 且不含上述移动端关键词</p>
 */
@Component
public class DingtalkPlatformDetector implements PlatformDetector {

    private static final String UA_DINGTALK = "DingTalk";

    private static final String[] UA_MOBILE_KEYWORDS = {
            "Mobile", "Android", "iPhone", "iPad", "iOS"
    };

    @Override
    public String detect(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) return null;
        if (!userAgent.contains(UA_DINGTALK)) return null;

        DeviceType device = detectDevice(userAgent);
        return device != null ? platform() + "_" + device.name().toLowerCase() : platform();
    }

    @Override
    public String platform() {
        return "dingtalk";
    }

    @Override
    public DeviceType detectDevice(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) return null;
        if (!userAgent.contains(UA_DINGTALK)) return null;

        for (String keyword : UA_MOBILE_KEYWORDS) {
            if (userAgent.contains(keyword)) {
                return DeviceType.MOBILE;
            }
        }
        return DeviceType.DESKTOP;
    }
}
