<template>
  <view class="page">
    <!-- 顶部标题 -->
    <view class="header">
      <text class="title">{{ title }}</text>
      <text class="list-btn" @tap="goList('全部')">列表</text>
    </view>

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

    <!-- 腾讯地图 -->
    <map
      id="tencentMap"
      class="tmap"
      :longitude="centerLng"
      :latitude="centerLat"
      :scale="scale"
      :subkey="mapKey"
      :show-location="false"
      :enable-zoom="true"
      :enable-scroll="true"
      @tap="mapTap"
      @regionchange="regionChange"
    >
      <!-- 各镇覆盖物（polygon） -->
      <polygon
        v-for="item in townPolygons"
        :key="item.name"
        :points="item.points"
        :strokeWidth="2"
        :strokeColor="item.stroke"
        :fillColor="item.fill"
        @tap="tapTown(item.name)"
      />
    </map>
  </view>
</template>

<script>
import loginService from '@/api/auth/loginService'
const qqMap = require('../../libs/qqmap-wx-jssdk.min.js')   // 官方下载
const qqmapsdk = new qqMap({ key: 'N4YBZ-EB2WZ-JCIXK-7G6R5-6NJNV-7OFNK' })

export default {
  data() {
    return {
      title: '盐都区闲置厂房分布图',
      pictures: [
        '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'
      ],
      mapKey: 'N4YBZ-EB2WZ-JCIXK-7G6R5-6NJNV-7OFNK',
      centerLng: 120.156,   // 盐都区政府大致经度
      centerLat: 33.108,
      scale: 10,             // 初始缩放
      townCntMap: new Map(), // name -> building_cnt
      townPolygons: []       // 供给 <polygon> 组件
    }
  },
  async onLoad() {
    await this.getList()     // 先拉取各镇厂房数量
    await this.loadDistrictBorder() // 再画行政区
  },
  methods: {
    /* 1. 获取各镇厂房数，与之前逻辑完全一致 */
    getList() {
      return loginService.getParkList().then(({ data }) => {
        let all = 0
        data.forEach(item => { all += item.building_cnt })
        this.townCntMap = new Map(data.map(item => [item.label, item.building_cnt]))
      })
    },
    /* 2. 拉取盐都区边界并拆成各镇 */
   /* 2. 通过 WebService 拿盐都区各镇边界 */
   loadDistrictBorder() {
     return new Promise((resolve, reject) => {
       uni.request({
         url: 'https://apis.map.qq.com/ws/district/v1/getchildren',
         method: 'GET',
         data: {
           keyword: '盐都区',
           key: this.mapKey,          // 你申请的 key
           output: 'json',
           extensions: 'all'          // 返回边界 polyline
         },
         success: res => {
           const data = res.data
           if (data.status !== 0) {
             console.error('district api error:', data.message)
             reject(data.message)
             return
           }
           // data.result[0] 就是盐都区下属镇/街道
           const towns = data.result[0]
           const polygons = []
           towns.forEach(t => {
             // 边界字符串 -> 经纬度数组
             const path = []
             if (t.polyline) {
               t.polyline.split(';').forEach(ll => {
                 const [lat, lng] = ll.split(',').map(Number)
                 path.push({ latitude: lat, longitude: lng })
               })
             }
             const cnt = this.townCntMap.get(t.fullname) || 0
             polygons.push({
               name: t.fullname,
               points: path,
               fill: cnt > 0 ? '#4A90E2AA' : '#E0E0E0AA',
               stroke: cnt > 0 ? '#ffffff' : '#cccccc'
             })
           })
           this.townPolygons = polygons
           resolve()
         },
         fail: reject
       })
     })
   },
    /* 3. 点击镇面 -> 跳转列表 */
    tapTown(name) {
      uni.navigateTo({ url: `/pages/factoryBuildings/factoryBuildingsList?parkid=${name}` })
    },
    /* 4. 右上角列表按钮 */
    goList() {
      uni.navigateTo({ url: '/pages/factoryBuildings/factoryBuildingsList?parkid=全部' })
    },
    /* 5. 地图空白处点一下，关闭气泡（这里没气泡，可留空） */
    mapTap(e) {},
    regionChange(e) {}
  }
}
</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;
}
.list-btn {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  background: #1296db;
  color: #fff;
  padding: 8rpx 30rpx;
  border-radius: 15rpx;
  font-size: 28rpx;
}
.swiper {
  width: 100%;
  height: 300rpx;
}
.swiper-item {
  width: 100%;
  height: 100%;
}
.tmap {
  flex: 1;
  width: 100%;
}
</style>