<script lang="ts" setup>
import { getAllOperatorRegionAPI, getCurrentLocationRegionAPI, getEbikeDetailForWorkAPI, getEbikeListForWorkAPI } from '@/api/operator'
import AMapWX from '@/plugIns/amap-wx.130.js'
import { addLine, drawPoint, drawRegion, getLoalcation, getMapContext, getRoutePlan } from '@/utils/map'
import { systemInfo } from '@/utils/systemInfo'
import carDetailsTools from './components/carDetailsTools.vue'
import changeTools from './components/changeTools.vue'
import dispatchTools from './components/dispatchTools.vue'

const { VITE_AMAP_KEY } = import.meta.env
const amapsdk = new AMapWX({
  key: VITE_AMAP_KEY,
})
const navBarHeight = systemInfo.statusBarHeight * 2 + 80 || 200// 导航栏高度
const height = (systemInfo.screenHeight - navBarHeight)

type ToolsType = 'dispatch' | 'charge' | 'none' | 'polling' | 'maintain'

definePage({
  style: {
    navigationStyle: 'custom',
  },
})

const tablist = ref<any>([
  {
    name: '换电',
    key: 'charge',
  },
  {
    name: '调度',
    key: 'dispatch',
  },
  {
    name: '巡检',
    key: 'polling',
  },
  {
    name: '维修',
    key: 'maintain',
  },
])
const bikeList = ref<any>([]) // 车辆列表
const toolsType = ref<ToolsType>(tablist.value[0].key)// 工具类型
const carDetaile = ref<any>({ // 获取车辆详情
  distance: '',
})
const carDetailsShow = reactive<any>({ // 车辆详情卡片配置
  show: false,
  key: tablist.value[0].key, // 记录工具类型
})

const changeToolsRef = ref(null) // 换电工具栏

/**
 * 弹窗配置
 */
const popupRef = ref<any>(null) // 弹窗
const regionList = ref<any>([]) // 区域列表
const selectRegion = ref<any>({}) // 选中的区域
const selectRegionMiddle = ref<any>({}) // 选中的区域中间点

/**
 * 地图引用
 */
const mapContext = ref<any>(null)
const mapRef = ref<any>()
const mapConfig = reactive({
  scale: 11,
  latitude: undefined,
  longitude: undefined,
})
const visionCenter = reactive({
  latitude: 0,
  longitude: 0,
})
const mapMarkers = ref([]) // 地图点
const mapPolygons = ref([]) // 地图多边形区域
const mapPolylines = ref([]) // 地图线

// 点击tab
function tabClick(item: any) {
  toolsType.value = item.key
  carDetailsShow.show = false
  mapPolylines.value = []
  drawMapPoint(toolsType.value)
}
// 定位
async function orientation() {
  if (!mapContext.value) {
    return console.error('地图未初始化')
  }
  return new Promise((resolve, reject) => {
    getLoalcation(
      {
        mapContext: mapContext.value,
        moveCenter: true,
        success: (res: any) => {
          const { latitude, longitude } = res
          mapConfig.latitude = latitude
          mapConfig.longitude = longitude
          resolve(mapConfig)
        // console.log('地图配置', mapConfig)
        },
      },
    )
  })
}

function mapUpdated() {

}
//  地图移动事件
function regionchange(e: any) {
  // console.log('regionchange', e)
  const { centerLocation, type } = e.detail
  if (type !== 'end') {
    return
  }
//   TUDO: 更新视野中心点(有缺陷)
//   visionCenter.latitude = centerLocation.latitude
//   visionCenter.longitude = centerLocation.longitude
}

// 获取车辆列表
async function getEbikeList(regionId: string) {
  try {
    const res: any = await getEbikeListForWorkAPI(regionId)
    if (Array.isArray(res) && res.length > 0) {
      bikeList.value = res
    }
    getBikeCount(res)
    return Promise.resolve(res)
  }
  catch (e) {
    uni.showToast({
      title: '获取车辆列表失败',
      icon: 'none',
    })
    console.error('获取车辆列表失败')
  }
}

// 绘制点位信息
function drawMapPoint(orderType: any) {
  if (!bikeList.value || bikeList.value.length === 0) {
    return
  }
  mapMarkers.value = []
  let list = []

  // 换电
  if (orderType === tablist.value[0].key) {
    list = bikeList.value.filter((item: any) => item.hasChangeBatteryOrder)
  }
  // 调度
  if (orderType === tablist.value[1].key) {
    list = bikeList.value.filter((item: any) => item.hasDispatchOrder)
  }
  // 巡检
  if (orderType === tablist.value[2].key) {
    list = bikeList.value.filter((item: any) => item.hasInspectionOrder)
  }
  // 维修
  if (orderType === tablist.value[3].key) {
    list = bikeList.value.filter((item: any) => item.hasRepairOrder)
  }

  // 绘制点位
  if (list.length > 0) {
    list.forEach((bike: any) => {
      drawPoint({
        type: orderType,
        point: {
          bikeCode: bike.bikeCode,
          longitude: bike.location.longitude,
          soc: bike.soc,
          latitude: bike.location.latitude,
          online: bike.online,
        },
        success(res) {
          mapMarkers.value.push(res)
        },
        fail(res) {
          console.error(res)
        },
      })
    })
  }
}

