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'},
]
Page({
    data: {
    wellTypeList: [
        '雨水井',
        '污水井',
        '燃气井',
        '热力井',
        '电力井',
        '通信井',
        '给水井',
        '公安井',
        '环卫井',
        '交通井',
        '路灯井',
        '市政井',
        '有线电视井',
        '园林绿化井',
        '其他',
        '消防井',
        '监控井'
        ],
      longitude: 116.397228,
      latitude: 39.907501,
      scale: 14,
      minScale: 2,
      maxScale: 22,
      markers: [],
      activeMarkerId: null,
      activeMarker: null,
      showActionSheet: false,
      filterOptions: [
        { name: '查看所有', type: 'all' },
        { name: '按位置', type: 'location' },
        { name: '按井编号', type: 'wellCode' },
        { name: '按井类型', type: 'wellType' },
        { name: '按井状态', type: 'status' }
      ],
      originalMarkers: [], // 存储原始数据用于筛选
      listQuery: { // 查询井列表的参数
        wellCode: '', // 井编号
        position: '', // 按位置
        wellType: '', // 井类型
        isInStall: '', // 井状态
      },
      wellList: [], // 井列表
      //   -----------------------弹出框--------------------
      showPopup: false,
      popupType: '',
      inputValue: '',
      defaultText: '请输入内容',
      defaultTitieText: '请输入内容',
      showPopupSelect: false, // 井类型选择器
    },
  
    onLoad() {
      this.fetchManhole({ // 查询井列表的参数
        wellCode: '', // 井编号
        position: '', // 按位置
        wellType: '', // 井类型
        isInStall: '0', // 井状态
      });
    },

    // 获取井
    fetchManhole(params) {
        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;
                    that.setData({
                        wellList: res.data.data,
                    })
                    that.initManholeData(listResultData)
                }
            },
            fail(err) {
                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),
                width: 30,
                height: 30,
                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) {
        // 地图上  橙红色：井打不开2，黄色 ：已安装，蓝色1：未安装0
      console.log('获取到的icon类型', status); 
      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}`;
    },
  
    getStatusText(status) {
      switch(status) {
        case '0': return '未安装';
        case '1': return '已安装';
        case '2': return '井打不开';
        default: return '未知';
      }
    },
    // 按钮点击事件处理方法
    createDevice() {
       console.log('气泡里面的按钮被点击');
       // 在这里可以添加按钮点击后的具体逻辑
    },
    // 点击标记点
    onMarkerTap(e) {
    // =========================================================
      console.log('点击marker', 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],
        });
        
        markers[index].callout.display = 'ALWAYS';
        markers[index].zIndex = 100;
        this.setData({
          markers: markers,
          activeMarkerId: markerId
        });
      }
    // =========================================================
    },
  
    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 });
            this.fetchManhole({
                wellCode: '', // 井编号
                position: '', // 按位置
                wellType: '', // 井类型
            })
            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.fetchManhole({ // 查询井列表的参数
                        wellCode: '', // 井编号
                        position: '', // 按位置
                        wellType: '', // 井类型
                        isInStall: types[res.tapIndex].value, // 井状态
                    })
                }
                }
            });
            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.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.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.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}`
        })
    }
})
      