package com.kingdee.eas.custom.integration.weaver.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;

/**
 * 泛微 E10 客户端检测器。
 * PC 浏览器 UA 常识别不到；深链请走 /auth/weaver/app 或 /auth/weaver?state=。
 */
@Component
public class WeaverPlatformDetector implements PlatformDetector {

    private static final String[] UA_PLATFORM_KEYWORDS = {
            "E-Mobile", "emobile", "CloudHub", "Weaver", "weaver", "eteams"
    };

    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 (!isWeaverClient(userAgent)) {
            return null;
        }
        DeviceType device = detectDevice(userAgent);
        return device != null ? platform() + "_" + device.name().toLowerCase() : platform();
    }

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

    @Override
    public DeviceType detectDevice(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty() || !isWeaverClient(userAgent)) {
            return null;
        }
        for (String keyword : UA_MOBILE_KEYWORDS) {
            if (userAgent.contains(keyword)) {
                return DeviceType.MOBILE;
            }
        }
        return DeviceType.DESKTOP;
    }

    private boolean isWeaverClient(String userAgent) {
        for (String keyword : UA_PLATFORM_KEYWORDS) {
            if (userAgent.contains(keyword)) {
                return true;
            }
        }
        return false;
    }
}
