import { userDetail, timestamp } from "../requests/user";
import { formatBirthday, formatSeconds, formatTime } from "./index";
import utils from "./index";
import user_store from '../store/index'


//刷新用户信息
export function reload_userinfo($this) {
  wx.showLoading({
    title: '加载中',
    mask: true
  }),
    setTimeout(function () {
      wx.hideLoading()
    }, 4000)
  let $errcode = [
    1001, 1002, 1011, 1012, 1021, 1031
  ]
  userDetail().then((res) => {
    let _data = res.data.data.validity_time;
    console.log("有效时间：" + _data);

    let $data = res.data;
    if ($errcode.indexOf($data.code) != -1) {
      do_logout($this)
    }
    // if ($this.userinfo['validity_time'] != -1) {
    //   do_logout($this)
    // }
    $this.userinfo = $data.data;
    // 联名活动要用
    wx.setStorageSync("phone", $this.userinfo.phone);
    $this.userinfo.birthday = formatBirthday($this.userinfo.birthday)
    // $this.userinfo['validity_unformattedTime'] = $this.userinfo['validity_time']
    $this.userinfo['validity_time_formatted'] = formatTime($this.userinfo['validity_time'])

    let nowTime = timestamp()
    //判断是否过期
    if ($this.userinfo['level'] == 11) {
      if (nowTime > $this.userinfo['validity_time']) {
        $this.userinfo.isActive = false
        $this.userinfo.isntActive = true
      } else {
        $this.userinfo.isActive = true
        $this.userinfo.isntActive = false
      }

    } else {
      $this.userinfo.isActive = true
      $this.userinfo.isntActive = false
    }

    // $this.userinfo['validity_time'] = formatTime($this.userinfo['validity_time'])
    $this.userinfo['free_time'] = formatSeconds($this.userinfo['free_time'])
    //设置邀请码
    user_store.setters.set_invite_code($this.userinfo['invite_id'])
    $this.invite_code = wx.getStorageSync('code') ? wx.getStorageSync('code') : $this.userinfo['invite_id']
    user_store.setters.set_userinfo($this.userinfo)
    //停止下拉刷新
    wx.stopPullDownRefresh()
    wx.hideLoading()
  }).catch((err)=>{
    // do_logout($this);
    wx.showToast({
      title: "获取用户信息失败",
      icon: 'none',
      mask: true,
    })
  })
}

function do_logout($this) {
  $this.is_login = false
  wx.showToast({
    title: "用户信息过期,请重新登录",
    icon: 'none',
    mask: true,
    success() {
      wx.clearStorageSync()
      wx.setStorageSync('is_login', false)
      mpvue.reLaunch({
        url: "/pages/index/main"
      })
      try {
        $this.change_login_status()
      } catch
      (e) {
        console.log(e)
      }
    }
  })
}

export default {
  do_logout
}