// 根据不同类型获取车的相应数量
function getBikeCount(carList: any[]) {
  switch (toolsType.value) {
    case 'charge': {
      const list = carList.filter((item: any) => item.hasChangeBatteryOrder)
      changeToolsRef.value?.setCarNum(list)
      break
    }
  }
}

// 地图初始化
async function initMap() {
  if (!mapContext.value) {
    mapContext.value = getMapContext('mapRef', getCurrentInstance())
  }
  // 定位
  await orientation()
  // 获取所有运营区域
  // await getAllOperatorList()
  // 获取定位就近的运营区域
  await getNearbyOperatorRegion()
  // 设置运营区域
  drawMapPolygons(regionList.value[0].regionId)
  setSelectedRegion(regionList.value[0].regionId)
  // 根据运营区域获取车辆列表
  await getEbikeList(regionList.value[0].regionId)
  drawMapPoint(toolsType.value)
}

// 监听点击marker事件
async function handleMarkertap(e: any) {
  const id = e.markerId

  // 从列表中查找对应车辆信息
  const item = mapMarkers.value.find(item => item.id === id)
  try {
    const res: any = await getEbikeDetailForWorkAPI(item.id.toString())
    if (res) {
      carDetaile.value = res
    }

    carDetailsShow.key = toolsType.value
    toolsType.value = 'none'
    carDetailsShow.show = true

    // 规划车辆地理位置信息
    getLoalcation({
      mapContext: mapContext.value,
      success(myRes: any) {
        const { longitude, latitude } = myRes
        getRoutePlan({
          mapsdk: amapsdk,
          slng: longitude,
          slat: latitude,
          elng: item.longitude,
          elat: item.latitude,
          success(routeRes: any) {
            const { arrPoint, distance } = routeRes
            carDetaile.value = {
              ...carDetaile.value,
              bikeCode: item.id.toString(),
              distance,
            }
            if (mapContext.value) {
              mapContext.value.includePoints({
                points: arrPoint,
                padding: [100, 100, 100, 100], // 视野边缘与点的间距
                success: () => {
                  mapPolylines.value = [
                    addLine({
                      sColor: '#1082FF',
                      arrPoint,
                      width: 10,
                      arrowLine: true,
                    }),
                  ]
                },
              })
            }
          },
          fail(err: any) {
            console.log(err)
          },

        })
      },
    })
  }
  catch (e) {
    console.log(e)
  }
}

function onZoom(lx: 'in' | 'out') {
  mapConfig.latitude = visionCenter.latitude
  mapConfig.longitude = visionCenter.longitude
  switch (lx) {
    case 'out':
      mapConfig.scale += 1
      break
    case 'in':
      mapConfig.scale -= 1
      break
  }
}

// 获取所有运营列表 (暂时没用)
async function getAllOperatorList() {
  try {
    const list = await getAllOperatorRegionAPI()
    if (Array.isArray(list) && list.length > 0) {
      regionList.value = list
    }
    return Promise.resolve(list)
  }
  catch (e) {
    console.error(e)
  }
}

// 获取附近运营
async function getNearbyOperatorRegion() {
  try {
    const list = await getCurrentLocationRegionAPI({
      type: 'point',
      coordinates: [mapConfig.longitude, mapConfig.latitude],
    })
    if (Array.isArray(list) && list.length > 0) {
      regionList.value = list
    }
    return Promise.resolve(list)
  }
  catch (e) {
    console.error(e)
  }
}

// 设置所选区域
function setSelectedRegion(regionId: string) {
  const region = regionList.value.find((item: any) => item.regionId === regionId)
  if (region) {
    selectRegion.value = region
  }
}

/**
 *地图绘制相关方法
 */

function drawMapPolygons(regionId: string) {
  if (!regionId) {
    return
  }
  const region = regionList.value.find((item: any) => item.regionId === regionId)
  if (region) {
    const { coordinates } = region.regionPolygon
    drawRegion({
      point: coordinates,
      isFormat: true,
      success(res) {
        mapPolygons.value = [res]
      },
      fail(err) {
        console.error(err)
      },
    })
  }
}

/**
 *不同类型工单处理
 */
