//index.js
//获取应用实例
let app = getApp();
let wechat = require("../../utils/wechat");
let amap = require("../../utils/amap");
let Util = require('../../utils/util');
Page({
  data: {
    markers: [],
    latitude: null,
    longitude: null,
    city: null,
    userInfo: {},
    isLogin: false,
    myChargeStationsIds: '',
    moneyActive: false,
    distanceActive: true,
    myChargeStationsActive: false,
    distancePng: 'asc',
    keywords: null,
    moneyPng: ''
  },
  resetchargStations(data){
    let that = this
    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){
        data.chargprice = resultList[i].elecPrice
        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) {
    let {
      city,
      latitude,
      longitude,
      searchString
    } = e;
    console.log(city, latitude, longitude, searchString);
    this.setData({
      city,
      latitude,
      longitude,
      keywords: searchString
    });
    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
      });
    } else {
      //未登录信息
      this.setData({
        userInfo: {}
      });
    }

    //开始请求充电站信息
    let that = this;
    var chargStationType;
    if (!userInfo.flag) {
      //用户是普通用户
      chargStationType = '2';
    }
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/chargStationsSearch',
      data: {
        searchString,
        chargStationType
      },
      method: 'POST',
      success(res) {
        that.resetchargStations(res.data)
        //userInfo.flag = true;
        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) => {
          
                var marker = {
                  brandName:item.brandName,
                  name: item.chargStationName,
                  address: item.address,
                  width: "46rpx",
                  height: "67rpx",
                  iconPath: "/images/marker.png",
                  chargfeatures:item.chargfeatures,
                  id: item.id,
                  callout: {},
                  latitude: item.lat,
                  longitude: item.lon,
                  //distance: item.distance / 1000,
                  distance: Util.distance(latitude, longitude, 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.toFixed(8).replace(/\.?0+$/, ""),
                  /** 服务费 */
                  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,
                };
                if (myChargeStationsIds.indexOf(item.id + ',') != -1) {
                  marker.userFlag = true;
                } else {
                  marker.userFlag = false;
                }
                
                markers[index] = marker;

              });
              markers.sort(function (ma, mb) {
                return ma.distance - mb.distance;
              });
              that.setData({
                markers,
                myChargeStationsIds
              });
              console.log(markers);
            }
          });
        } else {
          let {
            data
          } = res;
          let markers = [];
          data.forEach((item, index) => {
            var marker = {
              brandName:item.brandName,
              name: item.chargStationName,
              address: item.address,
              width: "46rpx",
              height: "67rpx",
              iconPath: "/images/marker.png",
              chargfeatures:item.chargfeatures,
              id: item.id,
              callout: {},
              latitude: item.lat,
              longitude: item.lon,
              //distance: item.distance / 1000,
              distance: Util.distance(latitude, longitude, 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.toFixed(8).replace(/\.?0+$/, ""),
              /** 服务费 */
              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;
          });
          markers.sort(function (ma, mb) {
            return ma.distance - mb.distance;
          });
          that.setData({
            markers
          });
          console.log(markers);
        }
      }
    });
  },
  onLoad2(e) {
    let {
      city,
      name,
      latitude,
      longitude,
      location
    } = e;
    console.log(name, latitude, longitude, location);
    this.setData({
      city,
      latitude,
      longitude
    });
    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
      });
    } else {
      //未登录信息
      this.setData({
        userInfo: {}
      });
    }

    //开始请求充电站信息
    let that = this;
    var chargStationType;
    if (!userInfo.flag) {
      //用户是普通用户
      chargStationType = '2';
    }
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/chargStations',
      data: {
        lon: location.split(",")[0],
        lat: location.split(",")[1],
        distance: 10000,
        chargStationType
      },
      method: 'POST',
      success(res) {
        that.resetchargStations(res.data)
        //userInfo.flag = true;
        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) => {
                console.log("itemitemitemitemitem");
                console.log(item);
                //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
                // };
                //console.log(Util.distance(latitude, longitude, item.lat, item.lon));
                var marker = {
                  name: item.chargStationName,
                  address: item.address,
                  width: "46rpx",
                  height: "67rpx",
                  iconPath: "/images/marker.png",
                  chargfeatures:item.chargfeatures,
                  id: item.id,
                  callout: {},
                  latitude: item.lat,
                  longitude: item.lon,
                  //distance: item.distance / 1000,
                  distance: Util.distance(latitude, longitude, 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,
                };
                if (myChargeStationsIds.indexOf(item.id + ',') != -1) {
                  marker.userFlag = true;
                } else {
                  marker.userFlag = false;
                }
                markers[index] = marker;

              });
              markers.sort(function(ma, mb) {
                return ma.distance - mb.distance;
              });
              that.setData({
                markers,
                myChargeStationsIds
              });
              console.log(markers);
            }
          });
        } else {
          let {
            data
          } = res;
          let markers = [];
          data.forEach((item, index) => {
            console.log("itemitemitemitemitem");
            //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
            // };
            //console.log(Util.distance(latitude, longitude, item.lat, item.lon));
            var marker = {
              name: item.chargStationName,
              address: item.address,
              width: "46rpx",
              height: "67rpx",
              iconPath: "/images/marker.png",
              chargfeatures:item.chargfeatures,
              id: item.id,
              callout: {},
              latitude: item.lat,
              longitude: item.lon,
              //distance: item.distance / 1000,
              distance: Util.distance(latitude, longitude, 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;
          });
          markers.sort(function(ma, mb) {
            return ma.distance - mb.distance;
          });
          that.setData({
            markers
          });
          console.log(markers);
        }
      }
    });
  },
  getRoute(e) {
    console.log(e);
    // 起点
    let {
      latitude,
      longitude,
      markers,
      city
    } = this.data;
    if (!markers.length) return;
    let markerId = e.currentTarget.id;
    // 终点
    markers.forEach((item, index) => {
      if (markerId && markerId == item.id) {
        let {
          name,
          address,
          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
        });
      }
    });
  },
  goIndex(e) {
    //console.log(e);
    let that = this;
    let markerId = e.currentTarget.id;
    let pages = getCurrentPages();
    let prevPage = pages[0]; //首页
    let markers =  this.data.markers; //首页
    this.data.markers.forEach((item, index) => {
      if (markerId && markerId == item.id) {
        wx.navigateBack({
          delta: pages.length
        });
        wx.request({
          url: getApp().globalData.postHeadAgreement + '/restapi/wechat/carParkingRate?stationId=' + item.id,
          method: 'POST',
          success: function (res) {
            // 是否减免停车费
            let carParkingRate =  false
            let parkTime = 0;
            console.info(res)
            let reduceTime = res.data?.reduceTime;
            if(!reduceTime){
              carParkingRate = false
            }else{
              carParkingRate = true
            }
            try{
              parkTime = parseFloat((reduceTime/ 3600).toFixed(2))
            }catch(e){
              carParkingRate = false
            }

            let {
              latitude,
              longitude
            } = item;
            prevPage.setData({
              markers,
              markerId,
              latitude,
              longitude,
              carParkingRate,
              parkTime,
              keywords: that.data.keywords,
              textData: item
            });
            console.info({
              markers,
              markerId,
              latitude,
              longitude,
              keywords: that.data.keywords,
              textData: item
            })

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

      }
    });
  },
  myChargeStationsOrder(e) {
    let {
      markers
    } = this.data;
    if (markers && 0 != markers.length) {
      markers.sort(function(ma, mb) {
        return mb.userFlag - ma.userFlag == 0 ? ma.distance - mb.distance : mb.userFlag - ma.userFlag;
      });
    }
    this.setData({
      markers,
      myChargeStationsActive: true,
      distanceActive: false,
      moneyActive: false,
      moneyPng: '',
      distancePng: ''
    });
  },
  distanceOrder(e) {
    let {
      markers
    } = this.data;
    let {
      distancePng
    } = this.data;
    if (distancePng == '' || distancePng == 'desc') {
      if (markers && 0 != markers.length) {
        markers.sort(function(ma, mb) {
          return ma.distance - mb.distance;
        });
      }
      this.setData({
        distancePng: 'asc'
      });
    } else {
      if (markers && 0 != markers.length) {
        markers.sort(function(ma, mb) {
          return mb.distance - ma.distance;
        });
      }
      this.setData({
        distancePng: 'desc'
      });
    }
    this.setData({
      markers,
      myChargeStationsActive: false,
      distanceActive: true,
      moneyActive: false,
      moneyPng: ''
    });
  },
  moneyOrder(e) {
    let {
      markers
    } = this.data;
    let {
      moneyPng
    } = this.data;
    if (moneyPng == '' || moneyPng == 'desc') {
      if (markers && 0 != markers.length) {
        markers.sort(function(ma, mb) {
          return (ma.chargprice + ma.serviceprice + ma.stopprice) - (mb.chargprice + mb.serviceprice + mb.stopprice);
        });
      }
      this.setData({
        moneyPng: 'asc'
      });
    } else {
      if (markers && 0 != markers.length) {
        markers.sort(function(ma, mb) {
          return (mb.chargprice + mb.serviceprice + mb.stopprice) - (ma.chargprice + ma.serviceprice + ma.stopprice);
        });
      }
      this.setData({
        moneyPng: 'desc'
      });
    }
    this.setData({
      markers,
      myChargeStationsActive: false,
      distanceActive: false,
      moneyActive: true,
      distancePng: ''
    });
  }
})