//index.js
//获取应用实例
let app = getApp();
let wechat = require("../../utils/wechat");
let amap = require("../../utils/amap");
let Util = require("../../utils/util");
let log = require('../../utils/log.js');
let wxpro = require('../../utils/wx-promise-pro.js');
let mapregionchange_makertap = false;


wxpro.promisifyAll()
// wxpro.promisify(wx.getSystemInfo)().then(console.log)
for (var variable in wx) {
  if (wx.hasOwnProperty(variable)) {
    wx.pro[variable] = wxpro.promisify(wx[variable])
  }
}


Page({
  data: {
    scanFlag:false,
    markers: [],
    latitude: 39.9088120620532,
    longitude: 116.39747668717192,
    user_lat: 39.9088120620532,
    user_lon: 116.39747668717192,
    textData: null,
    city: null,
    markerId: null,
    keywords: "搜索充电桩",
    userInfo: {},
    isLogin: false,
    myChargeStationsIds: '',
    distanceinfo: [
      // {
      //   value: 1000,
      //   text: '1km'
      // }, {
      //   value: 2000,
      //   text: '2km'
      // }, {
      //   value: 5000,
      //   text: '5km'
      // }, 
      {
        value: 10000,
        text: '10km'
      },
      // {
      //   value: 20000,
      //   text: '20km'
      // }, 
      {
        value: 50000,
        text: '50km'
      }, {
        value: 100000,
        text: '100km'
      }],
    distanceinfoindex: 0,
    polygon: [{
      points: [{
        latitude: 31,
        longitude: 131
      }, {
        latitude: 31,
        longitude: 131.1
      }, {
        latitude: 31.1,
        longitude: 131.1
      }, , {
        latitude: 31.1,
        longitude: 131
      }]
      
    }],
    showModal: false,
    notice: null,
    carParkingRate: false,
    showPrivacy:false,
    occupyFeeOrderList:[]
  },
  howtouse(){
    wx.navigateTo({
      url:'/pages/howtouse/howtouse'
    });
  },
  wxScan(q) {
    //console.log(decodeURIComponent(e.q));
    let charePileId = decodeURIComponent(q).replace("https://cdgl.pjnes.com/", "");
    log.info('[首页]', '[微信扫一扫]', { 'q': q });
    if(!charePileId){
      charePileId = "0"
    }
    if (charePileId) {
      let userInfo = wx.getStorageSync('userInfo');
      let isLogin = wx.getStorageSync('isLogin');

      if (isLogin && userInfo.flag) {
        return;
      }
      if (!isLogin) {
        log.info('[首页]', '[未登陆跳转登录界面]');
        let url = `/pages/login/phone_login/phone_login`;
        wx.navigateTo({
          url
        });
        return;
      } else {

        log.info('[首页]', '[获取用户是否有未完成订单]', '[请求]', { userId: userInfo.userId });
        wx.request({
          url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatchargstatus',
          data: {
            userId: userInfo.userId
          },
          method: 'POST',
          success(res) {
            let {
              data
            } = res;
            log.info('[首页]', '[获取用户是否有未完成订单]', '[响应]', data);
            if (data && data.code == 200) {
              log.info('[首页]', '[有未完成订单跳充电界面]');
              //onShow会跳转
            } else {
              //console.log('无订单');
              log.info('[首页]', '[用户无未完成订单]');
              log.info('[首页]', '[获取微信扫一扫充电桩]', '[请求]', charePileId);
              wx.request({
                url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
                // data: charePileId,
                data:{
                  chargPileId:charePileId,
                  userId: userInfo.userId
                },
                method: 'POST',
                success(res) {
                  //console.log(res.data);
                  log.info('[首页]', '[获取微信扫一扫充电桩]', '[响应]', res.data);
                  if (!res.data || res.data.code == 500) {
                    //没有该充电桩信息
                    wx.showModal({
                      showCancel: false,
                      content: res && res.data && res.data.msg ? res.data.msg :'无效的终端编号',
                      confirmColor:'#00AADD',
                    });
                  } else {
                    res.data = res.data.result
                    //充电状态0：离线、1：故障、2：空闲中、3：充电中、4：欠压故障、5：过压故障、6：过电流故障、8：预约、9：在线升级、10：操作中、11:已插枪等
                    if (!res.data.chargstatus || res.data.chargstatus == 0 || res.data.chargstatus == 1 || res.data.chargstatus == 4 || res.data.chargstatus == 5 || res.data.chargstatus == 6 || res.data.chargstatus == 9) {
                      //充电桩故障

                      wx.showModal({
                        showCancel: false,
                        content: '终端故障，维修中',
                        confirmColor:'#00AADD',
                      });
                    } else if (res.data.chargstatus == 3 || res.data.chargstatus == 8 || res.data.chargstatus == 10) {
                      wx.showModal({
                        showCancel: false,
                        content: '正在充电中',
                        confirmColor:'#00AADD',
                      });
                    } else if (res.data.chargstatus == 2 || res.data.chargstatus == 11) {
                      wx.setStorage({
                        key: "scan_chargpile",
                        data: res.data
                      });
                      log.info('[首页]', '[微信扫一扫充电桩空闲跳转去充电界面]');
                      let url = `/pages/scan_result/scan_result`;
                      wx.navigateTo({
                        url
                      });
                    }
                  }
                },
                fail(e) {
                  getApp().showNetworkError();
                }
              });
            }
          },
          fail(e) {
            getApp().showNetworkError();
          }
        });
      }
    }
  },
  resetchargStations(data){
    let that = this
    // 刷新 stationTag)

    
    for(let i=0;i<data.length;i++){
      let seeInfoChargPile = data[i];
      that.resetStationTag(seeInfoChargPile);
      let resultTable = seeInfoChargPile.resultList
      that.resetResultList(resultTable);
      that.resetResultData(resultTable,seeInfoChargPile)
      
    }
  },
  resetResultData(resultList,data){
    if(!resultList){
      return;
    }
    for(let i=0;i<resultList.length;i++){
      if(resultList[i].currentTime){
        if(resultList[i].elecPrice == '暂无费用'){
          data.chargprice = '暂无费用'
        }else{
          const elecPrice = parseFloat(resultList[i].elecPrice); // 将字符串转换为数字
          data.chargprice = elecPrice.toFixed(8).replace(/\.?0+$/, ""); // 格式化为8位小数
        }
        data.serviceprice = resultList[i].servicePrice
      }
    }
  },
  resetStationTag(seeInfoChargPile){
    let that = this
    if(!seeInfoChargPile){
      return;
    }
    if(!seeInfoChargPile?.stationTag){
        return;
    }
    seeInfoChargPile.stationTagList = seeInfoChargPile.stationTag.split("|");
  },
  resetResultList(resultList){
    let that = this
    if(!resultList){
      return;
    }
    resultList.forEach(item=>{
      item["sumPrice"] = that.resetResultListSumPrice(item);
      if(!item.elecPrice && item.elecPrice!=0){
        item["elecPrice"] = '暂无费用'
      }
      if(!item.servicePrice && item.servicePrice!=0){
        item["servicePrice"] = '暂无费用'
      }
    })
  },
  resetResultListSumPrice(item){
 
    if(!item.elecPrice && item.elecPrice!=0){
      return '暂无费用'
    }
    if(!item.servicePrice && item.servicePrice!=0){
      return '暂无费用'
    }
    return parseFloat((item.elecPrice + item.servicePrice).toFixed(6))
  },

  onLoad(e) {
    // 隐私开始
    wx.getPrivacySetting({
        success: res => {
          console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showPrivacy: true
            })
          } else {
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
            // wx.getUserProfile()
            // wx.chooseMedia()
            // wx.getClipboardData()
            // wx.startRecord()
          }
        },
        fail: () => {},
        complete: () => {}
      })
  


    // 隐私结束


   this.data.scanFlag = false;
    wx.hideLoading();
    if (e.q) {
      //console.log(decodeURIComponent(e.q));
      //let charePileId = decodeURIComponent(e.q).replace("https://cdgl.pjnes.com/", "");
      //console.log(charePileId);
      //if (charePileId){

      //}

      let userInfo = wx.getStorageSync('userInfo');
      let isLogin = wx.getStorageSync('isLogin');
      // userInfo.flag=true;
      this.setData({
        userInfo,
        isLogin
      });


      this.click_scan_control(e.q,false);
      // this.wxScan(e.q);
    }
    log.info('[首页]', '[加载完成]');

    amap.getRegeo(function () {
      var fail = function (obj) {
        wx.showModal({
          title: '请求失败',
          content: obj.errMsg,
          confirmColor:'#00AADD',
        });
      }
    })
      .then(d => {
        //console.log(d);
        let {
          latitude,
          longitude,
          latitude: user_lat,
          longitude: user_lon
        } = d[0];
        //console.log(d[0].regeocodeData.addressComponent);
        var {
          city
        } = d[0].regeocodeData.addressComponent;
        if (d[0].regeocodeData.addressComponent.city.length == 0) {
          var {
            province: city
          } = d[0].regeocodeData.addressComponent;
        }

        let that = this;
        let userInfo = wx.getStorageSync('userInfo');
        let isLogin = wx.getStorageSync('isLogin');
        // userInfo.flag=true;
        this.setData({
          city,
          latitude,
          longitude,
          user_lat,
          user_lon,
          userInfo,
          isLogin
        });

        //开始请求充电站信息
        var chargStationType;
        if (!userInfo.flag) {
          //用户是普通用户
          chargStationType = '2';
        }
        wx.request({
          url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargStations',
          data: {
            lon: longitude,
            lat: latitude,
            distance: that.data.distanceinfo[that.data.distanceinfoindex].value,
            chargStationType
          },
          method: 'POST',
          success(res) {
            //userInfo.flag = true;
            that.resetchargStations(res.data)

            if (isLogin && userInfo.flag) {
              wx.request({
                url: getApp().globalData.postHeadAgreement + '/restapi/wechat/userChargStations',
                data: {
                  userId: userInfo.userId,
                  lat: latitude,
                  lon: longitude
                },
                method: 'POST',
                success(res1) {

                  var myChargeStationsIds = '';
                  res1.data.forEach((item, index) => {
                    myChargeStationsIds += item.id + ",";
                  });
                  //console.log(myChargeStationsIds);
                  let {
                    data
                  } = res;
                  let markers = [];
                  data.forEach((item, index) => {
                    //item.callout = {
                    // content: item.name, //文本	String	1.2.0
                    //  display: 'BYCLICK', //'BYCLICK': 点击显示; 'ALWAYS': 常显	String	1.2.0
                    // textAlign: 'center' //文本对齐方式。有效值: left, right, center	String	1.6.0
                    // };
                    var iconPath = "/images/marker.png";
                    if (myChargeStationsIds.indexOf(item.id + ',') != -1) {
                      iconPath = "/images/marker1.png";
                    }
                    if (item.breaknum && item.breaknum != 0) {
                      iconPath = "/images/marker_b.png";
                    }
                    /**
                     * 运营状态 初始，待运营，运营中，暂停营业，关闭，未运营
                     * */
                    //private Long operationState;
                    var marker = {
                      name: item.chargStationName,
                      address: item.address,
                      width: "46rpx",
                      height: "67rpx",
                      chargfeatures: item.chargfeatures , 
                      iconPath: iconPath,
                      id: item.id,
                      callout: {},
                      latitude: item.lat,
                      longitude: item.lon,
                      //distance: item.distance / 1000,
                      distance: Util.distance(that.data.user_lat, that.data.user_lon, item.lat, item.lon),
                      chargPileNum: item.fastCharg + item.slowCharg,
                      fastCharg: item.fastCharg,
                      slowCharg: item.slowCharg,
                      freenum: item.freenum,
                      fastfreenum: item.fastfreenum,
                      slowfreenum: item.slowfreenum,
                      breaknum: item.breaknum,
                      /** 电费 */
                      chargprice: item.chargprice,
                      /** 服务费 */
                      serviceprice: item.serviceprice,
                      /** 停车费 */
                      stopprice: item.stopprice,
                      operationState: item.operationState,
                      chargStationId: item.id,
                      stationTag: item.stationTag,
                      stationTagList: item.stationTagList,
                      offlineServicecall: item.offlineServicecall,
                    };
                    markers[index] = marker;
                  });
                  that.setData({
                    markers,
                    myChargeStationsIds
                  });
                },
                fail(e) {
                  getApp().showNetworkError();
                }
              });
            } else {
              let {
                data
              } = res;
              let markers = [];
              if(data){
              data.forEach((item, index) => {
                //item.callout = {
                // content: item.name, //文本	String	1.2.0
                //  display: 'BYCLICK', //'BYCLICK': 点击显示; 'ALWAYS': 常显	String	1.2.0
                // textAlign: 'center' //文本对齐方式。有效值: left, right, center	String	1.6.0
                // };
                var iconPath = "/images/marker.png";
                //撤销普通用户显示异常站
                //if (item.breaknum && item.breaknum != 0) {
                //  iconPath = "/images/marker_b.png";
                //}
                //撤销结束
                var marker = {
                  name: item.chargStationName,
                  address: item.address,
                  width: "46rpx",
                  height: "67rpx",
                  chargfeatures: item.chargfeatures , 
                  iconPath: iconPath,
                  id: item.id,
                  callout: {},
                  latitude: item.lat,
                  longitude: item.lon,
                  //distance: item.distance / 1000,
                  distance: Util.distance(that.data.user_lat, that.data.user_lon, item.lat, item.lon),
                  chargPileNum: item.fastCharg + item.slowCharg,
                  fastCharg: item.fastCharg,
                  slowCharg: item.slowCharg,
                  freenum: item.freenum,
                  fastfreenum: item.fastfreenum,
                  slowfreenum: item.slowfreenum,
                  breaknum: item.breaknum,
                  /** 电费 */
                  chargprice: item.chargprice,
                  /** 服务费 */
                  serviceprice: item.serviceprice,
                  /** 停车费 */
                  stopprice: item.stopprice,
                  operationState: item.operationState,
                  sharpChargPrice : item.sharpChargPrice,
                  sharpServicePrice : item.sharpServicePrice,
                  peakChargPrice : item.peakChargPrice,
                  peakServicePrice : item.peakServicePrice,
                  flatChargPrice : item.flatChargPrice,
                  flatServicePrice : item.flatServicePrice,
                  valleyChargPrice : item.valleyChargPrice,
                  valleyServicePrice : item.valleyServicePrice,
                  resultList: item.resultList,
                  chargStationId: item.id,
                  stationTag: item.stationTag,
                  stationTagList: item.stationTagList,
                  offlineServicecall: item.offlineServicecall,
                };
                markers[index] = marker;

              });
            }
              that.setData({
                markers
              });
            }
          },
          fail(e) {
            getApp().showNetworkError();
          }
        });
      })
      .catch(e => {
        console.log(e);
      });
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    //console.log(userInfo);
    if (isLogin) {
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/wechat/lastNotice',
        data: { loginName: userInfo.loginName },
        method: 'POST',
        success(res) {
          //console.log(res);
          //res.data = { noticeTitle: '派捷充电例行维护通知', noticeContent:'nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好nihao你好'};
          if (res.data) {
            that.setData({
              showModal: true,
              notice: res.data
            });
          } else {
            that.setData({
              showModal: false,
              notice: null
            });
          }
        },
        fail(e) {
          //console.log(e);
          that.setData({
            showModal: false,
            notice: null
          });
          getApp().showNetworkError();
        }
      });
    }
    // 占位费查询
    // that.loadOccupyOrder()

  },
  loadOccupyOrder(){
    let that = this;
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/queryOccupyFeeOrder',
      data: {
        userId: wx.getStorageSync('userInfo').userId,
        searchIndex: 2,
        pagenum: this.data.pagenum++,
        pagesize: 10,
      },
      method: 'POST',
      success(res) {
        console.log("占位费",res);
        if (res.data.result.rows) {
          let {
            rows: occupyFeeOrderList
          } = res.data.result;
          // that.startTimeOrder(charginglogs);
          // that.formatCharginglogs(occupyFeeOrderList);
          // wx.hideLoading()
          that.setData({
            occupyFeeOrderList: that.data.occupyFeeOrderList.concat(occupyFeeOrderList),
            // total: res.data.result.total,
            // dataLoading: false
          });
        }
      }
    });
  },
  //跳转个人中心
  bindUserAvatarUrl() {
    let url = `/pages/ucenter/index/index`;
    wx.navigateTo({
      url
    });
  },
  //搜索
  bindInput() {
    var {
      user_lat: latitude,
      user_lon: longitude,
      city
    } = this.data;
    //console.log(this.data.city);
    let url = `/pages/inputtip/inputtip?city=${city}&lonlat=${longitude},${latitude}`;
    wx.navigateTo({
      url
    });
  },
  //单击地图mark
  makertap(e) {
    mapregionchange_makertap = true;
    //console.log(e);
    let {
      markerId
    } = e.detail;
    // console.log({
    //   e
    // });
    let {
      markers
    } = this.data;
    //撤销普通用户显示异常站
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let showBadMark = false;
    if (isLogin && userInfo.flag) {
      showBadMark = true;
    }
    //撤销结束
    markers.forEach((item, index) => {
      item.iconPath = "/images/marker.png";
      if (this.data.myChargeStationsIds.indexOf(item.id + ',') != -1) {
        item.iconPath = "/images/marker1.png";
      }
      //撤销普通用户显示异常站
      if (showBadMark) {
        //撤销结束
        if (item.breaknum && item.breaknum != 0) {
          item.iconPath = "/images/marker_b.png";
        }
        //撤销普通用户显示异常站
      }
      //撤销结束
      if (item.id == markerId) {
        item.iconPath = "/images/marker_checked.png";
        this.showMarkerInfo(item);
      }
    });
    this.setData({
      markers,
      markerId
    });
  },
  //将mark呈现在地图中心点，并弹出详细信息框
  showMarkerInfo(data) {
    let that = this
    let {
      latitude,
      longitude
    } = data;
    this.setData({
      textData: data,
      latitude: latitude,
      longitude: longitude
    })
    console.info(data)
    // 查询是否需要显示
    that.execParking(that,data.id)
  },
  execParking(that,stationId){
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/carParkingRate?stationId=' + stationId,
      // data: {
      // loginName: userInfo.loginName
      // },
      method: 'POST',
      success: function (res) {
        // 是否减免停车费
        // carParkingRate: false,
        // parkTime: 0,
        console.info(res)
        let reduceTime = res.data?.reduceTime;
        if(!reduceTime){
          that.setData({
            carParkingRate:false
          })
          return;
        }
        that.setData({
          carParkingRate:true
        })
        try{
          that.setData({
            parkTime: parseFloat((reduceTime/ 3600).toFixed(2))
          })
        }catch(e){
          that.setData({
            carParkingRate:false
          })
        }

      },
      fail(e) {
      console.log("用户数据同步失败");
      log.info('[扫码]', '[同步用户数据]', '[fail]', e);
      }
    });

  },
  //改变选中mark的颜色
  changeMarkerColor(markerId) {
    let {
      markers
    } = this.data;
    //撤销普通用户显示异常站
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let showBadMark = false;
    if (isLogin && userInfo.flag) {
      showBadMark = true;
    }
    //撤销结束
    markers.forEach((item, index) => {
      item.iconPath = "/images/marker.png";
      if (this.data.myChargeStationsIds.indexOf(item.id + ',') != -1) {
        item.iconPath = "/images/marker1.png";
      }
      //撤销普通用户显示异常站
      if (showBadMark) {
        //撤销结束
        if (item.breaknum && item.breaknum != 0) {
          item.iconPath = "/images/marker_b.png";
        }
        //撤销普通用户显示异常站
      }
      //撤销结束
      if (item.id == markerId) {
        item.iconPath = "/images/marker_checked.png";
      }
    })
    this.setData({
      markers,
      markerId
    });
  },
  seeInfo(e){
    console.log("11111");
    // 起点
    let {
      user_lat: latitude,
      user_lon: longitude,
      markers,
      markerId,
      city,
      textData
    } = this.data;
    let {
      name,
      address,
      chargprice,
      serviceprice,
      brandName
    } = textData;

    console.log("222222");
    console.log(markers);
    if (!markers.length) return;
    console.log("3333333");
    // 终点
    markers.forEach((item, index) => {
      if (markerId && markerId == item.id) {
        let that = this
        item.resultList.forEach(item=>{
          item["sumPrice"] = that.resetResultListSumPrice(item)
          item.elecPrice = item.elecPrice.toFixed(8).replace(/\.?0+$/, "")
          item.servicePrice = item.servicePrice.toFixed(8).replace(/\.?0+$/, "")
        })
        let {
          name: latitude2,
          longitude: longitude2
        } = item;
        wx.setStorage({
          key: "index_seeInfo_chargpile",
          data: item
        });

        let url = `/pages/charginfo/charginfo?name=${name}&address=${address}&chargprice=${chargprice}&serviceprice=${serviceprice}&chargid=${markerId}&brandName=${brandName}`;
        wx.navigateTo({
          url
        });
      }
    });

  },
  resetResultListSumPrice(item){
 
    if(!item.elecPrice && item.elecPrice!=0){
      return '暂无费用'
    }
    if(!item.servicePrice && item.servicePrice!=0){
      return '暂无费用'
    }
    return (Number(item.elecPrice || 0) + Number(item.servicePrice || 0))
    .toFixed(8)
    .replace(/\.?0+$/, "");
  },
  //导航
  getRoute(e) {
    //console.log(e);
    // 起点
    let {
      user_lat: latitude,
      user_lon: longitude,
      markers,
      markerId,
      city,
      textData
    } = this.data;
    let {
      name,
      address
    } = textData;
    if (!markers.length) return;
    // 终点
    markers.forEach((item, index) => {
      if (markerId && markerId == item.id) {
        let {
          latitude: latitude2,
          longitude: longitude2
        } = item;
        let url = `/pages/routes/routes?longitude=${longitude}&latitude=${latitude}&longitude2=${longitude2}&latitude2=${latitude2}&city=${city}&name=${name}&desc=${address}`;
        //console.log(url);
        wx.navigateTo({
          url
        });
      }
    });
    return;
  },
  //回到当前位置
  click_location_control(e) {
    //console.log("回到用户当前定位点");
    // let {
    //   controlId
    // } = e;
    let mpCtx = wx.createMapContext("map");
    mpCtx.moveToLocation();
  },
  //打开扫一扫
  click_scan_control_outer(){
    this.click_scan_control("",true)
  },

  click_scan_control(scanResult,inner) {
    if(this.data.scanFlag){
      return;
    }
    this.data.scanFlag = true;
    wx.showLoading({
      title: '努力加载中...',
    })

  
    console.log("打开扫一扫");
    log.info('[首页]', '[打开扫一扫]');
    let that = this;
    if (!this.data.isLogin) {
      log.info('[首页]', '[未登陆跳转登录界面]');
      let url = `/pages/login/phone_login/phone_login`;
      that.data.scanFlag = false;
      wx.hideLoading();
      wx.navigateTo({
        url
      });
      return;
    } else {
      if (this.data.userInfo.flag) {// 运维人员不作操作，直接返回首页
        wx.hideLoading(); 
        return false;
      }
      if(!this.phoneCheck()){
        return;
      }
      log.info('[首页]', '[获取用户是否有未支付订单]', '[请求]', { userId: this.data.userInfo.userId });
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatsettlement',
        data: {
          userId: this.data.userInfo.userId
        },
        method: 'POST',
        success(res) {
          let {
            data
          } = res;
          let {
            result: order
          } = data;
          log.info('[首页]', '[获取用户是否有未支付订单]', '[响应]', data);
          if (data && order && data.code == 200) {
            that.data.scanFlag = false;
            wx.hideLoading();
            log.info('[首页]', '[用户有未支付订单跳转订单支付界面]');
            wx.showModal({
              showCancel: false,
              content: '你有未支付的订单，请先支付',
              confirmColor:'#00AADD',
              success: function (res) {
                //console.log(res);
                if (!res.cancel) {
                  //点击确定
                  let url = `/pages/order/order?orderid=${order.orderid}&userId=${order.userId}&chargPileId=${order.chargPileId}`;
                  wx.navigateTo({
                    url
                  });
                }
              }
            });
            //console.log(that.data.result);
          } else {
            //console.log('无订单');
            log.info('[首页]', '[用户无未支付订单]');
            //console.log("打开扫一扫");
            



            if(inner){
              wx.pro.scanCode().then(d=>{
                that.afterScanCode(d,that,inner)
              }).catch(e=>{
                that.data.scanFlag = false;
                wx.hideLoading();
              });
            }else{
              that.afterScanCode(scanResult,that,inner)
            }



          }
        },
        fail(e) {
          that.data.scanFlag = false;
          wx.hideLoading();
          getApp().showNetworkError();
        }
      });
    }
    
  },
  afterScanCode(d,that,inner){
    let scanResult = ""
    if(inner){
      //console.log("完成扫一扫");
      //console.log(d);
      //兼容标准格式hlht://202001022222220101.330414214二维码
      scanResult = d.result;
      if((!scanResult) || scanResult == ""){
        scanResult="*"
      }

  }else{
    scanResult = decodeURIComponent(d)
    //console.log(charePileId);
    log.info('[首页]', '[微信扫一扫]', { 'd': d });
    if(!scanResult){
      scanResult = "0"
    }
  }
  // 是否电池包
  let batteryFlag = false;
  if (scanResult.startsWith("tkd")){
    scanResult = scanResult.substring(3);
    batteryFlag = true
  }

  if (scanResult.startsWith("hlht://") || scanResult.startsWith("HLHT://")){
    scanResult = scanResult.substring(7, scanResult.indexOf("."));
  }
  scanResult = scanResult.replace("https://cdgl.pjnes.com/", "");
  scanResult = scanResult.replace("https://cdglyy.pjnes.com/", "");
  console.log('扫描到的内容: [' + scanResult + '] , 是否内部按钮：' + inner)
    log.info('[首页]', '[用户完成扫一扫]', scanResult);
    log.info('[首页]', '[获取扫一扫充电桩]', '[请求]', scanResult);
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/' + (batteryFlag? 'chargBattery' : 'chargPile'),
      // data: scanResult,
      data: {
        chargPileId:scanResult,
        userId: that.data.userInfo.userId
      },
      method: 'POST',
      success(res) {
        console.log( res.data);
        log.info('[首页]', '[获取扫一扫充电桩]', '[响应]', res.data);
        if (!res.data || res.data.code == 500) {
          that.data.scanFlag = false;
          wx.hideLoading();
          //没有该充电桩信息
          wx.showModal({
            showCancel: false,
            content: res && res.data && res.data.msg ? res.data.msg :'无效的终端编号',
            confirmColor:'#00AADD',
          });
        } else {
          res.data = res.data.result
          // 拨乱反正， 将电池包的逻辑强行合并
          if(batteryFlag){
            //  0空闲
            let status = res.data.parkStatus
            if(status == 1){
                wx.showModal({
                    showCancel: false,
                    content: '当前停靠点占用',
                    confirmColor:'#00AADD',
                });
            }else if(status == 0){
                wx.hideLoading();
                that.data.scanFlag = false;
                // 判断电池包
                if(res?.data?.chargPileList?.length==0 || !res?.data?.chargPileList){
                    wx.showModal({
                        showCancel: false,
                        content: '暂无可用电池包',
                        confirmColor:'#00AADD',
                    });
                    return;
                }

                wx.setStorage({
                    key: "elpackage",
                    data: res.data
                  });

                let url = `/pages/scan_result/elpackage`;


                wx.navigateTo({
                  url
                });
            }else{
                wx.showModal({
                    showCancel: false,
                    content: '未知错误，电池包返回状态码异常:' + res.data.parkStatus,
                    confirmColor:'#00AADD',
                });
            }
            that.data.scanFlag = false;
            wx.hideLoading();
            return;
          }
          

            //SZP
            // park_status


          //充电状态0：离线、1：故障、2：空闲中、3：充电中、4：欠压故障、5：过压故障、6：过电流故障、8：预约、9：在线升级、10：操作中、11:已插枪等
          if (!res.data.chargstatus || res.data.chargstatus == 0 || res.data.chargstatus == 1 || res.data.chargstatus == 4 || res.data.chargstatus == 5 || res.data.chargstatus == 6 || res.data.chargstatus == 9) {

            //充电桩故障    
            wx.showModal({
                showCancel: false,
                content: '终端故障，维修中',
                confirmColor:'#00AADD',
            });

          } else if (res.data.chargstatus == 3 || res.data.chargstatus == 8 || res.data.chargstatus == 10) {
            wx.showModal({
              showCancel: false,
              content: '正在充电中',
              confirmColor:'#00AADD',
            });
          } else if (res.data.chargstatus == 2 || res.data.chargstatus == 11) {
            wx.setStorage({
              key: "scan_chargpile",
              data: res.data
            });
            log.info('[首页]', '[扫一扫充电桩空闲跳转去充电界面]');
            let url = `/pages/scan_result/scan_result`;
            that.data.scanFlag = false;
            wx.hideLoading();
            wx.navigateTo({
              url
            });
          }
          that.data.scanFlag = false;
          wx.hideLoading();
        }
      },
      fail(e) {
        getApp().showNetworkError();
      }
    });
  },
  //地图位移
  mapchange(e) {
    if (e.type == 'end') {
      if (!mapregionchange_makertap) {
        //console.log("移动地图");
        let that = this;
        let wMap = wx.createMapContext('map');
        wMap.getCenterLocation({
          type: 'gcj02',
          success: function (res) {
            let {
              latitude,
              longitude
            } = res;
            let userInfo = wx.getStorageSync('userInfo');
            let isLogin = wx.getStorageSync('isLogin');
            var chargStationType;
            if (!userInfo.flag) {
              //用户是普通用户
              chargStationType = '2';
            }
            wx.request({
              url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargStations',
              data: {
                lon: longitude,
                lat: latitude,
                distance: that.data.distanceinfo[that.data.distanceinfoindex].value,
                chargStationType
              },
              method: 'POST',
              success(res) {
                that.resetchargStations(res.data)
                let {
                  data
                } = res;
                let markers = [];
                var flag = false;
                if(data){
                data.forEach((item, index) => {
                  var iconPath;
                  if (that.data.markerId && that.data.markerId == item.id) {
                    iconPath = "/images/marker_checked.png";
                    flag = true;
                  } else {
                    iconPath = "/images/marker.png";
                    if (that.data.myChargeStationsIds.indexOf(item.id + ',') != -1) {
                      iconPath = "/images/marker1.png";
                    }
                    //撤销普通用户显示异常站
                    if (isLogin && userInfo.flag) {
                      //撤销结束
                      if (item.breaknum && item.breaknum != 0) {
                        iconPath = "/images/marker_b.png";
                      }
                      //撤销普通用户显示异常站
                    }
                    //撤销结束

                  }
                  //console.log(Util.distance(that.data.user_lat, that.data.user_lon, item.lat, item.lon));
                  var marker = {
                    brandName:item.brandName,
                    name: item.chargStationName,
                    address: item.address,
                    width: "46rpx",
                    height: "67rpx",
                    chargfeatures: item.chargfeatures ,
                    iconPath: iconPath,
                    id: item.id,
                    callout: {},
                    latitude: item.lat,
                    longitude: item.lon,
                    //distance: item.distance / 1000,
                    distance: Util.distance(that.data.user_lat, that.data.user_lon, item.lat, item.lon),
                    chargPileNum: item.fastCharg + item.slowCharg,
                    fastCharg: item.fastCharg,
                    slowCharg: item.slowCharg,
                    freenum: item.freenum,
                    fastfreenum: item.fastfreenum,
                    slowfreenum: item.slowfreenum,
                    breaknum: item.breaknum,
                    /** 电费 */
                    chargprice: item.chargprice,
                    /** 服务费 */
                    serviceprice: item.serviceprice,
                    /** 停车费 */
                    stopprice: item.stopprice,
  
                    operationState: item.operationState,
                    sharpChargPrice : item.sharpChargPrice,
                    sharpServicePrice : item.sharpServicePrice,
                    peakChargPrice : item.peakChargPrice,
                    peakServicePrice : item.peakServicePrice,
                    flatChargPrice : item.flatChargPrice,
                    flatServicePrice : item.flatServicePrice,
                    valleyChargPrice : item.valleyChargPrice,
                    valleyServicePrice : item.valleyServicePrice,
                    resultList: item.resultList,
                    chargStationId: item.id,
                    stationTag: item.stationTag,
                    stationTagList: item.stationTagList,
                    offlineServicecall: item.offlineServicecall,
                    
                  };
                  markers[index] = marker;
                });
              }
                if (!flag) {
                  that.setData({
                    textData: null,
                    markerId: null,
                  });
                }
                that.setData({
                  markers: markers
                });
              },
              fail(e) {
                getApp().showNetworkError();
              }
            });
          }
        });
      } else {
        //点击marker的情况下
        //console.log("点击marker");
        mapregionchange_makertap = false;
      }
    }
  },

  phoneCheck(){
    if (this.data.userInfo.bindingPhone==0) {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '当前账户未绑定手机号，请您进行手机号绑定操作',
        showCancel:false,
        confirmText: '去绑定',
        confirmColor:'#00AADD',
        success: function (res1) {
            let url = `/pages/bindPhone/bindPhone`;
            wx.navigateTo({
              url
            });
        }
      })
      return false;
    }else{
      return true;
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 处理页面跳转回来导致费率字段类型为字符串，处理为数值类型避免报错
    let that = this;
    for (let i = 0; i < that.data.markers.length; i++) {
        let marker = that.data.markers[i];  // 直接获取 marker，减少 that.data 访问
        let resultList = marker.resultList;

        if (!resultList) continue; 
        for (let j = 0; j < resultList.length; j++) {
            let item = resultList[j]; 
            if (item.elecPrice === '暂无费用') {
                item.chargprice = '暂无费用';
            } else {
                item.elecPrice = parseFloat(parseFloat(item.elecPrice).toFixed(8).replace(/\.?0+$/, ""));
            }
            if (item.servicePrice === '暂无费用') {
                item.servicePrice = '暂无费用';
            } else {
                item.servicePrice = parseFloat(parseFloat(item.servicePrice).toFixed(8).replace(/\.?0+$/, ""));
            }
        }
        marker.resultList = resultList; // 直接赋值给 marker
    }
    this.data.scanFlag = false;
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    // 页面显示
    if (userInfo && isLogin) {
      //console.log(userInfo);
      //userInfo.flag = true;
      this.setData({
        userInfo: userInfo,
        isLogin: isLogin
      });
      if ((!userInfo.userId && userInfo.userId != 0)){
        log.info('[首页]', '[已登陆未有用户ID跳转登录界面]');
        let url = `/pages/login/phone_login/phone_login`;
        wx.navigateTo({
          url
        });
        return;
      }

    // 查询订单

      log.info('[首页]', '[获取用户是否有未完成订单]', '[请求]', { userId: userInfo.userId });
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatchargstatus',
        data: {
          userId: userInfo.userId
        },
        method: 'POST',
        success(res) {
          let {
            data
          } = res;
          log.info('[首页]', '[获取用户是否有未完成订单]', '[响应]', data);
          if (data && data.code == 200) {
            log.info('[首页]', '[有未完成订单跳充电界面]');
            //获取用户正在充电的订单，并跳转到该页面
            let url = `/pages/charging/charging?orderid=${data.result.orderid}&userId=${userInfo.userId}&chargPileId=${data.result.chargPileId}`;
            //let url = `/pages/charging/charging?userId=${userInfo.userId}`;
            wx.navigateTo({
              url
            });
          } else {
            //console.log(res);
          }
        },
        fail(e) {
          getApp().showNetworkError();
        }
      });

    // 查询呼叫电车
    console.log("查询呼叫电车")
    wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/wechat/ivCarRequirement' + 
        '?userId='+userInfo.userId,
        data: {
        },
        method: 'POST',
        success(res) {
            console.log(res?.data?.result?.requirementStep)
            // 0-7 进等待 8进终端详情
            if(res?.data?.result?.requirementStep>=0 && res?.data?.result?.requirementStep<=7){
                // 等待
                let url = `/pages/batteryPack/batteryPackWait`;
                wx.reLaunch({
                  url
                });
            }else if(res?.data?.result?.requirementStep==8){
                // 8进终端详情
                let url = `/pages/batteryPack/batteryPackWait`;
                wx.reLaunch({
                  url
                });
            }
        },
        fail(e) {
            getApp().showNetworkError();
        }
    });

    } else {
      //未登录信息
      this.setData({
        userInfo: {}
      });
    }
  },
  bindDistanceinfoChange: function (e) {
    let distance = this.data.distanceinfo[e.detail.value].value;
    this.setData({
      distanceinfoindex: e.detail.value
    });
  },
  Sure: function () {
    this.setData({
      showModal: false
    });
  },
  handleAgreePrivacyAuthorization() {
      console.info('3333333333333');
      this.setData({
        showPrivacy: false
      })
    // 用户同意隐私协议事件回调
    // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
    // wx.getUserProfile()
    // wx.chooseMedia()
    // wx.getClipboardData()
    // wx.startRecord()
  },
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  }
})