function calculationDistance (point1, point2) {
  const lat1 = point1[1]
  const lat2 = point2[1]
  const lng1 = point1[0]
  const lng2 = point2[0]
  const radLat1 = lat1 * Math.PI / 180.0
  const radLat2 = lat2 * Math.PI / 180.0
  const a = radLat1 - radLat2
  const b = (lng1 * Math.PI / 180.0) - (lng2 * Math.PI / 180.0)
  const s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
    return s * 6370996.81
}

function distToSegment (start, end, center) {
  const a = Math.abs(calculationDistance(start, end))
  const b = Math.abs(calculationDistance(start, center))
  const c = Math.abs(calculationDistance(end, center))
  const p = (a + b + c) / 2.0
  const s = Math.sqrt(Math.abs(p * (p - a) * (p - b) * (p - c)))
    return s * 2.0 / a
}

function compressLine (coordinate, result, start, end, dMax) {
    if (start < end) {
      let maxDist = 0
      let currentIndex = 0
      const startPoint = coordinate[start]
      const endPoint = coordinate[end]
        for (let i = start + 1; i < end; i++) {
          const currentDist = distToSegment(startPoint, endPoint, coordinate[i])
            if (currentDist > maxDist) {
                maxDist = currentDist
                currentIndex = i
            }
        }
        if (maxDist >= dMax) {
            //  将当前点加入到过滤数组中
            result.push(coordinate[currentIndex])
            //  将原来的线段以当前点为中心拆成两段，分别进行递归处理
            compressLine(coordinate, result, start, currentIndex, dMax)
            compressLine(coordinate, result, currentIndex, end, dMax)
        }
    }
    return result
}

// 调用此方法
// 第一个参数为GPS点位数组，格式为[[x:lng,y:lat,dateKey:xxx],[x:lng,y:lat,dateKey:xxx],[x:lng,y:lat,dateKey:xxx]...]
// 第二个参数为误差，大于多少m的误差就保留
// 第三个参数为时间的key
export function douglasPeuckerForAMap (originalArr, dMax, dateKey) {
    const coordinate = []

    for (let index = 0; index < originalArr.length; index++) {
        const element = originalArr[index]
        const x = Number(element.x)
        const y = Number(element.y)
        const tempArr = [x, y]
        coordinate.push(tempArr)
    }

    if (!coordinate || !(coordinate.length > 2)) {
        return null
    }
    coordinate.forEach((item, index) => {
        item.key = index
    })

    const result = compressLine(coordinate, [], 0, coordinate.length - 1, dMax)

    result.push(coordinate[0])
    result.push(coordinate[coordinate.length - 1])
    const resultLatLng = result.sort((a, b) => {
        if (a.key < b.key) {
            return -1
        } else if (a.key > b.key) {
          return 1
        }
        return 0
    })

    resultLatLng.forEach((item) => {
        const originalDate = originalArr[item.key][dateKey]
        item.push(originalDate)
    })

    return resultLatLng
}