function changeDispatch(item: any) {
  console.log(item, '不同类型工单处理')
}
function carDetailsClose() {
  carDetailsShow.show = false
  toolsType.value = carDetailsShow.key
  mapPolylines.value = []
}
// 换电工具变化处理
function chargeChange(res: any) {
  const { type, value } = res
  const list = bikeList.value.filter((item: any) => item.hasChangeBatteryOrder)

  if (list.length <= 0) {
    return
  }

  mapMarkers.value = []
  if (type === 'tab') {
    console.log(value, list)
    switch (value) {
      case '低电量':{
        list.forEach((item: any) => {
          if (item.soc >= 0 && item.soc < 20) {
            drawPoint({
              type: tablist.value[0].key,
              point: {
                bikeCode: item.bikeCode,
                longitude: item.location.longitude,
                latitude: item.location.latitude,
                soc: item.soc,
                online: item.online,
              },
              success(res) {
                mapMarkers.value.push(res)
              },
              fail(res) {
                console.error(res)
              },
            })
          }
        })
        break
      }
      case '中电量':{
        list.forEach((item: any) => {
          if (item.soc >= 20 && item.soc < 70) {
            drawPoint({
              type: tablist.value[0].key,
              point: {
                bikeCode: item.bikeCode,
                longitude: item.location.longitude,
                latitude: item.location.latitude,
                soc: item.soc,
                online: item.online,
              },
              success(res) {
                mapMarkers.value.push(res)
              },
              fail(res) {
                console.error(res)
              },
            })
          }
        })
        break
      }
      case '高电量':{
        list.forEach((item: any) => {
          if (item.soc >= 70 && item.soc <= 100) {
            drawPoint({
              type: tablist.value[0].key,
              point: {
                bikeCode: item.bikeCode,
                longitude: item.location.longitude,
                latitude: item.location.latitude,
                soc: item.soc,
                online: item.online,
              },
              success(res) {
                mapMarkers.value.push(res)
              },
              fail(res) {
                console.error(res)
              },
            })
          }
        })
        break
      }
      case '离线':{
        list.forEach((item: any) => {
          if (!item.online) {
            drawPoint({
              type: tablist.value[0].key,
              point: {
                bikeCode: item.bikeCode,
                longitude: item.location.longitude,
                latitude: item.location.latitude,
                soc: item.soc,
                online: item.online,
              },
              success(res) {
                mapMarkers.value.push(res)
              },
              fail(res) {
                console.error(res)
              },
            })
          }
        })
        break
      }
      default: {
        list.forEach((item: any) => {
          drawPoint({
            type: tablist.value[0].key,
            point: {
              bikeCode: item.bikeCode,
              longitude: item.location.longitude,
              latitude: item.location.latitude,
              soc: item.soc,
              online: item.online,
            },
            success(res) {
              mapMarkers.value.push(res)
            },
            fail(res) {
              console.error(res)
            },
          })
        })
      }
    }

    return
  }

  if (type === 'slide') {
    list.forEach((item: any) => {
      if (item.soc >= value[0] && item.soc < value[1]) {
        drawPoint({
          type: tablist.value[0].key,
          point: {
            bikeCode: item.bikeCode,
            longitude: item.location.longitude,
            latitude: item.location.latitude,
            soc: item.soc,
            online: item.online,
          },
          success(res) {
            mapMarkers.value.push(res)
          },
          fail(res) {
            console.error(res)
          },
        })
      }
    })
  }
}

/**
 *弹窗
 */
function openRegion() {
  popupRef.value.open('right')
  selectRegionMiddle.value = selectRegion.value
}

function backRegion() {
  popupRef.value.close()
}

// 确定
async function handleRegion() {
  await getEbikeList(selectRegionMiddle.value.regionId)
  setSelectedRegion(selectRegionMiddle.value.regionId)
  drawMapPolygons(selectRegionMiddle.value.regionId)
  drawMapPoint(toolsType.value)
  backRegion()
}
function handleRegionClick(item: any) {
  selectRegionMiddle.value = item
}

onMounted(() => {
  initMap()
})
</script>

