// 高德地图key
export const GAODE_MAP_KEY = import.meta.env.VITE_AMAP_KEY

// 获取地图实例
export function getMapContext(mapid: string, instance: any) {
  return uni.createMapContext(mapid, {
    this: instance.proxy,
  })
}

// 获取当前定位
export function getLoalcation({
  mapContext,
  success = null,
  fail = null,
  moveCenter = false,
}) {
  uni.getLocation({
    type: 'gcj02',
    geocode: true,
    success(res) {
      console.log('定位成功', res)
      const { latitude, longitude } = res
      if (moveCenter && mapContext) {
        moveToLocation(mapContext, longitude, latitude)
      }
      success && success({ latitude, longitude })
    },
    fail(err) {
      console.error('uni.getLocation-------', err)
      fail && fail(err)
    },
  })
}

// 移至中心点
export function moveToLocation(mapContext: any, longitude: number, latitude: number) {
  const point = {
    latitude,
    longitude,
  }
  mapContext.moveToLocation(point)
}

/**
 * 添加线
 * @param sColor 线颜色
 * @param arrPoint 线坐标
 * @param width 线宽度
 * @param arrowLine 是否有箭头
 */
export function addLine({
  sColor,
  arrPoint,
  width = 4,
  arrowLine = false,
}: {
  sColor: string
  arrPoint: any[]
  width?: number
  arrowLine?: boolean
}) {
  return {
    points: arrPoint,
    color: sColor,
    width,
    arrowLine,
  }
}

/**
 * 获取路径规划
 * @param mapsdk 高德地图sdk实例
 * @param slng 起点经度
 * @param slat 起点纬度
 * @param elng 终点经度
 * @param elat 终点纬度
 * @param success 成功回调
 * @param fail 失败回调
 */
export function getRoutePlan({
  mapsdk,
  slng,
  slat,
  elng,
  elat,
  success,
  fail,
}: {
  mapsdk: any
  slng: number
  slat: number
  elng: number
  elat: number
  success: (res: any) => void
  fail: (err: any) => void
}) {
  // 检测 mapsdk 实例是否存在
  if (!mapsdk) {
    fail && fail('mapsdk实例不存在')
    console.error('mapsdk实例不存在')
    return
  }
  // 判断经纬度是否齐全
  if (!slng || !slat || !elng || !elat) {
    fail && fail('经纬度参数不完整')
    console.error('经纬度参数不完整')
    return
  }

  const options = {
    origin: `${slng},${slat}`,
    destination: `${elng},${elat}`,
    success: (res: any) => {
      const points = []
      let distance = 0
      if (res?.paths[0]?.steps) {
        const steps = res.paths[0].steps
        distance = res.paths[0].distance

        for (let i = 0; i < steps.length; i++) {
          const poLen = steps[i].polyline.split(';')
          for (let j = 0; j < poLen.length; j++) {
            points.push({
              longitude: Number.parseFloat(poLen[j].split(',')[0]),
              latitude: Number.parseFloat(poLen[j].split(',')[1]),
            })
          }
        }
      }

      const cnt = (distance / 1000).toFixed(2)
      let sdistance = `${distance}m`

      if (Number.parseFloat(cnt) >= 1) {
        sdistance = `${cnt} km`
      }
      const data = {
        arrPoint: points,
        distance: sdistance,
      }
      if (success)
        success(data)
    },
    fail: (error: any) => {
      fail && fail(error)
    },
  }

  mapsdk.getDrivingRoute(options)
}

/**
 * 逆解析地址
 * @param {object} options
 * @param {object} options.mapsdk - 地图对象
 * @param {number} options.longitude - 经度
 * @param {number} options.latitude - 纬度
 * @param {Function} options.success - 成功回调
 * @param {Function} options.fail - 失败回调
 */

