index.vue 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
<template>
  <div class="chart-amap" ref="vChartRef">
    <device-latest-table ref="deviceLatestTableRef"></device-latest-table>
  </div>
</template>

<script setup lang="ts">
import { ref, PropType, toRefs, watch, render, h, onMounted, onUnmounted, reactive } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { CreateComponentType } from '@/packages/index.d'
import { useChartDataFetch } from '@/hooks'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import {
  MarkerEnum,
  ThemeEnum,
  dataExtraInfoType,
  dataJsonType,
  dataJsonMarkersType,
  devicePartInfoInterface
} from './config'
import { isArray } from '@/utils'
import inactive from './images/inactive.png'
import online from './images/online.png'
import offline from './images/offline.png'
import listView from './images/list.png'
import { getDeviceActiveTime } from '@/api/external/common/index'
import dayjs from 'dayjs'
import DeviceLatestTable from './components/DeviceLatestTable.vue'
import { getDeviceLatest, getProfileAttrs } from '@/api/external/common'
import { isObject } from '@/utils/external/is'

const props = defineProps({
  chartConfig: {
    type: Object as PropType<CreateComponentType>,
    required: true
  }
})

const deviceLatestTableRef = ref<Nullable<InstanceType<typeof DeviceLatestTable>>>(null)

const {
  amapKey,
  amapStyleKey,
  amapLon,
  amapLat,
  amapZindex,
  mapMarkerType,
  lang,
  amapStyleKeyCustom,
  features,
  viewMode,
  pitch,
  skyColor,
  marker,
  mpBorderConfig,
  bgColor
} = toRefs(props.chartConfig.option.mapOptions)

const { dialogCustomField, dialogConfigField } = toRefs(props.chartConfig.option)

//官方没有高德地图api的ts,所以类型全用的any
let mapIns: any = null
let markers: any = []
let AMapIns: any = null
const vChartRef = ref<HTMLElement>()

const initMap = (newData: any) => {
  // 初始化
  AMapLoader.load({
    key: amapKey.value, //api服务key--另外需要在public中使用安全密钥!!!
    version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete'] // 需要使用的的插件列表
  })
    .then(AMap => {
      AMapIns = AMap
      mapIns = new AMap.Map(vChartRef.value, {
        resizeEnable: true,
        zoom: amapZindex.value, // 地图显示的缩放级别
        center: [amapLon.value, amapLat.value],
        lang: lang.value,
        features: features.value,
        pitch: pitch.value, // 地图俯仰角度,有效范围 0 度- 83 度
        skyColor: skyColor.value,
        viewMode: viewMode.value, // 地图模式
        willReadFrequently: true,
        WebGLParams: {
          preserveDrawingBuffer: true
        }
      })
      dataHandle(props.chartConfig.option.dataset) //处理地图标点
      let satellite = new AMap.TileLayer.Satellite()
      let roadNet = new AMap.TileLayer.RoadNet()
      if (newData.amapStyleKey === ThemeEnum.WEIXIN) {
        mapIns.add([satellite, roadNet])
      } else {
        mapIns.remove([satellite, roadNet])
        mapIns.setMapStyle(
          `amap://styles/${amapStyleKeyCustom.value !== '' ? amapStyleKeyCustom.value : amapStyleKey.value}`
        )
      }
      mapIns.on('click', () => {
        mapIns.clearInfoWindow()
      })
    })
    .catch(e => {
      console.error(e)
    })
}

//携带设备的tbDeviceId和别名或者名称
const devicePartInfo = reactive<devicePartInfoInterface>({
  tbDeviceId: '',
  name: '',
  alias: '',
  deviceProfileId: ''
})

