import { getUserInfo, setWxAuthUserInfo, getThirdInfo, createAccount, changePhone } from '@/api/user.js';
import store from '@/store';
import config from '@/config';
import { login, getCompanyByPhone, refreshToken, getUserControlSpace } from '@/api/user.js';
import utils from '@/common/utils.js';
//  定时检查用户信息并且续约-进入页面默认传0
function checkHasUserInfo() {
  let timer = setTimeout(() => {
    let token = store.state.user.token
    let tokenInfo = store.state.user.tokenInfo;
    let expireTime = tokenInfo.expireTime;
    let refreshTokenExpireTime = tokenInfo.refreshTokenExpireTime;
    let nowtime = utils.getTimeStamp();
    let refreshTokenValue = tokenInfo && tokenInfo.refreshToken ? tokenInfo.refreshToken : '';
    if (token && refreshTokenValue && expireTime && refreshTokenExpireTime >= nowtime) {  // 过期可续约
      let minute = (parseInt(expireTime - nowtime) / 1000 / 60);
      console.log(minute);
      if (minute < 20) {
        refreshTokenPage().then(() => {
          clearTimeout(timer);
          checkHasUserInfo(600000);
        });
      } else {
        clearTimeout(timer);
        checkHasUserInfo(600000);
      }
    } else {
      clearTimeout(timer);
      checkHasUserInfo(600000);
    }
  }, 600000)
}

// 登录
function wxLogin (type) {
  console.log("执行了登录")
  // type=1 如果type未激活和作废不需要跳转到登录页面
  return new Promise((resolve, reject) => {
    wx.login({
      success (wxLoginRes) {
        const jsCode = wxLoginRes.code;
        console.log(utils)
        const appId = utils.getAppId();
        if (jsCode) {
          let params = {
            "appId": appId,
            "wxCode": jsCode
          }
          login(params).then(res => {
            if (res.result == 'success') {
              let data = res.data || []
              let tokenInfo = {
                expireTime: data.expireTime,
                startTime: data.startTime,
                refreshTokenExpireTime: data.refreshTokenExpireTime,
                refreshToken: data.refreshToken
              };
              store.commit('setToken', data.token);
              store.commit('setActivated', data.isActivated);
              store.commit('setTokenInfo', tokenInfo);
              if (data.isActivated && data.isActivated == 1) {
                store.commit('setUserInfo', data.tokenUser);
                // store.commit('setProjectId', data.tokenUser.projectId);
              } else {
                if (!type) {
                  refreshLogin()
                }
                store.commit('setUserInfo', {});
              }
              resolve(data)
            } else {
              reject('login接口返回fail');
            }
          })
        } else {
          wx.showToast({
            title: `网络异常, 请稍后重试`,
            icon: 'none',
            duration: 5e3
          });
          reject('wx.login接口返回code为空');
        }
      },
      fail(res) {
        reject(res);
        wx.showToast({
          title: `网络异常, 请稍后重试`,
          icon: 'none',
          duration: 5e3
        });
      }
    });
  });
}

// 获取租户信息
function getCompanyDataByPhone() {
  return new Promise((resolve, reject) => {
    let userInfo = store.state.user.userInfo;
    let userPhone = userInfo.phone || wx.getStorageSync('userPhone');
    let params = {
      phone: userPhone
    }
    if (userPhone) {
      getCompanyByPhone(params).then(res => {
        let data = res.data || []
        resolve(data)
      }).catch(() => {
        reject({
          mesg: '获取租户数据异常'
        })
      })
    } else {
      reject({
        mesg: '无法获取手机号信息,跳转到首页'
      })
    }

  });
}

// 登录续约
function refreshTokenPage() {
  return new Promise((resolve, reject) => {
    let storeTokenInfo = store.state.user.tokenInfo
    let refreshTokenValue = storeTokenInfo && storeTokenInfo.refreshToken ? storeTokenInfo.refreshToken : '';
    refreshToken(refreshTokenValue).then(res => {
      if (res.result == 'success') {
        let data = res.data || []
        let tokenInfo = {
          expireTime: data.expireTime,
          startTime: data.startTime,
          refreshTokenExpireTime: data.refreshTokenExpireTime,
          refreshToken: data.refreshToken
        };
        console.log(data);
        store.commit('setToken', data.token);
        store.commit('setActivated', data.isActivated);
        store.commit('setTokenInfo', tokenInfo);
        if (data.isActivated && data.isActivated == 1) {
          store.commit('setUserInfo', data.tokenUser);
          resolve(data)
        } else {
          store.commit('clearToken', '');
          // 去登录页面
          refreshLogin()
          resolve(data)
        }
      } else {
        store.commit('clearToken', '');
        refreshHome();
        reject("续约失败!")
      }
    }).catch(() => {
      store.commit('clearToken', '');
      refreshHome();
      reject("续约失败!")
    })
  })
}

