// pages/mine/index/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: '昵称',
    name: '用户名称',
    userIcon: '/images/ic_user_default.png',
    menuList: [],
    imgUrl: app.urls.baseImgUrl,
    Height: 0,
    isShow: true,
    isBindPhone: false,
    isPay: true, //是否需要交费
    code: '',
    isOpen: true,
    payState: {},
    accountInfo: undefined,
    userId: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _self = this
    _self.setData({
      nickName: app.globalData.userInfo.name,
      name: app.globalData.userInfo.name
    })
    try {
      var isBind = wx.getStorageSync('bindPhone')
      var code = wx.getStorageSync('usercode')
      var userId = wx.getStorageSync('userId')
      if (code && code.length > 0) {
        _self.setData({
          code: code,
          userId: userId
        })
      }
      _self.setData({
        isBindPhone: isBind == 0
      })
    } catch (err) {
      console.log(err)
    }
  },
  //获取我的账户信息
  getAccountInfo() {
    var _self = this
    app.http.get(app.urls.getMyAccount, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        _self.setData({
          accountInfo: res.data
        })
      })
      .catch(err => {
        console.log(err)
      })
  },
  //获取支付状态
  getPayState() {
    wx.showLoading({
      title: '加载中...',
    })
    var _self = this
    app.http.get(app.urls.getPayState, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        //支付过跳转名片创建页面,没有支付跳转支付页面
        if (res.data.cardChargeEnd && res.data.cardChargeEnd.length > 0) {
          res.data.cardChargeEnd = _self.formatDate(res.data.cardChargeEnd)
        }
        _self.setData({
          isPay: res.data.cardCharge,
          payState: res.data
        })
      })
      .catch(err => {

      })
  },
  formatDate(date) {
    if (date.length > 0) {
      return date.slice(0, 11)
    } else {
      return ''
    }
  },
  //获取菜单状态
  getMenuState() {
    var _self = this
    app.http.get(app.urls.getMenuState, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        _self.setData({
          isOpen: res.data
        })
      })
      .catch(err => {

      })
  },
  //获取菜单
  getItemList() {
    wx.showLoading({
      title: '加载中...',
    })
    var _self = this
    app.http.get(app.urls.getMenuList, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        var data = res.data
        wx.stopPullDownRefresh({})
        wx.hideLoading({})
        var is = true
        data.forEach(it => {
          it.configColumnList.sort((a, b) => a.configColumnGroupOrder - b.configColumnGroupOrder)
          if (it.configColumnGroupName == '创建名片') {
            is = false
          }
        })
        _self.setData({
          menuList: data,
          isShow: is
        })
      })
      .catch(err => {
        console.log(err)
        wx.stopPullDownRefresh({})
        wx.hideLoading({})
      })
  },
  checkPermission() {
    var _self = this
    try {
      var names = wx.getStorageSync('name')
      var icon = wx.getStorageSync('userIcon')
      if (names) {
        this.setData({
          name: names,
          userIcon: icon
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '小程序需要您微信头像以及昵称用于展示,请授权.',
          showCancel: false,
          success(res) {
            console.log(res)
            if (res.confirm) {
              // _self.getUserProfile(3)
            }
          }
        })
      }
    } catch (error) {
      wx.showToast({
        title: '获取信息失败',
        icon: 'error'
      })
    }
  },
  getUserProfile(e) {
    let _self = this
    wx.getUserProfile({
      desc: '获取微信头像以及昵称用于展示',
      success: (res) => {
        wx.setStorage({
          data: res.userInfo.nickName,
          key: 'name',
        })
        wx.setStorage({
          data: res.userInfo.avatarUrl,
          key: 'userIcon',
        })
        _self.setData({
          name: res.userInfo.nickName,
          userIcon: res.userInfo.avatarUrl
        })
      },
      fail(err) {
        //判断是否绑定手机号
        wx.showToast({
          title: '获取个人信息失败',
          icon: 'error',
        })
      }
    })
  },
  addShop() {
    wx.navigateTo({
      url: '../shop/addshop',
    })
  },
  onShow() {
    var name = wx.getStorageSync('name')
    var userIcon = wx.getStorageSync('userIcon')
    var isBind = wx.getStorageSync('bindPhone')
    if (name) {
      this.setData({
        name: name,
        userIcon: userIcon,
        isBindPhone: isBind == 0
      })
    }
    // this.getMenuState()
    this.getItemList()
    this.getPayState()
    this.getAccountInfo()
  },
  //item 状态  1 待付款 2待发货  3待收货  4售后/退款
  showOrder(e) {
    var item = e.currentTarget.dataset.item
    console.log(item)
    var path = '/pages/mine/order/orderlist?status=' + item
    wx.navigateTo({
      url: path,
    })
  },
  choosePage(e) {
    // 栏目列表页跳转方式1:小程序页面,2:其他小程序,3:网址
    var path = e.currentTarget.dataset.path
    var type = e.currentTarget.dataset.type
    var item = e.currentTarget.dataset.item
    switch (type) {
      case '1': //跳转小程序内部
      case '3': //链接
        wx.navigateTo({
          url: path + '?id=' + item.configColumnId + '&mode=' + item.configTableMode + '&type=' + item.configColumnType + '&title=' + item.configColumnName
        })
        break
      case '2': //其他小程序
        wx.navigateToMiniProgram({
          appId: '',
          success(res) {
            // 打开成功
          }
        })
        break
    }
  },
  onPullDownRefresh() {
    this.getItemList()
    this.getPayState()
    this.getAccountInfo()
    this.getBaseInfo()
  },
  getBaseInfo() {
    var _self = this
    app.http.get(app.urls.getMainMoment.format({
        configColumnId: 'de7b5e22-64f9-4c60-a1f9-6ac004dfb9a8'
      }), {
        header: {
          token: app.globalData.token
        },
        data: {
          userId: _self.data.userId
        }
      })
      .then(res => {
        if (res.data.length > 0) {
          res.data[0].list.forEach(it => {
            switch (it.name) {
              case 'cardtitle':
                wx.setStorageSync('cardtitle', it.value)
                break
              case 'postertitle':
                wx.setStorageSync('postertitle', it.value)
                break
            }
          })
        } else {}
      })
      .catch(err => {})
  },
  //跳转到二级栏目页面
  goColumnList(e) {
    var item = e.currentTarget.dataset.item
    // 1小程序  . 2其他小程序 . 3网址 . 4栏目列表
    if (item.configColumnGroupTargetMode == '1') {
      //小程序
      wx.navigateTo({
        url: item.configColumnGroupTargetUrl,
      })
    } else if (item.configColumnGroupTargetMode == '2') {
      //其他小程序
    } else if (item.configColumnGroupTargetMode == '3') {
      //url
    } else {
      //二级列表
      wx.navigateTo({
        url: '../columnlist/columnlist?id=' + item.configColumnGroupId + '&title=' + item.configColumnGroupName,
      })
    }

  },
  // 跳转到 我的名片
  goMyCard: function () {
    wx.navigateTo({
      url: '../myCard/myCard',
    })
  },
  //跳转设置页面
  showSetting() {
    wx.navigateTo({
      url: '../../mine/setting/columnsetting'
    })
  },
  imgHeight(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw * 0.88 + "px"

    this.setData({
      Height: swiperH //设置高度
    })
  },
  //引导跳转
  toFunction(e) {
    var _self = this
    var path = ''
    _self.data.menuList.forEach(it => {
      //判断引导
      if (it.configColumnGroupDirection == '3') {
        //引导
        path = it.configColumnGroupTargetUrl
      }
    })
    wx.navigateTo({
      url: path,
    })
  },
  //获取手机号进行绑定
  getPhoneNumber(e) {
    var _self = this
    var iv = e.detail.iv
    var encryptedData = e.detail.encryptedData
    if (encryptedData) {
      wx.showLoading({
        title: '绑定中...',
      })
      app.http.put(app.urls.doUpdatePhone, {
          header: {
            token: app.globalData.token
          },
          data: {
            iv: iv,
            encryptedData: encryptedData
          }
        })
        .then(res => {
          wx.hideLoading({})
          //保存绑定状态
          wx.setStorageSync('token', res.data.data)
          wx.setStorageSync('bindPhone', 1)
          _self.setData({
            isBindPhone: true
          })
          app.globalData.token = token
          wx.showToast({
            title: '绑定成功',
            success(e) {
              wx.navigateTo({
                url: '/packagecard/cardList/cardList',
              })
            }
          })
        })
        .catch(err => {})
    }
  },
  //复制邀请码
  copyCode() {
    var _self = this
    if (_self.data.code != '') {
      wx.setClipboardData({
        data: _self.data.code,
        success: function () {}
      })
    } else {
      wx.showToast({
        title: '无邀请码',
        icon: 'error'
      })
    }
  },
  //营销资讯
  toInformation() {
    wx.navigateTo({
      url: '/packagecard/marketing/marketinginfo',
    })
  },
  //营销海报
  toReport() {
    wx.navigateTo({
      url: '/packagecard/marketing/marketingposter',
    })
  },
  //收益统计
  toStatistics() {
    wx.navigateTo({
      url: '/pages/mine/income/incomelist',
    })
  },
  //会员中心
  vipCenter() {
    wx.navigateTo({
      url: '/pages/mine/vip/vipcenter',
    })
  },
  //扫码
  toScan() {
    wx.scanCode({
      success(res) {

      }
    })
  },
  //订单页面跳转
  showOrder(e) {
    var type = e.currentTarget.dataset.type
    // 0待付款 1待发货 2待收货 3全部
    wx.navigateTo({
      url: '/pages/mine/order/orderlist?status=' + type,
    })
  },
  doCash(e) {
    wx.navigateTo({
      url: '/packagecard/purse/takecash',
    })
  }
})