//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: ''
  },
  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) {
        //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) {
              //console.log(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 = {
                  name: item.chargStationName,
                  address: item.address,
                  width: "46rpx",
                  height: "67rpx",
                  iconPath: "/images/marker.png",
                  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
                };
                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 = {
              name: item.chargStationName,
              address: item.address,
              width: "46rpx",
              height: "67rpx",
              iconPath: "/images/marker.png",
              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
            };
            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) {
        //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) {
              //console.log(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
                // };
                //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",
                  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
                };
                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) => {
            //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",
              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
            };
            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 markerId = e.currentTarget.id;
    let pages = getCurrentPages();
    let prevPage = pages[0]; //首页
    this.data.markers.forEach((item, index) => {
      if (markerId && markerId == item.id) {
        let {
          latitude,
          longitude
        } = item;
        prevPage.setData({
          markerId,
          latitude,
          longitude,
          keywords:this.data.keywords,
          textData: item
        });

        wx.navigateBack({
          delta: pages.length
        });
      }
    });
  },
  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: ''
    });
  }
})