import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionWorld;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;

import java.util.HashMap;
import java.util.Map;

public class EnhancedShootingSystem {
    private Transform playerCamera; // 玩家的相机
    private float lockOnRange = 30f; // 锁头范围
    private float lockOnStrength = 0.5f; // 锁头强度
    private float maxAimAssistAngle = 30f; // 辅助瞄准的最大角度
    private float spreadIncrement = 2f; // 每次射击增加的扩散值
    private float maxSpread = 10f; // 扩散上限
    private float spreadDecay = 5f; // 扩散恢复速度
    private float defaultFOV = 60f; // 默认视野范围（平板视野）
    private float aimFOV = 50f; // 瞄准时的视野范围（小身位视野）
    private float aimTransitionSpeed = 10f; // 瞄准视野切换速度
    private int targetLayer = 1 << 9; // 目标所在的Layer

    private Transform currentTarget; // 当前辅助瞄准目标
    private float spread = 0f; // 当前扩散值
    private boolean isAiming = false; // 是否正在瞄准
    private float currentFOV; // 当前视野
    private Camera camera; // LibGDX的相机

    public EnhancedShootingSystem(Transform playerCamera, Camera camera) {
        this.playerCamera = playerCamera;
        this.camera = camera;
        currentFOV = defaultFOV;
        camera.fieldOfView = currentFOV;
        loadConfig("Anim.ini");
    }

    private void loadConfig(String filePath) {
        JsonReader reader = new JsonReader();
        try {
            JsonValue config = reader.parse(Gdx.files.internal(filePath));
            JsonValue section = config.get("ShootingSystem");
            lockOnRange = Float.parseFloat(section.get("LockOnRange").asString());
            lockOnStrength = Float.parseFloat(section.get("LockOnStrength").asString());
            maxAimAssistAngle = Float.parseFloat(section.get("MaxAimAssistAngle").asString());
            spreadIncrement = Float.parseFloat(section.get("SpreadIncrement").asString());
            maxSpread = Float.parseFloat(section.get("MaxSpread").asString());
            spreadDecay = Float.parseFloat(section.get("SpreadDecay").asString());
            defaultFOV = Float.parseFloat(section.get("DefaultFOV").asString());
            aimFOV = Float.parseFloat(section.get("AimFOV").asString());
            aimTransitionSpeed = Float.parseFloat(section.get("AimTransitionSpeed").asString());
            targetLayer = 1 << Integer.parseInt(section.get("TargetLayer").asString());
        } catch (Exception e) {
            Gdx.app.error("EnhancedShootingSystem", "Failed to load config file: " + filePath);
        }
    }

    public void update(float deltaTime) {
        detectTarget();
        aimAtTarget();
        decaySpread(deltaTime);
        adjustFOV(deltaTime);
    }

    private void detectTarget() {
        // 假设使用LibGDX的射线检测
        Vector3 origin = playerCamera.position;
        Vector3 direction = playerCamera.forward;
        btCollisionObject hitObject = PhysicsUtils.raycast(origin, direction, lockOnRange, targetLayer);

        if (hitObject != null) {
            float angle = Vector3.angle(playerCamera.forward, hitObject.position.cpy().sub(playerCamera.position));
            if (angle <= maxAimAssistAngle) {
                currentTarget = hitObject.transform;
            }
        } else {
            currentTarget = null;
        }
    }

    private void aimAtTarget() {
        if (currentTarget != null) {
            Vector3 direction = currentTarget.position.cpy().sub(playerCamera.position);
            Quaternion targetRotation = new Quaternion().setFromAxes(direction);
            playerCamera.rotation = Quaternion.slerp(playerCamera.rotation, targetRotation, lockOnStrength * Gdx.graphics.getDeltaTime());
        }
    }

    private void decaySpread(float deltaTime) {
        spread = Math.max(spread - spreadDecay * deltaTime, 0f);
    }

    public void shoot() {
        if (currentTarget != null) {
            spread += spreadIncrement;
            spread = Math.min(spread, maxSpread);

            // 模拟子弹扩散
            Vector3 spreadDirection = Vector3.random().nor().scl(spread);
            btCollisionObject hitObject = PhysicsUtils.raycast(playerCamera.position, playerCamera.forward.cpy().add(spreadDirection), lockOnRange);

            if (hitObject != null) {
                Gdx.app.log("EnhancedShootingSystem", "Hit target with spread: " + spread);
            } else {
                Gdx.app.log("EnhancedShootingSystem", "Missed target with spread: " + spread);
            }
        }
    }

    private void adjustFOV(float deltaTime) {
        if (isAiming) {
            currentFOV = MathUtils.lerp(currentFOV, aimFOV, aimTransitionSpeed * deltaTime);
        } else {
            currentFOV = MathUtils.lerp(currentFOV, defaultFOV, aimTransitionSpeed * deltaTime);
        }
        camera.fieldOfView = currentFOV;
    }

    public void toggleAim() {
        isAiming = !isAiming;
    }
}