index.vue 8.41 KB
<template>
  <v-chart
    @click="handleVChartClick"
    ref="vChartRef"
    :init-options="initOptions"
    :theme="themeColor"
    :option="option.value"
    :manual-update="isPreview()"
    :loading="loading"
    :loadingOptions="{ maskColor: '#18181C', text: '加载中', textColor: 'white' }"
    autoresize
  >
  </v-chart>
</template>

<script setup lang="ts">
import { PropType, reactive, watch, ref, nextTick } from 'vue'
import config, { includes, areaEnum } from './config'
import VChart from 'vue-echarts'
import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook'
import { use, registerMap } from 'echarts/core'
import { EffectScatterChart, MapChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { useChartDataFetch } from '@/hooks'
import { mergeTheme, setOption } from '@/packages/public/chart'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { isPreview } from '@/utils'
import mapJsonWithoutHainanIsLands from './mapWithoutHainanIsLands.json'
import { DatasetComponent, GridComponent, TooltipComponent, GeoComponent, VisualMapComponent } from 'echarts/components'
import { getGeoJsonMap } from '@/api/external/common'

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

const initOptions = useCanvasInitOptions(props.chartConfig.option, props.themeSetting)

use([
  MapChart,
  DatasetComponent,
  CanvasRenderer,
  GridComponent,
  TooltipComponent,
  GeoComponent,
  EffectScatterChart,
  VisualMapComponent
])

const loading = ref(true)

const iconStr = ref(
  'path://M853.333333 245.333333H245.333333l93.866667-93.866666c12.8-12.8 12.8-34.133333 0-46.933334-12.8-12.8-34.133333-12.8-46.933333 0l-145.066667 145.066667c-12.8 12.8-12.8 34.133333 0 46.933333l145.066667 145.066667c6.4 6.4 14.933333 10.666667 23.466666 10.666667s17.066667-4.266667 23.466667-10.666667c12.8-12.8 12.8-34.133333 0-46.933333L256 311.466667h597.333333c6.4 0 10.666667 4.266667 10.666667 10.666666v426.666667c0 6.4-4.266667 10.666667-10.666667 10.666667H170.666667c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32h682.666666c40.533333 0 74.666667-34.133333 74.666667-74.666667V320c0-40.533333-34.133333-74.666667-74.666667-74.666667z'
)

const option = reactive({
  value: mergeTheme(props.chartConfig.option, props.themeSetting, includes)
})

const toolBoxOption = ref({
  show: true,
  right: 110,
  top: 20,
  feature: {
    myFullButton: {
      show: true,
      title: '返回',
      icon: iconStr.value,
      iconStyle: {
        color: ''
      },
      onclick: () => watchAdcode()
    }
  }
})

watch(
  () => props.chartConfig.option,
  newData => {
    const { iconColor, drillingIn, iconDistanceRight, iconDistanceTop } = newData
    toolBoxOption.value.feature.myFullButton.show = drillingIn
    toolBoxOption.value.feature.myFullButton.iconStyle.color = iconColor
    toolBoxOption.value.right = iconDistanceRight
    toolBoxOption.value.top = iconDistanceTop
  },
  {
    deep: true
  }
)

props.chartConfig.option = {
  ...props.chartConfig.option,
  ...{ toolbox: toolBoxOption.value }
}

//地图点击返回 adcode=100000,名字必须是china
const watchAdcode = async () => {
  if (props.chartConfig.option.drillingIn) {
    saveLevelStr.level = saveLevelStr.parentInfo.level
    await getGeojson(saveLevelStr.parentInfo.adcode)
    props.chartConfig.option.geo.map =
      saveLevelStr.parentInfo.adcode === 100000 ? 'china' : saveLevelStr.parentInfo.adcode
    props.chartConfig.option.series.forEach((item: any) => {
      if (item.type === 'map')
        item.map = saveLevelStr.parentInfo.adcode === 100000 ? 'china' : saveLevelStr.parentInfo.adcode
    })
    vEchartsSetOption()
  }
}

const vChartRef = ref<typeof VChart>()

const saveGeojson: any = ref({}) // 保存geojson

const chinaDefaultRegionId = ref(100000) //如果是china则adcode为100000

const saveLevelStr = reactive({
  // 保存行政级别和上一级的adcode和level
  level: '',
  parentInfo: {
    adcode: 0,
    level: ''
  }
})

//动态注册地图
const getGeojson = async (regionId: any) => {
  try {
    const { levelStr } = props.chartConfig.option.mapRegion.saveSelect //右侧配置项获取的行政级别
    const { data } = await getGeoJsonMap(
      regionId === 'china' ? chinaDefaultRegionId.value : regionId,
      !saveLevelStr.level ? levelStr : saveLevelStr.level
    )
    const { geoJson, name, code, level } = data
    const geoJsonFile = JSON.parse(geoJson)
    if (!geoJsonFile) return
    saveGeojson.value = geoJsonFile
    registerMap(level === areaEnum.COUNTRY ? name : code, { geoJSON: geoJsonFile as any, specialAreas: {} })
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error('动态注册地图出错', error)
    //注册出错则注册空的,不然在选择正确的adcode,则视图无法更新
    registerMap(props.chartConfig.option.mapRegion.adcode, { geoJSON: {} as any, specialAreas: {} })
  }
}

//异步时先注册空的 保证初始化不报错
registerMap(props.chartConfig.option.mapRegion.adcode, { geoJSON: {} as any, specialAreas: {} })

// 进行更换初始化地图 如果为china 单独处理
const registerMapInitAsync = async () => {
  await nextTick()
  const adCode = props.chartConfig.option.mapRegion.adcode
  if (adCode !== 'china') {
    await getGeojson(adCode)
  } else {
    await hainanLandsHandle(props.chartConfig.option.mapRegion.showHainanIsLands)
  }
  vEchartsSetOption()
}
registerMapInitAsync()

// 手动触发渲染
const vEchartsSetOption = async () => {
  try {
    option.value = props.chartConfig.option
    setOption(vChartRef.value, props.chartConfig.option)
  } catch (error) {
    console.error('触发渲染出错', error)
  }
}

// 更新数据处理
const dataSetHandle = async (dataset: any) => {
  props.chartConfig.option.series.forEach((item: any) => {
    if (item.type === 'effectScatter' && dataset.point) item.data = dataset.point
    else if (item.type === 'map' && dataset.map) item.data = dataset.map
  })
  if (dataset.pieces) props.chartConfig.option.visualMap.pieces = dataset.pieces
  isPreview() && vEchartsSetOption()
}

// 处理海南群岛
const hainanLandsHandle = async (newData: boolean) => {
  if (newData) {
    await getGeojson('china')
  } else {
    registerMap('china', { geoJSON: mapJsonWithoutHainanIsLands as any, specialAreas: {} })
  }
}

//监听 dataset 数据发生变化
// watch(
//   () => props.chartConfig.option.dataset,
//   newData => {
//     dataSetHandle(newData)
//   },
//   {
//     immediate: true,
//     deep: false
//   }
// )

//监听是否显示南海群岛
watch(
  () => props.chartConfig.option.mapRegion.showHainanIsLands,
  async newData => {
    try {
      await hainanLandsHandle(newData)
      vEchartsSetOption()
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: false
  }
)

//监听地图展示区域发生变化
watch(
  () => props.chartConfig.option.mapRegion.adcode,
  async newData => {
    try {
      await getGeojson(newData)
      props.chartConfig.option.geo.map = newData
      props.chartConfig.option.series.forEach((item: any) => {
        if (item.type === 'map') item.map = newData
      })
      vEchartsSetOption()
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: false
  }
)

// 预览
useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any) => {
  dataSetHandle(newData)
})

const regionMapParentArea = {
  [areaEnum.PROVINCE]: areaEnum.COUNTRY, //省份的上一级 中国
  [areaEnum.CITY]: areaEnum.PROVINCE, //城市的上一级 省份
  [areaEnum.COUNTY]: areaEnum.CITY, //县或者区的上一级 城市
  [areaEnum.TOWN]: areaEnum.COUNTY //镇的上一级 县或者区
}

//地图点击下钻
const handleVChartClick = async (params: any) => {
  if (props.chartConfig.option.drillingIn) {
    const { name } = params
    saveGeojson.value?.features.forEach((item: any) => {
      if (item.properties.name === name) {
        const level = item.properties.level.toUpperCase()
        const adcode = item.properties.adcode
        props.chartConfig.option.mapRegion.adcode = adcode
        saveLevelStr.level = level
        saveLevelStr.parentInfo.adcode = item.properties.parent.adcode //保存上一级的地区编码
        saveLevelStr.parentInfo.level = (regionMapParentArea as any)[level] //保存上一级的行政级别
      }
    })
  }
}
</script>