// 刷新首页
function refreshHome() {
  // wx.redirectTo({ url: '/pages/index' });
  wx.redirectTo({ url: '/packagesEnv/pages/home/index' });
}
function refreshLogin() {
  wx.redirectTo({ url: '/pages/index' });
  // wx.redirectTo({ url: '/packagesEnv/pages/home/index' });
}
// 检查用户是否有空间控制权限
function checkUserControl() {
  return new Promise((resolve, reject) => {
    let userInfo = store.state.user.userInfo;
    if (userInfo && userInfo.userId) {
      let params = {
        "criteria": {
          "projectId": userInfo.projectId,
          "companyId": userInfo.companyId,
          "userCode": userInfo.userId
        }
      }
      getUserControlSpace(params).then(res => {
        // console.log("返回用户权限数据")
        // console.log(res)
        if (res.result == 'success') {
          let data = res.data || {}
          if (data && JSON.stringify(data) != '{}') {
            if (data.isControlSpace !== 1) {
              resolve(data)
            } else {
              reject("租户下无可控空间");
              refreshHome();
            }

          } else {  // 如果无权限和楼层数据返回跳转到首页,不让点击
            reject("获取租户权限接口失败");
            refreshHome();
          }
        } else {
          reject("获取租户权限接口失败");
          refreshHome();
        }
      }).catch((error) => { // 如果无权限和楼层数据返回跳转到首页,不让点击
        reject("获取租户权限接口失败");
        refreshHome();
      })
    } else {
      reject("用户未登录");
    }
  })
}

// 登录续约逻辑-待处理
function checkLoginNew() {
  return new Promise((resolve, reject) => {
    let token = store.state.user.token;
    let storeTokenInfo = store.state.user.tokenInfo
    let refreshToken = storeTokenInfo && storeTokenInfo.refreshToken ? storeTokenInfo.refreshToken : '';
    console.log("执行checkLoginNew--", token, refreshToken);
    console.log("执行checkLoginNew--");
    if (!token || !refreshToken) {
      wxLogin().then((res) => {
        resolve(res)
      }).catch((error) => {
        reject("登录失败!");
      });
    } else {
      let flag = checkTokenIsValid();
      console.log("flag==", flag);
      if (flag == 1) {  // 续约
        refreshTokenPage().then(res => {
          resolve(res)
        }).catch((error) => {
          reject("续约失败!");
        });
      } else if (flag == 2) { // 重新登录
        wxLogin().then((res) => {
          resolve(res)
        }).catch((error) => {
          reject("登录失败!");
        });
      } else if (flag == 3) {  // 未过期
        resolve({
          isActivated: store.state.user.isActivated
        })
      }
    }
  })
}

// 判断token是否过期
function checkTokenIsValid() {
  let flag = 1
  let tokenInfo = store.state.user.tokenInfo;
  let expireTime = tokenInfo.expireTime;
  let refreshTokenExpireTime = tokenInfo.refreshTokenExpireTime;
  let nowtime = utils.getTimeStamp();
  if (expireTime && expireTime <= nowtime && refreshTokenExpireTime >= nowtime) {  // 过期可续约
    flag = 1
  } else if (expireTime && expireTime >= nowtime) { //未过期
    let minute = (parseInt(expireTime - nowtime) / 1000 / 60)
    if (minute <= 20) {
      flag = 1
    } else {
      flag = 3
    }
  }
  else { // 需要重新登录
    flag = 2
  }
  return flag;
}


// 本地保存用户头像
function setAvatar(avatar) {
  wx.setStorageSync('avatarBase64', avatar);
}
// 获取头像
function getAvatar() {
  return wx.getStorageSync('avatarBase64');
}

// 清楚数据
function clearAvatar() {
  wx.removeStorage('avatarBase64');
}


export {
  checkHasUserInfo,
  wxLogin,
  setAvatar,
  getAvatar,
  checkLoginNew,
  checkTokenIsValid,
  getCompanyDataByPhone,
  checkUserControl,
  refreshTokenPage
}