// page/homePage/homePage.js

const app = getApp();
var a = require("../../wxParse/wxParse.js");
var api = require("../../api.js");
var sever = require("../../api.js").sever;
console.log(sever)
var amapFile = require('../../amap-wx.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['北京市', '上海市', '杭州市', '广东市'],
    index: 0,
    bannerShow: 0,
    listShow: 0,
    imgBorder: 0,
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    isIphoneX: false,


    next_page_url:'',
    is_login: false,
    inputShowed: false,
    inputVal: "",
    takeup: true,
    more: false,
    color:'#666',
    route:'',
    color1: 'RGB(233,59,61)',
    color2: '#666',
    tappid: "",
    tpath: '',
    tappid1:'wx75bace3bfac6a8ee',
    tpath1:'/pages/index/index',
    tpath2:'pages/topic-list/topic-list',
    gourl:'www.baidu.com'

  },
  huace: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform == "devtools") {
          console.log('PC')
          that.setData({
            tappid: 'wxeb58f03a8553df9a',
            tpath: 'pages/index/index'
          })
        } else if (res.platform == "ios") {
          console.log('IOS')
          that.setData({
            tappid: 'wxeb58f03a8553df9a',
            tpayh: 'pages/index/index'
          })
        } else if (res.platform == "android") {
          console.log('android')
          that.setData({
            tappid: 'wxeb58f03a8553df9a',
            tpayh: 'pages/index/index'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  pickChange: function (e) {
    this.setData({
      index: e.detail.value
    });
  },
  bannerShow: function () {
    this.setData({
      bannerShow: 1
    })
    var gourl = this.data.sysinfo.go_url ? this.data.sysinfo.go_url :''
    if(gourl&&gourl!='')
    wx.navigateTo({
      url: '../homePage/outurl?url=' + gourl
    })
  },
  listShow: function (e) {
    console.log(e.target.dataset.productid)
    this.setData({
      listShow: e.target.dataset.productid
    })
  },
  borderShow: function (e) {
    console.log(e.target.dataset.borderid)
    this.setData({
      imgBorder: e.target.dataset.borderid
    })
  },
  isIphoneX() {
    let mobile = wx.getSystemInfoSync();
    if (mobile.model.indexOf("iPhone X") >= 0) {
      return true;
    } else {
      return false;
    }
  },



  onLoad: function (options) {
    this.setData({
      "isIphoneX": this.isIphoneX()
    })


    wx.login({
      success: function (res) {
      wx.getUserInfo({
        success: function (res) {
          wx.setStorageSync("iv", res.iv)
          wx.setStorageSync("encryptData", res.encryptedData)
        }
      })
      }
    })
    this.huace()
    var that = this
    that.setData({
      route: that.route
    })
    var myAmapFun = new amapFile.AMapWX({
      key: 'f74da0d1484bbbefb69059efa771b01d'
    });
    myAmapFun.getWeather({
      success: function(data) {
        console.log(data)
        that.setData({
          weather: data.weather.data,
          temp: data.temperature.data,
        })
      },
      fail: function(info) {
        //失败回调
        console.log(info)
      }
    })
    app.request1({
        url: api.setting,
        success: function(e) {
          console.log(e.data)
          that.setData({
              slide: e.data.banner,
              nav: e.data.navbar,
              sysinfo: e.data.setting,
            menus: e.data.menus,
            getfocus: e.data.getFocus
            }),
            console.log(that.data.sysinfo)
            app.avatar = e.data.setting.avatar,
            app.username = e.data.setting.name
          wx.setNavigationBarTitle({
              title: e.data.setting.illustrated_name,
            }),

            wx.setNavigationBarColor({
              frontColor: '#000000',
              backgroundColor: '#ffffff'
            })
        }
        //console.log(e.data)
      }),
      app.request1({
        url: api.news_list,
      success: function (e) {
        var datas = e.data.data
        for (var i = 0; i < datas.length; i++) {
          var ht = datas[i].content
          var re1 = new RegExp("<.+?>", "g");//匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
          var msg = ht.replace(re1, '');//执行替换成空字符
          console.log(msg)
          datas[i].txt = msg
        }
          that.setData({
            next_page_url:e.data.next_page_url,
            news: datas,
          })
          console.log(that.data.news)
        }
      }), 
      app.request1({
        url: api.newgoods_list,
        success: function (e) {
          console.log(e)
          var datas = e.data.data
          for(var i=0;i<datas.length;i++){
            var ht = datas[i].content
            var re1 = new RegExp("<.+?>", "g");//匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
            var msg = ht.replace(re1, '');//执行替换成空字符
            console.log(msg)
            datas[i].txt = msg
          }
          that.setData({
            //next_page_url: e.data.next_page_url,
            newsgoods: datas,
          })
        }
      }),
      app.request1({
        url: api.goods_list,
        success: function(e) {
          console.log(e)
          that.setData({
            goods: e.data.data,
          })
        }
      });
      


  },

  navigatorClick: function(e) {
    console.log(1)
    var page = this;
    var open_type = e.currentTarget.dataset.open_type;
    if (open_type == 3) {
      var url = e.currentTarget.dataset.url;
      var appid = e.currentTarget.dataset.appid;
      var user_info = wx.getStorageSync("user_info");
      //return true;
      //console.log(url);
      console.log(appid);
      wx.navigateToMiniProgram({
        appId: appid,
        path: url + '?user_id=' + user_info.user_id,
        complete: function(e) {
          console.log(e);
        }
      });
    } else if (open_type == 1) {
      var phone = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
        phoneNumber: phone,
      })
    } else if (open_type == 2) {
      var address = e.currentTarget.dataset.address;
      var lon = parseFloat(e.currentTarget.dataset.lon);
      var lat = parseFloat(e.currentTarget.dataset.lat);

      wx.openLocation({
        name: address,
        latitude: lat,
        longitude: lon,
        scale: 28
      })
    } else if (open_type == 4) {
      var url = e.currentTarget.dataset.url;
      wx.navigateTo({
        url: url
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this
    if(that.data.next_page_url)
    {
      app.request1({
        url: that.data.next_page_url,
        success: function (e) {
          that.setData({
            next_page_url: e.data.next_page_url,
            news: [...that.data.news.concat(e.data.data)],
          })
          console.log(that.data.news)
        }
      })
    }else{
      console.log('no more news')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  showInput: function() {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function() {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  takeup: function() {
    var that = this
    that.setData({
      takeup: false,
      more: true
    })
  },
  more: function() {
    var that = this
    that.setData({
      takeup: true,
      more: false
    })
  },
  todetail: function(e) {
    console.log(e.currentTarget.dataset.id)
    var news_id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: 'detail/detail?id=' + news_id+'&way='+'wk',
    })
  },
  togdetail: function (e) {
    console.log(e.currentTarget.dataset.id)
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: 'detail/detail?id=' + id+'&way='+'xp',
    })
  },
  goShouhou: function() {
    var that = this
    if (wx.getStorageSync('user')) {
      var u = wx.getStorageSync('user')
      if (u.role == 0) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
      if (u.role == 1) {
        wx.redirectTo({
          url: '/pages/make/make',
        })
      }
      if (u.role == 2) {
        wx.redirectTo({
          url: '/pages/packing/packing',
        })
      }
      if (u.role == 3) {
        wx.redirectTo({
          url: '/pages/manager/manage',
        })
      }
    } else {
      that.setData({
        is_login: true
      })
    }

  },
  goJingdu: function () {
    var that = this
    if (wx.getStorageSync('user')) {
      var u = wx.getStorageSync('user')
      if (u.role == 0) {
        wx.redirectTo({
          url: '/pages/infor/infor',
        })
      }
      if (u.role == 1) {
        wx.redirectTo({
          url: '/pages/make/make',
        })
      }
      if (u.role == 2) {
        wx.redirectTo({
          url: '/pages/packing/packing',
        })
      }
      if (u.role == 3) {
        wx.redirectTo({
          url: '/pages/manager/manage',
        })
      }
    } else {
      that.setData({
        is_login: true
      })
    }

  },
  close_login: function() {
    this.setData({
      is_login: false
    })
  },
  userLogin: function(e) {
    this.setData({
      is_login: false
    })
    wx.showLoading({
      title: '登录中',
    })
    console.log(e.detail)
    var un = JSON.parse(e.detail.rawData)
    var that = this
    try {
      wx.login({
        success: function(res) {
          let code = res.code
          console.log(code)
          let tx = un.avatarUrl
          let nn = un.nickName
          let iv = e.detail.iv
          let encryptedData = e.detail.encryptedData
          app.request({
            url: sever+'service_login',
            method: 'POST',
            data: {
              code: code,
              avatar: tx,
              nickName: nn,
              store_id: app.globalData.store_id,
              iv: iv,
              encryptData: encryptedData
            },
            success: function(res) {
              console.log(res.data)
              wx.setStorageSync("token", res.data.data.token)
              wx.setStorageSync('key', res.data.data.session_key)
              wx.setStorageSync("user", res.data.data.user);
              wx.setStorageSync('ma', 0)
              wx.setStorageSync('pa', 0)
              wx.setStorageSync('us', 0)
              wx.hideLoading();
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1000,
                
              })
            }
          })
        }
      })
    } catch (e) {
      console.log(e.message)
    }
  },
})