export function reverseGeocoder({
  mapsdk,
  longitude,
  latitude,
  success,
  fail,
}: {
  mapsdk: any
  longitude: number
  latitude: number
  success: (data: any) => void
  fail: (error: any) => void
}) {
  if (!mapsdk) {
    console.error('请传入地图sdk')
    fail && fail('请传入地图sdk')
    return
  }

  if (!longitude || !latitude) {
    console.error('请传入经纬度')
    fail && fail('请传入经纬度')
    return
  }
  mapsdk.getRegeo({
    location: `${longitude},${latitude}`,
    success(res: any) {
      console.log(res)
      const { desc, regeocodeData, latitude, longitude } = res[0]
      success && success({
        desc,
        regeocodeData,
        latitude,
        longitude,
      })
    },
    fail(err: any) {
      console.log(err, '地理位置信息失败')
      fail && fail(err)
    },
  })
}

/**
 *绘制区域
 * @param {object} options
 * @param {Array} options.point - 区域点
 * @param {boolean} options.isFormat - 是否格式化(处理经纬度)
 * @param {Function} options.success - 成功回调函数
 * @param {Function} options.fail - 失败回调函数
 * @param {any} options.option - 配置
 */
export function drawRegion({
  point,
  isFormat = false,
  success,
  fail,
  option = {
    strokeWidth: 2,
    strokeColor: '#4595f8',
    fillColor: '#b7dff299',
    level: 'abovelabels', // abovelabels 显示在所有 POI 之上 abovebuildings 显示在楼块之上 POI 之下
  },
}: {
  point: any
  isFormat?: boolean
  option?: any
  success: (data?: any) => void
  fail: (err?: any) => void
}) {
  let obj = {
    point: [],
  }

  if (!point) {
    fail && fail('point参数不能为空')
    return
  }

  // 格式化数据(判断数据是不是二维数组)
  if (isFormat) {
    if (Array.isArray(point) && point.length > 0 && point.every(item => Array.isArray(item))) {
      const points = point.map((item: any) => ({
        latitude: item[1],
        longitude: item[0],
      }))
      obj = {
        points,
        ...option,
      }
    }
  }
  else {
    obj = {
      points: point,
      ...option,
    }
  }

  success && success(obj)
}

/**
 *绘制点位
 * @param {object} param
 * @param {Array} param.point
 * @param {object} param.option
 * @param {boolean} param.isSoc
 * @param {Function} param.success
 * @param {Function} param.fail
 *
 */
//  iconPath: '/static/images/carImage.png',
//  iconPath: '/static/images/markerH.png',
export function drawPoint({
  point,
  type = 'none',
  option = {
    width: 35,
    height: 35,
    iconPath: '/static/images/carImage.png',
  },
  success,
  fail,
}: {
  type?: 'none' | 'charge' // 工具的类型
  point: {
    bikeCode: string
    latitude: number
    longitude: number
    soc?: number
    online?: boolean
  }
  option?: any
  success: (res: any) => void
  fail: (res: any) => void
}) {
  // console.log(point, '------------>point')
  let obj = {}

  if (!point) {
    fail && fail('point参数不能为空')
    return
  }

  switch (type) {
    case 'charge': {
      obj = setChargePoint(point, option)
      break
    }
  }
  success && success(obj)
}

// 换电点位设置
function setChargePoint(point: any, option: any) {
  const { soc, online } = point
  const obj = {
    id: Number(point.bikeCode),
    latitude: point.latitude,
    longitude: point.longitude,
    width: 40,
    height: 40,
    label: {
      anchorY: -32,
      anchorX: -11,
      fontSize: 10,
      color: '#0dc31b',
    },
  }

  if (!online) {
    return {
      ...obj,
      iconPath: '/static/images/markerL.png',
      label: {
        ...obj.label,
        content: '离线',
        color: '#d81e06',
      },
    }
  }
  if (soc >= 0 && soc < 20) {
    return {
      ...obj,
      iconPath: '/static/images/markerL.png',
      label: {
        ...obj.label,
        content: `${point.soc}%`,
        color: '#d81e06',
      },
    }
  }
  if (soc >= 20 && soc < 70) {
    return {
      ...obj,
      iconPath: '/static/images/markerM.png',
      label: {
        ...obj.label,
        content: `${point.soc}%`,
        color: '#e16530',
      },
    }
  }
  if (soc >= 70 && soc <= 100) {
    return {
      ...obj,
      iconPath: '/static/images/markerH.png',
      label: {
        ...obj.label,
        content: `${point.soc}%`,
        color: '#0dc31a',
      },
    }
  }
}
