package com.casic.detector.extensions

import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.casic.detector.model.CalculateResult
import kotlin.math.acos

/**
 * 计算两个经纬度之间连线的方位角，因为距离很近（一般是3米内），球面近似为平面
 * C        B
 * |-------/
 * |      /
 * |     /
 * |    /
 * |   /
 * |  /
 * | /
 * |/
 * A
 * */
fun AMapLocation.calculateAngle(target: LatLng): CalculateResult {
    //构造直角辅助点
    val auxiliaryPoint = LatLng(target.latitude, this.longitude)

    //AB线段长度
    val distance = AMapUtils.calculateLineDistance(
        LatLng(this.latitude, this.longitude), target
    )

    //AC线段长度
    val auxiliaryDistance = AMapUtils.calculateLineDistance(
        LatLng(auxiliaryPoint.latitude, auxiliaryPoint.longitude), target
    )

    //求余弦值
    val cosine = auxiliaryDistance / distance

    //反余弦得弧度
    val radian = acos(cosine)

    //弧度转角度，度=弧度×180°/π
    val angle = (radian * 180) / Math.PI

    //判断方位
    val direction = if (target.latitude > this.latitude && target.longitude > this.longitude) {
        //东北方
        "东偏北"
    } else if (target.latitude < this.latitude && target.longitude < this.longitude) {
        //西南方
        "西偏南"
    } else if (target.latitude > this.latitude && target.longitude < this.longitude) {
        //西北方
        "西偏北"
    } else {
        "东偏南"
    }
    return CalculateResult(angle.toInt(), direction, distance.toInt())
}