//创建信息弹窗
const createInfoWindow = async (extraInfo: dataExtraInfoType) => {
  try {
    const {
      name,
      alias,
      organizationDTO,
      deviceState,
      deviceProfile,
      deviceInfo,
      tbDeviceId,
      deviceProfileId,
      customField
    } = extraInfo
    // customField 用于自定义服务端返回的数据
    let realDialogConfigFieldValue = []
    if ('customField' in extraInfo && isObject(customField)) {
      realDialogConfigFieldValue = dialogConfigField.value?.reduce((acc: Recordable[], curr: Recordable) => {
        const realValue = Object.entries(customField)?.map(([label, value]) => ({
          label,
          value
        }))
        const findRealValue = realValue?.find(realItem => realItem.label === curr.value)?.value
        curr['realValue'] = findRealValue
        acc.push(curr)
        return [...acc]
      }, [])
    }
    //
    devicePartInfo.tbDeviceId = tbDeviceId
    devicePartInfo.alias = alias
    devicePartInfo.name = name
    devicePartInfo.deviceProfileId = deviceProfileId
    let deviceLastUpdateTs = null
    try {
      const res = !dialogCustomField.value ? await getDeviceActiveTime(tbDeviceId) : [{ lastUpdateTs: '' }] //查询设备最后离线时间
      if (!res) {
        deviceLastUpdateTs = null
      } else {
        deviceLastUpdateTs = res[0]['lastUpdateTs']
      }
    } catch (e) {
      console.error(`${e}`, '查询设备最后离线时间(tbDeviceId错误)')
    }
    const lastUpdateFormatTs = deviceLastUpdateTs ? dayjs(deviceLastUpdateTs).format('YYYY-MM-DD HH:mm:ss') : ''
    //以render方式渲染小组件里的边框组件
    const BorderInstance = await import(`../../../../Decorates/Borders/${mpBorderConfig.value.value}/index.vue`)
    const config = await import(`../../../../Decorates/Borders/${mpBorderConfig.value.value}/config.ts`)
    const BorderConfigInstance = new config.default()
    const id = Date.now().toString()
    setTimeout(() => {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      render(h(BorderInstance.default, { chartConfig: BorderConfigInstance }), document.getElementById(id)!)
    }, 100)
    //

    const dialogStyles = {
      textOverflowStyle: `width:15rem;text-overflow:ellipsis;overflow:hidden;word-break:break-all;white-space:nowrap;`,
      customFieldBox: `display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;color:white;`,
      defaultFieldHeaderBox: `display:flex;justify-content:space-between;align-items:center;color:white;`,
      defaultFieldHeaderBoldText: `width:12rem;text-overflow:ellipsis;overflow:hidden;word-break:break-all;white-space:nowrap;font-size:15px;font-weight:bold;`,
      defaultFieldBox: `display:flex;flex-direction:column;justify-content:space-between;color:white;margin-top:1rem;gap:0.95rem;`,
      iconSize: `width:1.2rem;height:1.2rem;`,
      textStatus: `margin-left:0.6rem;font-weight:bold;`,
      defaultFieldHeaderRightBox: `display:flex;justify-content:space-between;align-items:center;margin-right:16px`
    }

    return `
     <div id="${id}" style="position: absolute;top: 70px">
     </div>
    ${
      dialogCustomField.value
        ? `
      <div style="position: absolute;top: 135px;left:110px;width:20rem">
        <div style="${dialogStyles.customFieldBox}">
         ${realDialogConfigFieldValue?.map((item: { label: string; value: string; realValue: any }) => {
           const { label, realValue } = item
           return `
             <div style="${dialogStyles.textOverflowStyle}">
             <span >${label}:${realValue}</span>
             </div>
            `
         })}
        </div>
      </div>
      `
        : `
        <div style="position: absolute;top: 135px;left:110px;width:20rem">
          <div style="${dialogStyles.defaultFieldHeaderBox}">
           <span style="${dialogStyles.defaultFieldHeaderBoldText}">${alias || name}</span>
           <div style="${dialogStyles.defaultFieldHeaderRightBox}">
             <img onclick="handleOpenDrawer()" style="${
               dialogStyles.iconSize
             };cursor:pointer;margin-right:0.5rem" src="${listView}"/>
             <img style="${dialogStyles.iconSize};margin-left:0.5rem" src="${
            deviceState === 'INACTIVE' ? inactive : deviceState === 'ONLINE' ? online : offline
          }"/>
             <span style="${dialogStyles.textStatus}">${
            deviceState === 'INACTIVE' ? '待激活' : deviceState === 'ONLINE' ? '在线' : '离线'
          }</span>
           </div>
          </div>
          <div style="${dialogStyles.defaultFieldBox}">
             <div style="${dialogStyles.textOverflowStyle}">所属组织:${organizationDTO?.name}</div>
             <div style="${dialogStyles.textOverflowStyle}">接入协议:${deviceProfile?.transportType}</div>
             <div style="${dialogStyles.textOverflowStyle}">设备位置:${
            !deviceInfo?.address ? '该设备暂无地理位置' : deviceInfo?.address
          }</div>
          <div style="${dialogStyles.textOverflowStyle}">${
            deviceState === 'ONLINE' ? '在线' : deviceState === 'INACTIVE' ? '创建' : '离线'
          }时间:${lastUpdateFormatTs}</div>
          </div>
          `
    }

    `
  } catch (e) {
    console.error(e)
  }
}