<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="nav" :style="{ height: `${navBarHeight}rpx` }">
      <view class="tabs">
        <uv-tabs
          line-color="#ffffff"
          :list="tablist" :active-style="{
            color: '#ffffff',
            fontWeight: 'bold',
            transform: 'scale(1.05)',
          }"
          :inactive-style="{
            color: '#cccccc',
            transform: 'scale(1)',
          }"
          @click="tabClick"
        />
      </view>
    </view>

    <!-- 地图 -->
    <view class="map-container" :style="{ height: `${height}px` }">
      <map
        id="mapRef"
        ref="mapRef"
        :style="{ width: '100%', height: `100%` }"
        :show-location="true"
        :scale="mapConfig.scale"
        :markers="mapMarkers"
        :latitude="mapConfig.latitude"
        :longitude="mapConfig.longitude"
        :polygons="mapPolygons"
        :polyline="mapPolylines"
        @regionchange="regionchange"
        @updated="mapUpdated"
        @markertap="handleMarkertap"
        @labeltap="handleMarkertap"
      />
    </view>

    <!-- 切区 -->
    <view class="region-container" @click="openRegion">
      <uv-icon
        name="qiehuan"
        custom-prefix="custom-icon"
        size="16"
        color="#514f50"
      />
      <text class="title">切区</text>
    </view>

    <!-- 左侧工具栏 -->
    <view class="left-toolbar" catchtouchmove="true">
      <!-- <uv-button
        icon="plus" class="m-b_10"
        :custom-style="{
          width: '70rpx',
          height: '70rpx',
        }"
        @click="onZoom('out')"
      />
      <uv-button
        icon="minus"
        class="m-b_10"
        :custom-style="{
          width: '70rpx',
          height: '70rpx',
        }"
        @click="onZoom('in')"
      /> -->
      <uv-button
        :custom-style="{
          width: '70rpx',
          height: '70rpx',
        }"
        @click="orientation"
      >
        <template #suffix>
          <uv-icon
            name="ditu_dingwei"
            custom-prefix="custom-icon"
            size="28"
          />
        </template>
      </uv-button>
    </view>

    <!-- 底部位置 -->
    <view class="bottom-toolbar" catchtouchmove="true">
      <!-- 调度 -->
      <dispatchTools v-show="toolsType === 'dispatch'" @change="changeDispatch" />
      <!-- 换电 -->
      <changeTools v-show="toolsType === 'charge'" ref="changeToolsRef" @change="chargeChange" />
      <!-- 车辆详情 -->
      <carDetailsTools
        v-show="carDetailsShow.show"
        :data="carDetaile"
        @close="carDetailsClose"
      />
    </view>

    <!-- 区域弹框 -->
    <uv-popup ref="popupRef">
      <view class="regionContainer">
        <!-- 导航栏 -->
        <view class="title" :style="{ height: `${navBarHeight - 20}rpx` }">
          <view class="back" @click="backRegion">
            <uv-icon name="arrow-left" color="white" size="22" />
          </view>
          <text>区域选择</text>
        </view>
        <!-- 列表 -->
        <view
          :style="{
            maxHeight: `calc(100vh - ${navBarHeight + 20 + 150}rpx)`,
          }"
          class="regionList"
        >
          <view
            v-for="(item) in regionList"
            :key="item.regionId"
            class="list_item"
            :class="{
              active: item.regionId === selectRegionMiddle.regionId,
            }"
            @click="handleRegionClick(item)"
          >
            {{ item.regionName }}
          </view>
        </view>
        <!-- 按钮栏 -->
        <view class="btn_bar">
          <uv-button type="primary" text="确定" @click="handleRegion" />
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 90vh;
  position: relative;
  overflow: hidden;

  .nav {
    width: 100%;
    background-color: #1488f5;
    position: relative;

    .tabs {
      width: 70%;
      position: absolute;
      bottom: 15rpx;
      left: 0;
    }
  }

  .left-toolbar {
    position: fixed;
    left: 20rpx;
    top: 50%;
    background-color: #bcb9b966;
    z-index: 999;
    padding: 10rpx;
    border-radius: 10rpx;
  }

  .region-container {
    position: fixed;
    left: 20rpx;
    top: 13%;
    background-color: white;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
    padding: 15rpx 35rpx;
    z-index: 999;
    border-radius: 30rpx;
    display: flex;
    align-items: center;

    .title {
      font-size: 26rpx;
      color: #514f50;
      margin-left: 8rpx;
    }
  }

  .bottom-toolbar {
    position: fixed;
    left: 15rpx;
    right: 15rpx;
    bottom: 90px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    z-index: 700;
  }
}
.map-container {
  width: 100%;
  z-index: 1;
}

.regionContainer {
  width: 100vw;
  height: 100%;
  position: relative;

  .title {
    position: relative;
    width: 100%;
    background-color: #1281ff;
    color: white;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding-bottom: 20rpx;

    .back {
      position: absolute;
      left: 30rpx;
      bottom: 20rpx;
    }
  }

  .regionList {
    width: calc(100vw - 60rpx);
    padding: 20rpx 30rpx;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: start;
    gap: 30rpx;

    .list_item {
      font-size: 28rpx;
      height: 50rpx;
      color: #4a4a4a;
      padding: 10rpx 30rpx;
      background-color: #f6f6f6;
      line-height: 50rpx;
      border-radius: 40rpx;
      margin-right: 20rpx;
    }

    .active {
      color: #0187fb !important;
    }
  }

  .btn_bar {
    position: absolute;
    left: 0;
    bottom: 0;
    width: calc(100% - 60rpx);
    padding: 0 30rpx;
    padding-bottom: 45rpx;
  }
}
</style>
