<script>
export default {
  name: "AppMap",
  label: "地图",
  data() {
    return {
      map: null,
      layers: [],
      geoJson: null,
    }
  },
  computed: {
    search: v => v.$marketBoard.search,
    thirdGoods: v => v.$marketBoard.thirdGoods || {}
  },
  watch: {
    search: {
      deep: true, handler() {
        this.getData().then(() => this.refreshData())
      }
    },
    thirdGoods: {
      deep: true, handler() {
        this.getData().then(() => this.refreshData())
      }
    },
  },
  methods: {
    loadLib() {
      return Promise.all([
        '/presource/datascreen/js/turf.min.js',
      ].map(e => $loadScript('js', e)))
    },
    getContent([x, y, bakeStockAmt = 0, preSaleNum = 0, stockNum = 0] = []) {
      if (this.thirdGoods.thirdGoodsCode) {
        return [`库存数量：${stockNum}`]
      }
      return [`现烤库存金额：${bakeStockAmt}`, `现烤销售机会：${preSaleNum}`]
    },
    getData() {
      const {$http, $waitFor} = window
      const {search: {groupCodeList, currentDate, hourNum}, thirdGoods: {thirdGoodsCode}} = this
      const maps = []
      return $waitFor($http).then(() => Promise.all([
        $http.post("/data-boot/la/screen/marketBoard/storeReport", {
          groupCodeList, currentDate, hourNum, thirdGoodsCode
        }).then(res => {
          if (res?.data) {
            return this.layers = res.data || []
          }
        }),
        axios.get('http://10.0.97.209/blade-visual/map/data?id=1456').then(res => {
          if (res?.data) {
            return maps.push(res.data.features)
          }
        }),
        axios.get('http://10.0.97.209/blade-visual/map/data?id=1469').then(res => {
          if (res?.data) {
            return maps.push(res.data.features)
          }
        })
      ])).then(() => {
        return this.geoJson = {type: 'FeatureCollection', features: maps.flat(1)}
      })
    },
    async initMap() {
      const {echarts, turf} = window
      const boundary = turf.union(this.geoJson)
      boundary.properties.name = "boundary"
      this.geoJson.features.unshift(boundary)
      echarts.registerMap('zhengzhou', this.geoJson)
      this.map = echarts.init(this.$el)
      while (!this.map) {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.map = echarts.init(this.$el)
      }
      const areaColor = {
        type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
          {offset: 0, color: 'rgba(61,127,255,0.35)'},
          {offset: 1, color: '#09E2F8'},
        ]
      }
      const label = {
        show: true,
        backgroundColor: {type: 'linear', x: 0, y: 0, x2: 1, y2: 0, colorStops: [{offset: 0, color: 'rgba(9,63,107,0.79)'}, {offset: 1, color: 'rgba(13,58,99,0.03)'}]},
        borderRadius: 2,
        padding: 8,
        position: 'right',
        formatter: (params) => {
          const {name, value} = params
          return `{a|${name}\n${this.getContent(value).join("\n")}}`
        },
        rich: {
          a: {color: '#fff', fontSize: 12, lineHeight: 14}
        }
      }
      this.map.setOption({
        geo: {
          map: 'zhengzhou', roam: true, emphasis: {disabled: true},
          itemStyle: {areaColor: "transparent", borderColor: '#97CAE6'},
          silent: true,
          label: {show: true, color: '#fff'},
          regions: [
            {name: "boundary", itemStyle: {areaColor, shadowColor: "#1A80BF", shadowOffsetY: 2}, label: {show: false}}
          ],
        },
        series: [
          {type: 'scatter', coordinateSystem: 'geo', itemStyle: {color: '#66FFFF'}, label},
          {type: 'effectScatter', coordinateSystem: 'geo', itemStyle: {color: '#FFD15C'}, label}
        ],
        tooltip: {
          trigger: 'item', formatter: params => {
            const {name, marker, value} = params
            return `${marker} ${name}<br/>${this.getContent(value).join("<br/>")}`
          },
        },
      })
      this.map.on('click', evt => {
        const storeCode = evt.data.storeCode
        if (storeCode) {
          this.$storeBoard.search.storeCode = storeCode
          this.$marketBoard.screenId = 'a90522ef-869b-40ea-8542-d1fc9674a1e8'
        }
      })
      this.refreshData()
    },
    convertData(layers) {
      const result = {normal: [], abnormal: []}
      layers.forEach(e => {
        const item = {name: e.storeName, storeCode: e.storeCode, value: [e.longitude, e.latitude, e.bakeStockAmt, e.preSaleNum, e.stockNum]}
        // 有库存或者有现烤库存金额 就算正常
        if (e.bakeStockAmt > 0 || e.stockNum > 0) {
          result.normal.push(item)
        } else {
          result.abnormal.push(item)
        }
      })
      return Object.values(result).map(data => ({data}))
    },
    refreshData() {
      const {thirdGoods: {goodsName}} = this
      const title = {left: 20, top: 20, text: goodsName ? `{sub|选择产品：}${goodsName}` : '', textStyle: {color: "#fff", rich: {sub: {color: "#fff", fontSize: 16}}}}
      this.map.setOption({title, series: this.convertData(this.layers)})
    },
  },
  mounted() {
    this.loadLib().then(() => Promise.all([
      this.getData(),
    ])).then(() => this.initMap())
  }
}
</script>

<template>
  <div class="AppMap"/>
</template>

<style>
</style>