const handleOpenDrawer = async () => {
  deviceLatestTableRef.value?.openDrawer()
  deviceLatestTableRef.value?.setDrawerTitle(devicePartInfo.alias || devicePartInfo.name)
  if (!devicePartInfo.tbDeviceId) return
  const resp = await getDeviceLatest(devicePartInfo.tbDeviceId)
  const respGetAttrs = await getProfileAttrs({ deviceProfileId: devicePartInfo.deviceProfileId })
  deviceLatestTableRef.value?.setValue(resp, respGetAttrs)
}

onMounted(() => {
  ;(window as any).handleOpenDrawer = handleOpenDrawer
})

onUnmounted(() => {
  ;(window as any).handleOpenDrawer = null
})

//地图鼠标hover
const mapClick = (markerInstance: any, markerItem: dataJsonMarkersType) => {
  markerInstance.setExtData({
    extraInfo: markerItem.extraInfo
  })
  // mouseover
  markerInstance.on('click', async (e: any) => {
    const { extraInfo } = e.target.getExtData()
    let infoWindow = new AMapIns.InfoWindow({
      content: await createInfoWindow(extraInfo)
      // offset: new AMapIns.Pixel(3, -30)
    })
    infoWindow.open(mapIns, e.target.getPosition())
  })
  // markerInstance.on('click', () => {
  //   mapIns.clearInfoWindow()
  // })
}

const dataHandle = (newData: dataJsonType) => {
  if (!mapIns && !AMapIns) {
    initMap(props.chartConfig.option)
    return
  }
  if (isArray(newData.markers)) {
    // 先清除旧标记
    mapIns.remove(markers)
    markers = []
    // 记录新标记
    if (mapMarkerType.value === MarkerEnum.MARKER) {
      newData.markers.forEach((markerItem: dataJsonMarkersType) => {
        console.log('🚀 ~ newData.markers.forEach ~ markerItem:', markerItem.extraInfo.deviceState)
        const markerInstance = new AMapIns.Marker({
          position: [markerItem.position[0], markerItem.position[1]],
          offset: new AMapIns.Pixel(-13, 5),
          icon: new AMapIns.Icon({
            image:
              markerItem.extraInfo.deviceState === 'ONLINE'
                ? online
                : markerItem.extraInfo.deviceState === 'INACTIVE'
                ? inactive
                : offline,
            size: new AMapIns.Size(35, 35), //图标所处区域大小
            imageSize: new AMapIns.Size(35, 35) //图标大小
          })
        })
        // 原作者这种方式添加,属于JS API 1.4.8版本的
        markers.push(markerInstance)
        markerInstance.setMap(mapIns)
        // mapIns.add(markerInstance)
        mapClick(markerInstance, markerItem)
      })
    } else if (mapMarkerType.value === MarkerEnum.CIRCLE_MARKER) {
      newData.markers.forEach((markerItem: dataJsonMarkersType) => {
        const markerInstance = new AMapIns.CircleMarker({
          center: [
            !markerItem.position[0] ? 0 : markerItem.position[0],
            !markerItem.position[1] ? 0 : markerItem.position[1]
          ],
          radius: markerItem.value, //圆圈半径大小
          ...marker.value
        })
        // markers.push(markerInstance) //原作者这种方式添加,属于JS API 1.4.8版本的
        // markerInstance.setMap(mapIns)
        mapIns.add(markerInstance)
        mapClick(markerInstance, markerItem) // circle点击无效
      })
    }
  }
}

const stopWatch = watch(
  () => props.chartConfig.option.mapOptions,
  option => {
    initMap(option)
  },
  {
    immediate: true,
    deep: true
  }
)

watch(
  () => props.chartConfig.option.dataset,
  newData => {
    try {
      dataHandle(newData)
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: false
  }
)

// 预览
useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any) => {
  stopWatch()
  setTimeout(() => {
    dataHandle(newData)
  }, 1000)
})
</script>

<style>
/**去除高德地图原生弹窗 */
.amap-info-outer,
.amap-menu-outer {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0) !important;
}

.amap-info-outer {
  background-color: rgba(0, 0, 0, 0) !important;
}

.amap-info-close {
  display: none !important;
}

.amap-info-content {
  width: 30rem;
  height: 20rem;
  overflow: hidden !important;
  position: relative;
}

/**去除高德地图原生弹窗*/
.amap-info-content .go-border-box {
  position: absolute;
  transform: scale(0.68);
  top: 0;
  z-index: -100;
}

.amap-info-content .go-border-box svg {
  background-color: v-bind(bgColor);
}
</style>
<style lang="scss" scoped>
.chart-amap {
  position: relative;

  .search-box {
    cursor: pointer;
    position: absolute;
    right: -25px;
    top: 15px;
    z-index: 9999;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
  }
}
</style>