import Toast from '@vant/weapp/toast/toast';
var app = getApp();
const wellTypes = [
    {label: '雨水井', value: '1'},
    {label: '污水井', value: '2'},
    {label: '燃气井', value: '3'},
    {label: '热力井', value: '4'},
    {label: '电力井', value: '5'},
    {label: '通信井', value: '6'},
    {label: '给水井', value: '7'},
    {label: '公安井', value: '8'},
    {label: '环卫井', value: '9'},
    {label: '交通井', value: '10'},
    {label: '路灯井', value: '11'},
    {label: '市政井', value: '12'},
    {label: '有线电视井', value: '13'},
    {label: '园林绿化井', value: '14'},
    {label: '其他', value: '15'},
    {label: '消防井', value: '16'},
    {label: '监控井', value: '17'},
]
let wellList = []
Page({
    data: {
      wellTypeList: [
        '雨水井',
        '污水井',
        '燃气井',
        '热力井',
        '电力井',
        '通信井',
        '给水井',
        '公安井',
        '环卫井',
        '交通井',
        '路灯井',
        '市政井',
        '有线电视井',
        '园林绿化井',
        '其他',
        '消防井',
        '监控井'
        ],
      longitude: "116.627340",
      latitude: "39.874390",
      scale: 17,
      minScale: 2,
      maxScale: 22,
      markers: [],
      activeMarkerId: null,
      activeMarker: null,
      activeMarkerWellCode: null,
      showActionSheet: false,
      filterOptions: [
        { name: '查看全部井', type: 'all' },
        { name: '查看全部打不开井', type: 'cannotOpen' },
        { name: '按位置', type: 'location' },
        { name: '按井编号', type: 'wellCode' },
        { name: '按井类型', type: 'wellType' },
        { name: '按井状态', type: 'status' }
      ],
      originalMarkers: [], // 存储原始数据用于筛选
      listQuery: { // 查询井列表的参数
        wellCode: '', // 井编号
        position: '', // 按位置
        wellType: '', // 井类型
        isInStall: '', // 井状态
      },
      position7: {
        left: '46%',
        top: '46%',
    },
      //   -----------------------弹出框--------------------
      showPopup: false,
      popupType: '',
      inputValue: '',
      defaultText: '请输入内容',
      defaultTitieText: '请输入内容',
      showPopupSelect: false, // 井类型选择器
      showLocation: true, // 是否显示定位
    },

    preventDefault(e) {
        // 不执行任何操作，阻止事件冒泡
      },
  
    onLoad() {
      if(!app.globalData.addsuccessWellCode) {
          this.setData({
            listQuery: { // 查询井列表的参数
                wellCode: '', // 井编号
                position: '', // 按位置
                wellType: '', // 井类型
                isInStall: '', // 井状态
              },
          })
        this.fetchManhole(this.data.listQuery);
    }
},
    onShow() {
        if(app.globalData.addsuccessWellCode && wellList.length) {
            const index = wellList.findIndex(item => item.wellCode === app.globalData.addsuccessWellCode)
            if(index !== -1) {
                wellList[index].isInStall = '1'
                this.initManholeData(wellList)
                app.globalData.addsuccessWellCode = ''
                this.setData({
                    activeMarker: null
                })
            }
        }
    },

    // 点击刷新
    refresh() {
        this.fetchManhole(this.data.listQuery, 'refresh');
    },

    // 获取井
    fetchManhole(params, type = '') {
        const that = this
        console.log('请求井列表', params);
        wx.showLoading({
          title: '获取闸井信息中',
          mask: true, // 是否显示透明蒙层，防止触摸穿透
        })
        wx.request({
            method: "POST",
            url: app.globalData.httpsUrl + "appDeviceAdd/getAppWellList",
            data: params,
            header: {
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            success(res) {
                if (res.data.code == 200) {
                    const listResultData = res.data.data;
                    wellList = listResultData
                    if(listResultData.length) {
                        if(type === 'all' || type === 'cannotOpen' || type === 'refresh') { // 查看所有井
                            that.initManholeData(listResultData)
                            if(listResultData.length && type !== 'refresh') {
                                const mapCtx = wx.createMapContext('map');
                                mapCtx.moveToLocation({
                                    latitude: listResultData[0].latGaode,
                                    longitude: listResultData[0].lngGaode
                                });
                            }
                            } else { // 显示周围30米井
                                that.locateCurrentPosition()
                            }
                        // const tempList = that.filterNearbyPoints(listResultData, 39.907900661893, 116.39424858941)
                        // console.log('获取当前人的定位周围30米的数据',tempList.length,  tempList);
                        // that.initManholeData(tempList)
                    } 
                    else {
                        console.log('查询不到数据');
                        wx.hideLoading()
                        // wx.showToast({
                        //         title: "未查询到数据",
                        //         icon: 'none',
                        //         duration: 2000,
                        //         mask: true, // 避免与其他 mask 组件同时显示
                        //     })
                        // }
                        Toast.fail('未查询到数据');
                    }
                }
                wx.hideLoading()
            },
            fail(err) {
                wx.hideLoading()

                wx.showToast({
                    title: "无法获取闸井相关信息！",
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
  
    initManholeData(list) {
        console.log('获取到的闸井信息', list);
        const that = this
        const markers = list.map((manhole, index) => {
            return {
                id: index,
                longitude: manhole.lngGaode,
                latitude: manhole.latGaode,
                iconPath: that.getMarkerIcon(manhole.isInStall, manhole.wellType),
                width: 16,
                height: 16,
                zIndex: 0,
                callout: {
                    content: that.getCalloutContent(manhole),
                    color: '#fff',
                    fontSize: 13,
                    bgColor: '#616161',
                    padding: 10,
                    borderRadius: 6,
                    display: 'BYCLICK',
                    anchorY: -12,
                    borderWidth: 1,
                    borderColor: '#616161',
                    textAlign: 'left',
                },
                manholeInfo: manhole
            };
      });
      that.setData({
        originalMarkers: markers,
        markers: markers
      });
      wx.hideLoading()
    },
  
    getMarkerIcon(status, wellType) {
        // 地图上  橙红色：井打不开2，黄色 ：已安装，蓝色1：未安装0
      if((wellType === '燃气井' || wellType === '雨水井' || wellType === '污水井') && status !== '3' && status !== '4' && status !== '5') {
        return '/images/gray-marker.png'
      } else if((wellType === '燃气井' || wellType === '雨水井' || wellType === '污水井') && (status === '3' || status === '4' || status === '5')) {
        return '/images/purple-marker.png'
      }
      else{
        switch(status) {
            case '0': return '/images/blue-marker.png';
            case '1': return '/images/yellow-marker.png';
            case '2': return '/images/orange-marker.png';
            default: return '/images/default-marker.png';
          }
      }
    },
  
    getCalloutContent(manhole) {
    //   return `闸井编号: ${manhole.wellCode}\n闸井类型: ${manhole.wellType}\n闸井状态: ${this.getStatusText(manhole.isInStall)}\n位置: ${manhole.coordinateX},${manhole.coordinateY}\n详细地址: ${manhole.position}`;
    //   return `闸井编号: ${manhole.wellCode}\n闸井类型: ${manhole.wellType}\n闸井状态: ${this.getStatusText(manhole.isInStall)}\n详细地址: ${manhole.position}`;
      return `${this.getStatusText(manhole.isInStall)}  ${manhole.wellCode}   ${manhole.wellType}`;
    },
  
    getStatusText(status) {
    //   switch(status) {
    //     case '0': return '未安装';
    //     case '1': return '已安装';
    //     case '2': return '井打不开';
    //     default: return '未知';
    //   }
      switch(status) {
        case '0': return '未 ';
        case '1': return '已 ';
        case '2': return '井打不开 ';
        default: return '未知 ';
      }
    },
    // 按钮点击事件处理方法
    createDevice() {
       console.log('气泡里面的按钮被点击');
       // 在这里可以添加按钮点击后的具体逻辑
    },
    // 点击井打不开
    notopen() {
        var that = this
        wx.showModal({
            content: '确定井打不开吗？',
            success: function (res) {
              if (res.confirm) {
                if(wellList.length) {
                    console.log('000000000000', that.data.activeMarkerWellCode);
                    const index = wellList.findIndex(item => item.wellCode === that.data.activeMarkerWellCode)
                    if(index !== -1) {
                        wellList[index].isInStall = '2'
                        that.initManholeData(wellList)
                    }
                }
                wx.request({
                    method: "post",
                    url: app.globalData.httpsUrl + "appDeviceAdd/changeWellState",
                    data: {
                        wellCode: that.data.activeMarker.manholeInfo.wellCode,
                        isInStall: '2'
                    },
                    header: {
                    'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
                    },
                    success(res) {
                    },
                    fail(err) {
                        wx.showToast({
                            title: "修改井打不开状态失败",
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
              } else { //这里是点击了取消以后 
                console.log('用户点击取消')
              }
            }
          })
    },
     //   编辑雨-污-燃井
     updateWellType() {
        var that = this
        wx.showActionSheet({
            itemList: ['雨水井', '污水井', '燃气井'],
            success: (res) => {
            if (!res.cancel) {
                const types = [{label: '雨水井', value: '3'}, {label: '污水井', value: '4'}, {label: '燃气井', value: '5'}];
                const paramstypes = types[res.tapIndex].value
                const paramstitle = types[res.tapIndex].label
                wx.showModal({
                    content: `确定修改为${paramstitle}吗？`,
                    success: function (res) {
                      if (res.confirm) {
                        if(wellList.length) {
                            const index = wellList.findIndex(item => item.wellCode === that.data.activeMarkerWellCode)
                            if(index !== -1) {
                                wellList[index].isInStall = paramstypes
                                wellList[index].wellType = paramstitle
                                that.initManholeData(wellList)
                            }
                        }
                        wx.request({
                            method: "post",
                            url: app.globalData.httpsUrl + "/appDeviceAdd/markerWell",
                            data: {
                                wellCode: that.data.activeMarker.manholeInfo.wellCode,
                                isInStall: paramstypes
                            },
                            header: {
                            'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
                            },
                            success(res) {
                            },
                            fail(err) {
                                wx.showToast({
                                    title: "修改井类型失败",
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        })
                      } else { //这里是点击了取消以后 
                        console.log('用户点击取消')
                      }
                    }
                  })
                } 
            }
        });
    },

    // 显隐定位
    clickShowLocation() {
        var that = this
        const showLocation = !that.data.showLocation;
        that.setData({
            showLocation
        });
    },
    // 点击标记点
    onMarkerTap(e) {
    // =========================================================
      const markerId = e.markerId;
      console.log('Marker tapped:', markerId);
      //   先隐藏所有气泡
      const markers = this.data.markers.map(marker => {
        marker.callout.display = 'BYCLICK';
        // marker.zIndex = 0
        return marker;
      });
      
    //   找到被点击的marker并显示其气泡
      const index = markers.findIndex(marker => marker.id === markerId);
      if (index !== -1) {
        this.setData({
            activeMarker: markers[index],
        });
      console.log('点击marker', markers[index]);
        
        markers[index].callout.display = 'ALWAYS';
        markers[index].zIndex = 100;
        this.setData({
          markers: markers,
          activeMarkerId: markerId,
          activeMarkerWellCode: markers[index].manholeInfo.wellCode
        });
      }
    // =========================================================
    },
  
    zoomIn() {
      if (this.data.scale < this.data.maxScale) {
        this.setData({
          scale: this.data.scale + 1
        });
      }
    },
  
    zoomOut() {
      if (this.data.scale > this.data.minScale) {
        this.setData({
          scale: this.data.scale - 1
        });
      }
    },

    // ----------------------------------------------筛选---------------------------------------------
    showFilterPicker() {
        this.setData({
          showActionSheet: true
        });
      },

    //   关闭选择器
      hideActionSheet() {
        this.setData({
          showActionSheet: false
        });
      },
    
      onFilterSelect(e) {
        console.log('点击选择器', e);
        const { type } = e.currentTarget.dataset;
        this.setData({popupType: type });
        this.handleFilter(type);
        this.hideActionSheet();
      },
    
      handleFilter(type) {
        const that = this
        console.log('筛选类型：popupType', that.data.popupType);
        switch(type) {
          case 'all': // 查看所有井
            // that.setData({ markers: that.data.originalMarkers });
            that.setData({
                listQuery: { // 查询井列表的参数
                    wellCode: '', // 井编号
                    position: '', // 按位置
                    wellType: '', // 井类型
                    isInStall: '', // 井状态
                  },
              })
            that.fetchManhole(this.data.listQuery, type);
            break;
        case 'cannotOpen': // 查看全部打不开井
            // that.setData({ markers: that.data.originalMarkers });
            that.setData({
                listQuery: { // 查询井列表的参数
                    wellCode: '', // 井编号
                    position: '', // 按位置
                    wellType: '', // 井类型
                    isInStall: '2', // 井状态
                  },
              }, type)
            that.fetchManhole(this.data.listQuery, type);
            break;
          case 'location': // 按位置筛选
            that.setData({defaultTitieText: '请输入位置',  defaultText: '请输入位置', showPopup: true });
            break;
          case 'wellCode': // 按照井编号筛选
            that.setData({defaultTitieText: '请输入井编号',  defaultText: '请输入井编号', showPopup: true });
            break;
          case 'wellType': // 按井类型
            that.showPopupSelect()
            break;
          case 'status':
            wx.showActionSheet({
                itemList: ['井打不开', '已安装', '未安装'],
                success: (res) => {
                if (!res.cancel) {
                    const types = [{label: '井打不开', value: '2'}, {label: '已安装', value: '1'}, {label: '未安装', value: '0'}];
                    // 前端做筛选
                    //   const filtered = that.data.originalMarkers.filter(
                //     marker => marker.manholeInfo.isInStall === types[res.tapIndex].value
                //   );
                //   console.log('======filtered======', filtered);
                //   that.setData({ markers: filtered });
                    // 由于井的状态在实时变化，因此请求接口
                    that.setData({
                        listQuery: { // 查询井列表的参数
                            wellCode: '', // 井编号
                            position: '', // 按位置
                            wellType: '', // 井类型
                            isInStall: types[res.tapIndex].value, // 井状态
                          },
                      }, type)
                    that.fetchManhole(this.data.listQuery);
                }
                }
            });
            break;
        }
      },

    //   --------------------------------popup相关方法--------------------------------------------
    // 打开popup
    showPopup() {
        this.setData({ showPopup: true });
    },
    // 关闭popup
    onClose() {
        this.setData({ showPopup: false });
    },
    // 输入内容
    onInput(e) {
        this.setData({ inputValue: e.detail });
    },
    // 点击确认按钮
    onConfirm() {
        let params
        console.log('确认按钮点击', this.data.inputValue);
        console.log('当前筛选的类型', this.data.popupType);
        if(this.data.popupType === 'location') {
            params = {
                wellCode: '', // 井编号
                position: this.data.inputValue, // 按位置
                wellType: '', // 井类型
                isInStall: '', // 井状态
            }
        } else if(this.data.popupType === 'wellCode') {
            params = {
                wellCode: this.data.inputValue, // 井编号
                position: '', // 按位置
                wellType: '', // 井类型
                isInStall: '', // 井状态
            }
        }
        this.onClose()
        this.setData({
            listQuery: params
        })
        this.fetchManhole(params)
    },
    // 点击取消按钮
    onCancel() {
        console.log('取消按钮点击');
        this.setData({ showPopup: false });
    },

    // --------------------------------------------筛选井类型相关方法----------------------------------
    // 打开popup
    showPopupSelect() {
        this.setData({ showPopupSelect: true });
    },
    // 关闭popup
    onCloseSelect() {
        this.setData({ showPopupSelect: false });
    },
    // 输入内容
    onInput(e) {
        this.setData({ inputValue: e.detail });
    },
    // 点击确认按钮
    confirmSelectWellType: function (e) {
        console.log('确认选择井类型', e);
        const params = {
            wellCode: '', // 井编号
            position: '', // 按位置
            wellType: e.detail.index + 1 + '', // 井类型
            isInStall: '', // 井状态
        }
        this.onCloseSelect()
        this.setData({
            listQuery: params
        })
        this.fetchManhole(params)
    },
    // 点击确认按钮
    // onConfirmSelect() {
    //     console.log('确认按钮点击', this.data.inputValue);
    //     this.setData({ showPopupSelect: false });
    //     if(this.data.popupType === 'location') {
    //         const params = {
    //             wellCode: this.data.inputValue, // 井编号
    //             position: this.data.inputValue, // 按位置
    //             wellType: this.data.inputValue, // 井类型
    //             isInStall: this.data.inputValue, // 井状态
    //         }
    //         this.setData({
    //             listQuery: params
    //         })
    //         this.fetchManhole(params)
    //     }
    // },
    // 点击取消按钮
    onCancelSelect() {
        console.log('取消按钮点击');
        this.setData({ showPopupSelect: false });
    },

    // --------------------------------------------新建设备----------------------------------
    createDevice() {
        console.log('当前选中的设备', this.data.activeMarker);
        wx.navigateTo({
            url: `../addDevice/addDevice?fromPage=defineMap&latitude=${this.data.activeMarker.latitude}&longitude=${this.data.activeMarker.longitude}&position=${this.data.activeMarker.manholeInfo.position}&wellCode=${this.data.activeMarker.manholeInfo.wellCode}&wellType=${this.data.activeMarker.manholeInfo.wellType}`
        })
    },
    // ----------------------------------------------------------------------------------

    /**
     * 筛选用户当前位置周围指定距离内的点位数据
     * @param {Array} points - 点位数组（每条数据需包含 latGaode 和 lngGaode 字段）
     * @param {number} userLat - 用户当前纬度
     * @param {number} userLng - 用户当前经度
     * @param {number} radius - 筛选半径（单位：米，默认 30 米）
     * @returns {Array} 符合条件的点位数组
     */
    filterNearbyPoints(points, userLat, userLng, radius = 30) {
        if (!points || !points.length || !userLat || !userLng) {
        return []; // 校验参数合法性
        }
  
        return points.filter(point => {
        // 调用距离计算函数
        const distance = this.calculateDistance(userLat, userLng, point.latGaode, point.lngGaode);
        return distance <= radius; // 保留距离≤半径的点位
        });
    },
  
    /**
     * 计算两点间球面距离（Haversine 公式）
     * @param {number} lat1 - 点1纬度
     * @param {number} lng1 - 点1经度
     * @param {number} lat2 - 点2纬度
     * @param {number} lng2 - 点2经度
     * @returns {number} 两点间距离（单位：米）
     */
    calculateDistance(lat1, lng1, lat2, lng2) {
        const R = 6371e3; // 地球半径（米）
        const dLat = (lat2 - lat1) * Math.PI / 180; // 纬度差（弧度）
        const dLng = (lng2 - lng1) * Math.PI / 180; // 经度差（弧度）
        
        // Haversine 公式计算中间变量
        const a = 
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2);
        
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); // 计算圆心角（弧度）
        return R * c; // 返回距离（米）
    },

    // 点击定位
    locateCurrentPosition() {
        var that = this;
        that.setData({
            markers: []
        })
        //获取当前坐标（gcj02）
        wx.showLoading({
            title: '正在定位',
            mask: true, // 是否显示透明蒙层，防止触摸穿透
        })
        wx.getLocation({
          type: "gcj02",
          altitude: true,
          success: function (res) {
            that.setData({
              latitude: parseFloat(res.latitude).toFixed(6),
              longitude: parseFloat(res.longitude).toFixed(6),
            //    latitude: '39.908599446615',
            //   longitude: '116.391914605035',
            })
            console.log('获取到当前定位', parseFloat(res.latitude), parseFloat(res.longitude));
            // 将地图中心移动到当前定位点
            const mapCtx = wx.createMapContext('map');
            mapCtx.moveToLocation();
            wx.hideLoading()
            if(wellList.length) {
                // const tempList = that.filterNearbyPoints(wellList, '39.908599446615', '116.391914605035')
                const tempList = that.filterNearbyPoints(wellList, parseFloat(res.latitude), parseFloat(res.longitude))
                console.log('获取当前人的定位周围30米的数据',tempList.length,  tempList);
                if(tempList.length) {
                    that.initManholeData(tempList)
                    mapCtx.moveToLocation({
                        latitude: tempList[0].latGaode,
                        longitude: tempList[0].lngGaode,
                    });
                    that.setData({
                        scale: 17
                    });
                } else {
                    wx.showToast({
                        title: "当前位置周围30米无闸井",
                        icon: 'none',
                        duration: 3000
                    })
                }
            } else {
                that.fetchManhole()
            }
          },
          fail(err) {
            wx.hideLoading()
            wx.showToast({
                title: "未获取到当前定位！",
                icon: 'none',
                duration: 2000
            })
        }
        })
    }
})
      