var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');
var app = getApp();
// 定义插件变量 引入方法

const tempUserInfo = {
  nickName: 'Hi,游客',
  userName: '点击去登录',
  avatarUrl: 'https://platform-wxmall.oss-cn-beijing.aliyuncs.com/upload/20180727/150547696d798c.png'
}

Page({
    data: {
        userInfo: {},
        hasMobile: '',
        imgServer: util.imgServer,
        all: {
          icon: 'ct1',

          name: '全部订单',
          id: -1
        },
        orderList:[
          {
            icon: 'ct2',
            name: '待付款',
            id: 0
          },
          {
            icon: 'ct3',
            name: '待发货',
            id: 201
          },
          {
            icon: 'ct4',
            name: '待收货',
            id: 300
          },
          {
            icon: 'ct5',
            name: '已完成',
            id: 301
          }
        ],
        barList:[
          {
            icon: 'cb1',
            url: '/pages/ucenter/collect/collect',
            name: '我的收藏',
            id: 0
          },
          {
            icon: 'cb5',
            url: '/pages/coupon/coupon',
            name: '优惠券',
            id: 5
          },
          // {
          //   icon: 'cb6',
          //   url: '/pages/ucenter/footprint/footprint',
          //   name: '我的积分',
          //   id: 1
          // },
          {
            icon: 'cb2',
            url: '/pages/ucenter/address/address',
            name: '地址管理',
            id: 1
          }
        ],
        relatedGoods: [],
        isLogin: app.globalData.isLogin

    },
    getGoodsRelated: function () {
      let that = this;
      util.request(api.GoodsRelated, {}).then(function (res) {
        if (res.errno === 0) {
          that.setData({
            relatedGoods: res.data.goodsList,
          });
        }
      });
    },

  

  tapByIdx:function(e){
    let {
      url
    } = e.currentTarget.dataset;

    console.log(app.globalData)

    // if (this.data.isLogin) {
      wx.navigateTo({
        url: url,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    // } else {

    //   wx.navigateTo({
    //     url: '/pages/auth/btnAuth/btnAuth',
    //   })
    //   // wx.showModal({
    //   //   title: '提示',
    //   //   content: '请登录后查看',
    //   //   showCancel: false,
    //   //   confirmColor: '#ED5D18',
    //   //   success: res=>{

    //   //   }
    //   // });
    // }

  },
  onLoad: function (options) {
      getApp().checkNetStatu();
      // 页面初始化 options为页面跳转所带来的参数
      // this.getGoodsRelated()
      
      // wx.setNavigationBarColor({
      //   frontColor:'#ffffff',
      //   backgroundColor:'#fb6400',
      //   "navigationStyle":"custom"
      //   animation: {
      //     duration: 400,
      //     timingFunc:'easeIn'
      //   }
      // })
    },
    onReady: function () {

    },
    async getCounts() {
      let { data } = await util.request(api.OrderCount)
      let orderList = this.data.orderList.map(item => {
        let ci = data.find(({code}) => code === item.id)
        if (ci) {
          item.count = ci.num > 99 ? '..' : ci.num
        }
        return { ...item }
      })

      this.setData({ orderList })
    },
    async getUserInfo() {
      const {data} = await util.request(api.UserInfo)
      wx.setStorageSync('userinfoDetail', data)
      this.setData({
        userInfo: {
          nickName: data.nickname,
          avatarUrl: data.avatar,
        }
      })
    },
    async getBrandList () {
      let res = await util.request(api.GetAdminBrands)
      let list = res.data
      if (list && list.length>0) {
        this.setData({
          hasBrand: true
        })
      } else {
        this.setData({
          hasBrand: false
        })
      }
    },
    onShow: function () {
      getApp().updateCardCount()
      let userInfo = wx.getStorageSync('userInfo');
      let token = wx.getStorageSync('token');
      this.getBrandList()
      this.getUserInfo()
      this.getCounts()
      // 页面显示
      if (userInfo && token) {
          app.globalData.userInfo = userInfo;
          app.globalData.token = token;
      }

      this.setData({
        // userInfo: app.globalData.userInfo,
        token: app.globalData.token
      });

      util.request(api.CartList).then((res) => {
        let isLogin = false
        if (res.errno === 401) {
          isLogin = false
          app.globalData.userInfo = tempUserInfo;
          app.globalData.token = '';
        } else {
          isLogin = true
          app.globalData.userInfo = userInfo;
          app.globalData.token = token;
        }
        if (!isLogin){
          this.setData({
            token:'',
            userInfo: tempUserInfo
          });
        }
        this.setData({
          isLogin
        });
      });

      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 3
        })
      }

    },
    onPullDownRefresh() {
      getApp().onPullDownRefresh()
    },
    onHide: function () {
        // 页面隐藏

    },
    onUnload: function () {
        // 页面关闭
    },
    bindGetUserInfo(e) {
      let userInfo = wx.getStorageSync('userInfo');
      let token = wx.getStorageSync('token');
      if (userInfo && token) {
        return;
      }
        if (e.detail.userInfo){
            //用户按了允许授权按钮
            user.loginByWeixin(e.detail).then(res => {
                this.setData({
                    userInfo: res.data.userInfo,
                    isLogin: true
                });
                res.data.userInfo.userId = res.data.userId
                res.data.userInfo.isAdmin = res.data.isAdmin
                wx.setStorageSync('userInfo', res.data.userInfo);
                wx.setStorageSync('token', res.data.token);
                wx.setStorageSync('userId', res.data.userId);
                app.globalData.userInfo = res.data.userInfo;
                app.globalData.token = res.data.token;
            }).catch((err) => {
              this.setData({
                token: '',
                userInfo: tempUserInfo
              });
              app.globalData.userInfo = tempUserInfo;
              app.globalData.token = '';
              console.log(err)
            });
        } else {
            //用户按了拒绝按钮
            // wx.showModal({
            //     title: '温馨提示',
            //     content: '您点击了"取消"授权,将无法获取杭州天门科技有限公司完整服务。请“授权”以保证各项功能正常使用。',
            //     confirmText:'授权',
            //     success: function (res) {
            //         if (res.confirm) {
            //             wx.openSetting({
            //                 success: (res) => {
            //                     if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
            //                         user.loginByWeixin(e.detail).then(res => {
            //                             this.setData({
            //                                 userInfo: res.data.userInfo
            //                             });
            //                             app.globalData.userInfo = res.data.userInfo;
            //                             app.globalData.token = res.data.token;
            //                         }).catch((err) => {
            //                             console.log(err)
            //                         });
            //                     }
            //                 }
            //             })
            //         }
            //     }
            // });
        }
    },
    exitLogin: function () {
        wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            content: '退出登录？',
            success: function (res) {
                if (res.confirm) {
                    wx.removeStorageSync('token');
                    wx.removeStorageSync('userInfo');
                    wx.switchTab({
                        url: '/pages/index/index'
                    });
                }
            }
        })

    },
    toReport () {
      wx.navigateTo({
        url: '/dataReport/pages/data-report/data-report',
      })
    }
})