<template>
  <view class="page">
    <!-- 1. 顶部标题 -->
    <view class="header">
      <text class="title">{{title}}</text>
	  <!-- 新增地图按钮 -->
	  <image
	    class="map-btn"
	    src="/static/img/tab.png"
	    mode="aspectFit"
	    @tap="goMap"
	  />
    </view>

    <!-- 2. 轮播图 -->
    <swiper
      class="swiper"
      circular
      :indicator-dots="true"
      :autoplay="true"
      :interval="3000"
      :duration="800"
    >
      <swiper-item v-for="(item, index) in picture" :key="index">
        <image :src="item" class="swiper-item" mode="aspectFill" />
      </swiper-item>
    </swiper>

    <!-- 3. 地图 -->
    <view class="map-box">
      <view @touchend="onTouchEnd" class="map-wrap">
        <canvas canvas-id="ydChart" id="ydChart" class="map-canvas" />
      </view>
    </view>
  </view>
</template>

<script>
import * as echarts from 'echarts'
import loginService from "@/api/auth/loginService";

export default {
  data() {
    return {
      chart: null,
	  title:'盐都区闲置厂房分布图',
      /* 轮播图示例，换成你的真实图片即可 */
      picture:["https://ydwqfw.com.cn/yd_qycpfbH5/bg1.jpg",
      "https://ydwqfw.com.cn/yd_qycpfbH5/bg2.jpg",
      "https://ydwqfw.com.cn/yd_qycpfbH5/bg3.jpg",
      "https://ydwqfw.com.cn/yd_qycpfbH5/bg4.jpg"],
	  parkList2: [],
	  buildingMap: new Map()   // 新增
    }
  },
  async onReady() {
    const json = await this.loadGeoJSON()
    echarts.registerMap('yanduqu', json)

    let canvasNode
    // #ifdef H5
    canvasNode = document.getElementById('ydChart')
    // #endif
    // #ifndef H5
    canvasNode = await new Promise(resolve => {
      uni.createSelectorQuery()
        .in(this)
        .select('#ydChart')
        .node(res => resolve(res.node))
        .exec()
    })
    // #endif

    this.chart = echarts.init(canvasNode, null, {
      width : uni.getSystemInfoSync().windowWidth,
      height: uni.getSystemInfoSync().windowHeight * 0.6   // 地图占屏幕 50%
    })
	this.getList()    
  },
  
  methods: {
	getList() {
	  	loginService.getParkList().then(({
	  		data
	  	}) => {		
			
			let alls = 0
			  data.forEach(item => { alls += item.building_cnt })
			  
			  for(var i = 0; i < data.length; i++){
			  	alls=alls+data[i].building_cnt;
				
				if(data[i].label.indexOf("高新区") != -1){
					data[i].label='盐龙'
				}
				// if(data[i].label.indexOf("大冈") != -1){
				// 	data[i].label='大冈镇'
				// }else if(data[i].label.indexOf("大纵湖") != -1){
				// 	data[i].label='大纵湖镇'
				// }else if(data[i].label.indexOf("学富") != -1){
				// 	data[i].label='学富镇'
				// }else if(data[i].label.indexOf("尚庄") != -1){
				// 	data[i].label='尚庄镇'
				// }else if(data[i].label.indexOf("张庄") != -1){
				// 	data[i].label='张庄镇'
				// }else if(data[i].label.indexOf("楼王") != -1){
				// 	data[i].label='楼王镇'
				// }else if(data[i].label.indexOf("潘黄") != -1){
				// 	data[i].label='潘黄街道'
				// }else if(data[i].label.indexOf("盐渎") != -1){
				// 	data[i].label='盐渎街道'
				// }else if(data[i].label.indexOf("秦南") != -1){
				// 	data[i].label='秦南镇'
				// }else if(data[i].label.indexOf("郭猛") != -1){
				// 	data[i].label='郭猛镇'
				// }else if(data[i].label.indexOf("高新区") != -1){
				// 	data[i].label='盐龙街道'
				// }else if(data[i].label.indexOf("龙冈") != -1){
				// 	data[i].label='龙冈镇'
				// }
				
			  }
			  
		
			  this.allcount = alls
			  this.parkList2 = data
		
			  /* 构造 name -> building_cnt 映射表 */
			  this.buildingMap = new Map(data.map(item => [item.label, item.building_cnt]))
		
			  /* 插入“全部”汇总行 */
			  this.parkList2.unshift({ total_area: 0, total_idle_area: 0, building_cnt: alls, label: '全部' })
		
			  this.renderMap()
			
	  	}).catch(e => {
	  		
	  	})
	  	
	},
    loadGeoJSON() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: './static/yandu.json',
          method: 'GET',
          success: res => resolve(res.data),
          fail: reject
        })
      })
    },
	goList(parkName) {

	    // 真正跳转
	    uni.navigateTo({
	      url: `/pages/factoryBuildings/factoryBuildingsList?parkid=${parkName}`
	    })
	},
	goMap() {
		uni.navigateTo({
		  url: `/pages/index/factoryindex`   // 换成你的地图页面路径
		})
	},
	onTouchEnd(e) {
		
	  const touch = e.changedTouches[0]
	  uni.createSelectorQuery()
	    .in(this)
	    .select('.map-wrap')
	    .boundingClientRect(rect => {
	      const dpr = uni.getSystemInfoSync().pixelRatio        // 关键1：拿到 dpr
	      const xCss = touch.clientX - rect.left                // CSS 像素
	      const yCss = touch.clientY - rect.top
	      const xCanvas = xCss ;                            // 关键2：转成 canvas 物理像素
	      const yCanvas = yCss ;

	      // 用物理像素判断
	      const inGeo = this.chart.containPixel('geo', [xCanvas, yCanvas])

	      if (inGeo) {
	        // 拿到逻辑坐标（供 emit 用）
	        const [lng, lat] = this.chart.convertFromPixel('geo', [xCanvas, yCanvas])

	        // 直接 emit 一个 click 事件，把 name 传出去
	        // 先用 chart.getOption().series[0].data 里匹配，这里简化：用 convert 回来的坐标反查
	        const geoModel = this.chart.getModel().getComponent('geo', 0)
	        const region = geoModel.coordinateSystem.getRegionByCoord([lng, lat])
			const name = region ? region.name : ''
			
	        if (region) {
	          this.goList(name)
	        }
	      }
	    })
	    .exec()

	},
	
    renderMap() {
		const mapData = []
		/* 如果你知道所有镇名，可以写死；否则把 geoJSON 里的名字读出来即可 */
		const townNames = ['台创园', '大冈镇', '大纵湖镇', '学富镇', '尚庄镇', '张庄街道', '楼王镇','潘黄街道','盐渎街道', '秦南镇', '郭猛镇', '盐龙街道', '龙冈镇']
		townNames.forEach(name => {
		  mapData.push({
			name,
			value: this.buildingMap.get(name) || 0   // 没有就按 0 处理
		  })
		})
		
      const option = {
         geo: [{
              map: 'yanduqu',
              roam: true,
              aspectScale: 1.2,
              zoom: 1.3,
              itemStyle: {
				normal: {
				  areaColor: {
					type: 'linear-gradient',
					x: 0,
					y: 400,
					x2: 0,
					y2: 0,
					colorStops: [{
					  offset: 0,
					  color: 'rgba(37,108,190,0.8)' // 0% 处的颜色
					}, {
					  offset: 1,
					  color: 'rgba(15,169,195,0.8)' // 50% 处的颜色
					}],
					global: true // 缺省为 false
				  },
				  borderColor: '#4ecee6',
				  borderWidth: 1
				},
				emphasis: {
				  areaColor: {
					type: 'linear-gradient',
					x: 0,
					y: 300,
					x2: 0,
					y2: 0,
					colorStops: [{
					  offset: 0,
					  color: 'rgba(37,108,190,1)' // 0% 处的颜色
					}, {
					  offset: 1,
					  color: 'rgba(15,169,195,1)' // 50% 处的颜色
					}],
					global: false // 缺省为 false
				  },
				}
			  },
              emphasis: {
                itemStyle: { areaColor: '#ffca28' }
              },
              // 关键：打开标签
              label: {
                show: true,          // 默认显示名称
                color: '#fff',       // 文字颜色
                fontSize: 12,        // 字号
                fontWeight: 'bold',
				/* 关键：让标签显示两行 */
				  formatter: params => {
					const cnt = this.buildingMap.get(params.name) || 0
					return `${params.name} ${cnt} 处`
					//return `${params.name}`
				  }
              }
            }],
            series: [{ type: 'map', geoIndex: 0, data: mapData    },]
      }
      this.chart.setOption(option)

      this.chart.on('click', params => {
		uni.navigateTo({
			url: `/pages/factoryBuildings/factoryBuildingsList?parkid=${params.name}`
		})

      })
    }
  }
}
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

/* 顶部标题 */
.header {
  position: relative;   /* 让子元素绝对定位参照它 */
  padding: 20rpx 0;
  text-align: center;
  background: #fff;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
/* 右上角地图按钮 */
.map-btn {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 48rpx;
  height: 48rpx;
}

/* 轮播图 */
.swiper {
  width: 100%;
  height: 300rpx;
}
.swiper-item {
  width: 100%;
  height: 100%;
}

/* 地图容器 */
.map-box {
  flex: 1;
  width: 100%;
  /* background: #003366; */   /* 任意你想要的深色 */
}
.map-canvas {
  width: 100%;
  height: 100%;
}
</style>