<template>
  <div class="container">
    <div id="container" @click="handleInfoWindowClick"></div>
    <div class="tips">
      <div class="tip-item">
        <img :src="icons.blue" alt="蓝色">
        <span class="span-class">待骑行</span>
      </div>
      <div class="tip-item">
        <img :src="icons.green" alt="绿色">
        <span class="span-class">预约中</span>
      </div>
      <div class="tip-item">
        <img :src="icons.yellow" alt="黄色">
        <span class="span-class">骑行中</span>
      </div>
      <div class="tip-item">
        <img :src="icons.orange" alt="橙色">
        <span class="span-class">临时停车</span>
      </div>
      <div class="tip-item">
        <img :src="icons.red" alt="红色">
        <span class="span-class">离线中</span>
      </div>
      <div class="tip-item">
        <img :src="icons.redyellow" alt="红黄">
        <span class="span-class">离线骑行</span>
      </div>
      <div class="tip-item">
        <img :src="icons.orangered" alt="橙红">
        <span class="span-class">离线临时锁车</span>
      </div>
      <div class="tip-item">
        <img :src="icons.gray" alt="灰色">
        <span class="span-class">未上架/下线</span>
      </div>
    </div>
    <div class="input-card">
      <el-button @click="setFitView()">全局查看</el-button>
      <el-button @click="changeMapStyle()">切换地图</el-button>
      <el-button @click="showMarkers">显示/隐藏文字</el-button>
    </div>

    <el-dialog style="font-weight: bold;" title="设备详情" :visible.sync="open2" width="1000px" append-to-body>
      <el-form ref="form" :model="form"  label-width="100px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备mac：">{{ form.mac }}</el-form-item>
            <el-form-item label="设备sn：">{{ form.sn }}</el-form-item>
            <el-form-item label="车辆状态：" style="color: #12d2ac;font-weight: 700">{{ form.statusStr }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分区：" style="color:#4c97e7;font-weight: 700">{{ form.areaName }}</el-form-item>
            <el-form-item label="剩余电量：" >{{ form.remainingPower }}%</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="二维码：">
              <template>
                <el-popover
                  placement="top"
                  width="180"
                  trigger="hover">
                  <div class="qr-code-box">
                    <qr-code :text="form.qrText" :width="150" :height="150" />
                  </div>
                  <el-button slot="reference" type="text" icon="el-icon-picture">查看</el-button>
                </el-popover>
              </template>
            </el-form-item>
            <el-form-item label="网络状态：" style="color: #ffcc00;font-weight: 700">{{ form.onlineStatus == 1 ? '在线' : '离线' }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <div class="nav-container">
            <el-menu :default-active="activeIndex" class="el-menu-demo nav-menu" mode="horizontal" @select="handleSelect">
              <el-menu-item index="1" >使用记录</el-menu-item>
              <el-menu-item index="2" >维修记录</el-menu-item>
              <el-menu-item index="3" >换电记录</el-menu-item>
            </el-menu>
            <div class="line"></div>
          </div>
        </el-row>
        <el-row>
          <order-record v-show="activeIndex == '1'" :sn="form.sn"/>
          <repair-record v-show="activeIndex == '2'" :sn="form.sn"/>
          <replacement-record v-show="activeIndex == '3'" :sn="form.sn"/>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open2 = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
  import AMapLoader from "@amap/amap-jsapi-loader";
  import globalConfig from "@/utils/config/globalConfig";
  import { getDevice, listDevice } from '@/api/system/device'
  import {listArea} from "@/api/system/area";
  import { listParking } from '@/api/system/parking'
  import LocationMap from '@/components/Map/location/LocationMap'
  import OrderRecord from '@/views/system/device/components/orderRecord'
  import RepairRecord from '@/views/system/device/components/repairRecord'
  import ReplacementRecord from '@/views/system/device/components/replacementRecord'
  import QrCode from '@/components/QrCode'

  function formarStatus(status,onlineStatus) {
    if(onlineStatus == "0"){
      if(status == "3"){
        return globalConfig.icon.redyellow;
      }else if(status == "4"){
        return globalConfig.icon.orangered;
      }
      return globalConfig.icon.red;
    }else{
      if(status == "0"){
        return globalConfig.icon.gray;
      }else if(status == "1"){
        return globalConfig.icon.blue;
      }else if(status == "2"){
        return globalConfig.icon.green;
      }else if(status == "3"){
        return globalConfig.icon.yellow;
      }else if(status == "4"){
        return globalConfig.icon.orange;
      }else if(status == "8"){
        return globalConfig.icon.gray;
      }else if(status == "9"){
        return globalConfig.icon.gray;
      }
    }
  }
  export default {
    name: "map-view",
    components: { OrderRecord, RepairRecord, ReplacementRecord,QrCode,LocationMap },
    data() {
      return {
        AMap: null,
        map: null,  // 地图实例
        markers: [],
        labels: [],
        tips: null,
        // 运营区表格数据
        areaList: [],
        lon: null,
        lat: null,
        area:null,
        ids: null,
        showDialog: null,
        icons: globalConfig.icon,
        showPlaceSearchMap: false,
        selected: null,
        activeIndex: '1',
        cluster: null,
        data: [],
        show: false,
        // 详情窗口
        open2: false,
        // 表单参数
        form: {},
        infoWindow: null,
        // 设备表格数据
        deviceList: [],
        onDeviceList: [],
        parkingList: [],
        noParkingList: [],
        noridingList: [],
        type: null
      }
    },
    mounted() {
      this.getAreaList();
    },
    unmounted() {
      this.map?.destroy();
    },
    methods: {
      onMapGeo(data, lat, lng) {
        console.log("onMapGeo", data)
        let component = data.regeocode.addressComponent;
        this.selected = {
          address: data.regeocode.formattedAddress,
          lng: lat,
          lat: lng,
          province: component.province,
          city: component.city === '' ? '市辖区' : component.city,
          county: component.district,
          name: component.street + component.streetNumber
        }
      },
      onSelectChange(addr) {
        console.log("onSelectChange", addr)
        let data = addr.selected.data;
        this.selected = {
          address: data.pname + (data.cityname === data.pname ? '' : data.cityname) + data.adname + data.address + data.name,
          lng: data.location.lng,
          lat: data.location.lat,
          province: data.pname,
          city: data.cityname === data.pname ? '市辖区' : data.cityname,
          county: data.adname,
          name: data.address + data.name,
        }
      },
      handleSelect(key, keyPath) {
        this.activeIndex = key;
        console.log(key, keyPath);
      },
      showMarkers() {
        if(this.show){
          // this.markers.forEach(marker => {
          //   marker.show();
          // });
          this.labels.forEach(label => {
            label.show();
          });
        }else{
          // this.markers.forEach(marker => {
          //   marker.hide();
          // });
          this.labels.forEach(label => {
            label.hide();
          });
        }
        this.show = !this.show;
        const elements = document.querySelectorAll('.apiary-marker-name');
        elements.forEach(element => {
          element.style.visibility = this.show ? 'hidden' : 'visible';
        });
      },
      async getAreaList(){
        listArea().then(response => {
          this.areaList = response.rows;
          if (this.areaList.length > 0) { // 确保数组不为空
            const firstArea = this.areaList[0]; // 获取第一个元素
            this.area = firstArea;
            console.log('第一个区域的信息:', firstArea);
            this.lon = firstArea.longitude;
            this.lat = firstArea.latitude;
            console.log("area============="+JSON.stringify(this.area))
            listParking({areaId: this.area.areaId}).then(response => {
              let list = response.rows;
              list.forEach(item => {
                if (item.type === '1') {
                  this.parkingList.push(item);
                } else if (item.type === '2') {
                  this.noParkingList.push(item);
                } else if (item.type === '3') {
                  this.noridingList.push(item);
                }
              });
              console.log("parkingList============="+JSON.stringify(this.parkingList));
              console.log("noParkingList============="+JSON.stringify(this.noParkingList));
              console.log("noriding============="+JSON.stringify(this.noridingList));
              this.initAMap();
            });
          }else{
            console.log('区域列表为空');
          }
        });
      },
      changeMapStyle(){
        // 创建一个默认的图层组件
        let defaultLayer = new AMap.TileLayer();
        // 创建一个卫星图图层组件
        let satelliteLayer = new AMap.TileLayer.Satellite();
        let roadNetLayer = new AMap.TileLayer.RoadNet();
        // 将默认图层添加到地图中
        this.map.add(defaultLayer);
        // 获取当前地图显示的图层
        let currentLayer = this.map.getLayers()[0]; // 假设默认图层在第一个位置
        // 切换图层
        if(this.type=='default'){
          console.log(1111111)
          //获取地图图层数据
          this.map.setLayers([defaultLayer]); // 切换回默认图层
          this.type = 'Satellite';
        }else{
          console.log(222222)
          this.map.setLayers([satelliteLayer,roadNetLayer]); // 切换到卫星图图层
          this.type = 'default';
        }
      },
      setFitView(){
        this.map.setFitView(null, false, [150, 60, 100, 60]);
      },
      initAMap() {
        AMapLoader.load({
          key: globalConfig.aMap.key, // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        }).then((AMap) => {
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 13, // 初始化地图级别
            center: [this.lon,this.lat], //初始化地图中心点位置
          });
          // 创建信息窗体
          this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -30)
          });
          //设备点标记
          this.deviceMarker();
          //运营区边界
          this.areaList.forEach(area => {
            this.addArea(JSON.parse(area.boundaryStr) || []);
          });
          //停车区
          this.parkingList.forEach(parking => {
            this.addParking(JSON.parse(parking.boundaryStr) || [],parking.parkingName,parking.longitude,parking.latitude);
            this.addMarker2(parking,"https://lxnapi.ccttiot.com/FqcYf6ecsnbC0OT6YYAF5npgu-kh",parking.parkingName,"#1890ff");
          });
          //禁停区
          this.noParkingList.forEach(noparking => {
            this.addNoParking(JSON.parse(noparking.boundaryStr) || []);
            this.addMarker2(noparking,"https://lxnapi.ccttiot.com/FjKE5PWbnEnZUq3k-wVIvV4lv8Ab",noparking.parkingName,"#ff4444");
          });
          //禁行区
          this.noridingList.forEach(noriding => {
            this.addNoriding(JSON.parse(noriding.boundaryStr) || [],noriding.parkingName,noriding.longitude,noriding.latitude);
            this.addMarker2(noriding,"https://lxnapi.ccttiot.com/FmX1diEPPbFYe1vcUfKp6qbKzzh2",noriding.parkingName,"#ffcc00");
          });
          // setTimeout(() => {
          //   this.setFitView();
          // }, 2000);
        }).catch((e) => {
          console.log(e);
        });
      },
      // 刷新点标记
      freshMarker(points) {
        let that = this;

        // 聚合对象存在，则修改数据
        if (this.cluster != null) {
          this.cluster.setData(points);
        }else {
          this.map.plugin(["AMap.MarkerCluster"], () => {
            that.cluster = new AMap.MarkerCluster(
              this.map, //地图实例
              points, //海量点数据，数据中需包含经纬度信息字段 lnglat
              {
                styles: this.getStyles(),
                renderMarker: this.getRenderMarker, //上述步骤的自定义非聚合点样式
              }
            );
            that.cluster.on('click', that.onClickCluster)
          });
        }
      },
      // 点击聚合对象事件
      onClickCluster(e) {
        console.log("点击聚合点====",e)
        this.onDeviceList = e.clusterData.map(item => item);
        // 如果数量 > 1，则打开列表页
        if (this.onDeviceList.length > 1) {
          console.log("打开列表====",this.onDeviceList)
          let content = this.generateInfoContent(this.onDeviceList);
          this.infoWindow.setContent(content);
          this.infoWindow.open(this.map, e.lnglat);
        }
      },
      generateInfoContent(data) {
        let content = `<div><table  class="info-table">
        <thead>
          <tr>
            <th>SN</th>
            <th>车牌号</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>`;
        data.forEach(item => {
          content += `<tr>
          <td>${item.sn}</td>
          <td>${item.vehicleNum}</td>
          <td>${formatVehicleStatus(item.status)}</td>
          <td><button class="detail-btn" data-device-id="${item.deviceId}">详情</button></td>
        </tr>`;
        });
        content += `</tbody>
      </table></div>`;
        function formatVehicleStatus(status) {
          switch (status) {
            case '7':
              return '未绑定';
            case '0':
              return '仓库中';
            case '1':
              return '待骑行';
            case '2':
              return '预约中';
            case '3':
              return '骑行中';
            case '4':
              return '临时停车';
            case '8':
              return '禁用';
            case '9':
              return '废弃';
            default:
              return '未知状态';
          }
        }
        return content;
      },
      handleInfoWindowClick(event) {
        console.log("点击详情按钮====",event)
        const button = event.target.closest('.detail-btn');
        if (button) {
          const deviceId = button.getAttribute('data-device-id');
          this.onClickMarker(deviceId);
        }
      },
      // 自定义非聚合点样式
      getRenderMarker(context) {
        let device = context.data[0];
        let content = `
            <div class="apiary-marker">
                <div style="visibility: ${this.show ? 'hidden' : 'visible'};" class="apiary-marker-name">${device.vehicleNum}</div>
                <image class="apiary-marker-img" src='${formarStatus(device.status,device.onlineStatus)}'/>
            </div>
      `
        context.marker.setContent(content);
        context.marker.on("click", () => this.onClickMarker(device.deviceId));
      },
      // 点击非聚合点事件
      onClickMarker(deviceId) {
        console.log("点击非聚合点====",deviceId)
        getDevice(deviceId).then(response => {
          this.open2 = true;
          this.form = response.data;
          this.showPlaceSearchMap = true;
          this.key++;
        });
      },
      openDetail(deviceId) {
        console.log("点击非聚合点====",deviceId)
        getDevice(deviceId).then(response => {
          this.open2 = true;
          this.form = response.data;
          this.showPlaceSearchMap = true;
          this.key++;
        });
      },
      getStyles() {
        return [
          {
            //聚合量在1-10时，聚合点的样式
            url: "//a.amap.com/jsapi_demos/static/images/blue.png", //图标显示图片的地址
            size: new AMap.Size(32, 32), //图标显示图片的大小
            offset: new AMap.Pixel(-16, -16), //图标定位在地图上的位置相对于图标左上角的偏移值
            textColor: "#fff", //文字的颜色
          },
          {
            //聚合量在11-100时，聚合点的样式
            url: "//a.amap.com/jsapi_demos/static/images/green.png",
            size: new AMap.Size(32, 32),
            offset: new AMap.Pixel(-16, -16),
            textColor: "#fff",
          },
          {
            //聚合量在101-1000时，聚合点的样式
            url: "//a.amap.com/jsapi_demos/static/images/orange.png",
            size: new AMap.Size(36, 36),
            offset: new AMap.Pixel(-18, -18),
            textColor: "#fff"
          },
          {
            //聚合量在1001-10000时，聚合点的样式
            url: "//a.amap.com/jsapi_demos/static/images/red.png",
            size: new AMap.Size(48, 48),
            offset: new AMap.Pixel(-24, -24),
            textColor: "#fff"
          },
          {
            //聚合量在10001-100000时，聚合点的样式
            url: "//a.amap.com/jsapi_demos/static/images/red.png",
            size: new AMap.Size(48, 48),
            offset: new AMap.Pixel(-24, -24),
            textColor: "#fff"
          },
        ]
      },
      addMarker2(parking, icon,title,color) {
        let marker = new AMap.Marker({
          map: this.map,
          icon: new AMap.Icon({
            image: icon,
            size: new AMap.Size(25, 36), // 设置图标的宽高
            imageSize: new AMap.Size(25, 36) // 设置图标的实际显示尺寸
          }),
          position: [parking.longitude, parking.latitude],
          offset: new AMap.Pixel(-12.5, -36)
        });

        this.markers.push(marker);

        console.log("title============="+title)
        // 创建一个 Text 实例来显示标题
        let text = new AMap.Text({
          text: title,
          anchor: 'center', // 设置文本的锚点
          position: [parking.longitude, parking.latitude],
          offset: new AMap.Pixel(0, -50),
          style: {
            'background-color': color, // 背景颜色为蓝色
            'border': 'none', // 边框颜色与背景一致
            'border-radius': '5px', // 圆角 5px
            'color': 'white', // 文字颜色为白色
            'font-size': '12px', // 字体大小
          }
        });

        // 将文本标签添加到地图实例
        this.map.add(text);
        console.log("text=============",text)
        this.labels.push(text)
      },
      deviceMarker(){
        listDevice({pageNum: 1,pageSize: 999}).then(response => {
          this.deviceList = response.rows;
          this.deviceList.forEach(device => {
            // 检查经纬度是否为空且为有效数字
            if (device.longitude !== null && device.latitude !== null &&
              !isNaN(device.longitude) && !isNaN(device.latitude)) {
              this.data.push({
                lnglat: [device.longitude, device.latitude],
                status: device.status,
                onlineStatus: device.onlineStatus,
                sn: device.sn,
                vehicleNum: device.vehicleNum,
                deviceId: device.deviceId
              });
              // this.addMarker(device.longitude, device.latitude, device.status, device.onlineStatus,device.sn);
            } else {
              console.warn(`无效的经纬度值: 经度=${device.longitude}, 纬度=${device.latitude}`);
            }
          });
          // 将所有标记添加到聚合器中
          this.freshMarker(this.data);
        }).catch(error => {
          console.error('获取设备列表失败:', error);
        });
      },
      addMarker(lng, lat, status, onlineStatus,title) {



      },

      //添加运营区边界
      addArea(data) {
        let polygon = new AMap.Polygon({
          path: data,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#2b8cbe',
          strokeWeight: 1,
          strokeStyle: 'dashed',
          strokeDasharray: [5, 5],
        });
        // polygon.on('mouseover', () => {
        //   polygon.setOptions({
        //     fillOpacity: 0.7,
        //     fillColor: '#7bccc4'
        //   })
        // })
        // polygon.on('mouseout', () => {
        //   polygon.setOptions({
        //     fillOpacity: 0.5,
        //     fillColor: '#ccebc5'
        //   })
        // })
        this.map.add(polygon);
      },
      addParking(data,title,lon,lat) {
        let polygon = new AMap.Polygon({
          path: data,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#3b7ed9',  // 修改边界颜色为红色
          strokeWeight: 2,         // 加粗边界
          strokeStyle: 'solid',
          strokeDasharray: [5, 5],
        });
        polygon.on('mouseover', () => {
          polygon.setOptions({
            fillOpacity: 0.7,
            fillColor: '#71b7cc'  // 鼠标悬浮时填充颜色为红色
          });
        });
        polygon.on('mouseout', () => {
          polygon.setOptions({
            fillOpacity: 0.5,
            fillColor: '#a7c1d0'  // 鼠标移出时恢复填充颜色
          });
        });
        this.map.add(polygon);
      },
      addNoParking(data) {
        let polygon = new AMap.Polygon({
          path: data,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#ff0000',  // 修改边界颜色为红色
          strokeWeight: 2,         // 加粗边界
          strokeStyle: 'solid',
          strokeDasharray: [5, 5],
        });
        polygon.on('mouseover', () => {
          polygon.setOptions({
            fillOpacity: 0.7,
            fillColor: '#ff0000'  // 鼠标悬浮时填充颜色为红色
          });
        });
        polygon.on('mouseout', () => {
          polygon.setOptions({
            fillOpacity: 0.5,
            fillColor: '#cc7b7b'  // 鼠标移出时恢复填充颜色
          });
        });
        this.map.add(polygon);
      },
      addNoriding(data,title,lon,lat) {
        let polygon = new AMap.Polygon({
          path: data,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#ffcc00',  // 修改边界颜色为红色
          strokeWeight: 2,         // 加粗边界
          strokeStyle: 'solid',
          strokeDasharray: [5, 5],
        });
        polygon.on('mouseover', () => {
          polygon.setOptions({
            fillOpacity: 0.7,
            fillColor: '#FFEBA4FF'
          });
        });
        polygon.on('mouseout', () => {
          polygon.setOptions({
            fillOpacity: 0.5,
            fillColor: '#ffeba4'
          });
        });
        this.map.add(polygon);
      }
    },
  };
