import { getTenementDetail } from "../../service/tenement";
import { userApply } from "../../service/user";
import { alertInfo, alertSuccess, loadingFunc, wxLogin } from "../../utils/index";
import request from '../../utils/request'
const { OK } = request;
// pages/apply/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    tenement: {},
    nickName: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const querys = decodeURIComponent(options.scene)
    const id = querys.slice(querys.indexOf("=") + 1)
    this.getInfo(id);
  },
  async getInfo(id) {
    const { code, message, data } = await getTenementDetail(id);
    if (code !== OK) {
      alertInfo(message)
      return
    }
    this.setData({
      tenement: data,
      id
    })
  },
  exit() {
    wx.exitMiniProgram()
  },
  onChangeName(e) {
    this.setData({
      nickName: e.detail
    })
  },
  async handleLogin(phoneCode) {
    const { id, nickName } = this.data;
    loadingFunc(async () => {
      const wxLoginCode = await wxLogin()
      const result = await userApply({ code: wxLoginCode, phoneCode, id, name: nickName })
      const { code, message, data } = result;
      if (code !== OK) {
        alertError(message)
        return
      }
      if (!data?.id) {
        this.noPermission()
        return;
      }
      alertSuccess("登录成功")
      const { token, ...user } = data
      wx.setStorageSync('user', user)
      wx.setStorageSync('token', data?.token)
      wx.switchTab({
        url: '/pages/home/index',
      })
    })
  },
  getPhoneNumber(e) {
    const { nickName } = this.data;
    if (!nickName) {
      alertInfo("请填写你的名字")
      return;
    }
    const { errno, code: phoneCode } = e.detail;
    switch(errno) {
      case 103:
        alertInfo("已拒绝");
        
        return;
      case 1400001:
        alertInfo("服务达到上限")
        return;
      default:
        this.handleLogin(phoneCode)
        return;
    }
  },
  async join() {
    const { id } = this.data;
    const { code, message, data } = await userApply({ id })
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    alertSuccess("加入成功")
    const { token, ...currentUser } = data;
    wx.setStorageSync('user', currentUser)
    wx.setStorageSync('token', token)
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/home/index',
      })
    }, 500)
  },
})