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';

// 检查登录
function checkLogin(needGetetUserInfo = true) {
  let token = store.state.user.token;
  if (!token) {
    return wxLogin(needGetetUserInfo);
  } else {
    return Promise.resolve();
  }
}

//  检查用户信息
function checkHasUserInfo() {
  let userInfo = store.state.user.userInfo;
  if (userInfo && JSON.stringify(userInfo) !== '{}') {
    return Promise.resolve(userInfo);
  } else {
    // return checkLogin(false).then(() => {
    //   return getUserData();
    // })
    wxLogin();
  }
}

function setUserInfoByAuth() {
  return new Promise((resolve, reject) => {
    // if (ing) {
    //   return;
    // }
    // ing = true;
    // let { userInfo = {} } = store.state.user;
    // // 如果已经保存过了
    // let nickName = userInfo.nickName;
    // if (nickName) {
    //   ing = false;
    //   resolve();
    //   return;
    // }
    wx.getUserProfile({
      desc: '用于完善用户信息',
      success: res => {
        let detail = res;
        wx.login({
          success: loginRes => {
            // ing = false;
            // if (loginRes.code) {
            //   let params = {
            //     encryptedData: detail.encryptedData,
            //     iv: detail.iv,
            //     jsCode: loginRes.code
            //   };
            //   setWxAuthUserInfo(params).then(res => {
            //     let userInfo = JSON.parse(detail.rawData);
            //     let cachedInfo = wx.getStorageSync('UserInfo');
            //     userInfo = {
            //       ...cachedInfo,
            //       ...userInfo,
            //       headImgUrl: userInfo.avatarUrl
            //     };
            //     delete userInfo.avatarUrl;
            //     store.commit('setUserInfo', {
            //       ...userInfo
            //     });
            //     wx.setStorageSync('UserInfo', { ...userInfo });
            //     resolve(res.data);
            //   });
            // }
          },
          fail: res => {
            // ing = false;
            // reject(res);
          }
        });
      },
      fail: res => {
        // ing = false;
        // wx.showToast({
        //   icon: 'none',
        //   title: '授权用户公开信息后方可进入下一步操作'
        // });
        // reject();
      }
    });
  });
}

// 登录
function wxLogin(type) {
  // 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) {
                  wx.redirectTo({ url: '/pages/index' });
                }
                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 userPhone = wx.getStorageSync('userPhone');
    let userInfo = store.state.user.userInfo;

    console.log("userInfo==",userInfo)
    if (!userPhone) {
      userPhone = userInfo.phone
    }
    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) => {
    refreshToken().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);
          resolve(data)
        } else {
          store.commit('setToken', '')
          // store.commit('setUserInfo', {});
          wx.redirectTo({ url: '/pages/index' });
          resolve(data)
        }
      }
    }).catch(() => {
      resolve("续约失败")
      store.commit('setToken', '')
      wx.redirectTo({ url: '/pages/index' });
      // store.commit('setUserInfo', {});
      // wxLogin()
    })
  })

}

// 刷新首页
function refreshHome() {
  // wx.redirectTo({ url: '/pages/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;
    if (!token) {
      wxLogin().then((res) => {
        resolve(res)
      });
    } else {
      let flag = checkTokenIsValid()
      if (flag == 1) {
        refreshTokenPage().then(res => {
          resolve(res)
        }); // 续约
      } else if (flag == 2) { // 重新登录
        wxLogin().then((res) => {
          resolve(res)
        });
      } else if (flag == 3) {  // 后续补定时器定时续约逻辑
        resolve({
          isActivated: 1
        })
      }
    }
  })
}

// 判断token是否过期
function checkTokenIsValid() {
  let flag = 1
  let tokenInfo = store.state.user.tokenInfo;
  let expireTime = tokenInfo.expireTime;
  let refreshToken = tokenInfo.refreshToken;
  let nowtime = utils.getTimeStamp();
  if (expireTime && expireTime < nowtime && refreshToken >= nowtime) {  // 过期可续约
    flag = 1
  } else if (expireTime && expireTime >= nowtime) { // 没过期
    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,
  setUserInfoByAuth
}