</script>
<style lang="scss"  scoped>
  #container {
    width: 100%;
    height: 850px;
  }
  .container {
    position: relative;
    border: 1px solid rgb(204, 204, 204);

    .input-card {
      position: absolute;
      bottom: 15px;
      right: 15px;
    }
  }
  .tips{
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 15px;
    left: 15px;
    .tip-item {
      display: flex;
      align-items: center; /* 垂直居中 */
      margin-bottom: 10px; /* 可以根据需要调整间距 */
      color: #38383b;
      .span-class{
        background-color: rgba(255, 255, 255, 0.5);
        padding: 3px 5px;
        border-radius: 5px;
        font-weight: 600;
        font-size: 13px;
      }
    }
    img{
      width: 25px;
      padding-top: 5px;
      height: auto; /* 保持图片高度自适应 */
      margin-right: 10px; /* 图片与文字间距，根据需要调整 */
    }
  }
</style>
<style  lang="scss">
  .apiary-marker{
    position: relative;
    top: -19px;
    left: -19px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .apiary-marker-img{
      width: 25px;
    }
    .apiary-marker-name{
      background-color: #1890ff;
      border: none;
      border-radius: 5px;
      color: white;
      font-size: 12px;
      padding: 5px;
    }
  }
  .detail-btn {
    background: none;
    border: none;
    color: #007bff;
    text-decoration: underline;
    cursor: pointer;
    font-size: 14px;
    padding: 0;
  }

  .detail-btn:hover {
    color: #0056b3;
  }

  .info-table {
    border: 1px solid #ccc;
    border-collapse: collapse;
    width: 100%;
    text-align: center;
    font-size: 14px;
  }

  .info-table th,
  .info-table td {
    border: 1px solid #ccc;
    padding: 8px;
  }

  .info-table th {
    background-color: #f4f4f4;
  }

  .amap-info-content{
    padding: 10px 25px 10px 10px !important;
  }

  .el-dialog:not(.is-fullscreen) {
    margin-top: 6vh !important;
  }

</style>
