import { defineStore } from 'pinia';
import { getBaseInfo, getUserInfo, getUserAccountInfo } from '@/api/user';
import { smsLogin, passwordLogin, weChatLogin, logout, userRegister, shareUserRegister } from '@/api/common'
import { closeAuthModal, showAuthModal } from '@/hooks/useModal'
import { timesTampChange } from '@/utils/date'
import { getBaseInfoDictOfName } from '@/utils/getText'
import { userLogout } from '@/api/common';

// 默认账户信息
const defaultAccountInfo = {
  accessToken: '',
  expiresTime: '',
  openid: '',
  refreshToken: '',
  userId: ''
}

export const userStore = defineStore('user', {
  state: () => {
    const userLocal = uni.getStorageSync('user')

    const userInfo = userLocal ? JSON.parse(userLocal) : {}
    return {
      phone: null,
      baseInfo: userInfo.baseInfo ?? {}, // 用户信息
      userInfo: userInfo.userInfo ?? {},
      isLogin: !!uni.getStorageSync('token'), // 登录状态
      refreshToken: uni.getStorageSync('refresh-token'), // 用户切换
      lastUpdateTime: 0, // 上次更新时间
      accountInfo: { ...defaultAccountInfo }, // 账号信息
      userAccountInfo: userInfo.userAccountInfo ?? {}, // 账户信息
    }
  },

  actions: {
    setLogin (val) {
      this.isLogin = val
    },
    // 登录
    async handleSmsLogin (query, index = 0, isGetData = true) {
      this.phone = query.phone
      const apiList = [smsLogin, passwordLogin] 
      const { data, code } = await apiList[index](query)
      if (code === 0) {
        uni.showToast({
          title: '登录成功'
        })
      }
      this.accountInfo = data

      // 企业注册-审核被拒绝-重新提交-效验手机号不需要获取用户信息
      if (!isGetData) return

      this.getUserInfos()
      this.getAccountInfo()
    },

    async handleRegister (query) {
      this.phone = query.phone
      const { data, code } = await smsLogin(query)
      if (code === 0) {
        uni.showToast({
          title: '手机号验证成功'
        })
      }
      this.accountInfo = data
      closeAuthModal()
    },
    // 获取用户信息
    async getUserInfos() {
      const { code, data } = await getUserInfo();
      if (code !== 0) {
        return;
      }
      this.userInfo = data;
      return Promise.resolve(data);
    },
    // 获取账户信息
    async getAccountInfo () {
      const { code, data } = await getUserAccountInfo();
      if (code !== 0) {
        return;
      }
      this.userAccountInfo = data;
      return Promise.resolve(data);
    },
    // 设置 token
    setToken(token = '', refreshToken = '') {
      if (token === '') {
        this.isLogin = false;
        this.refreshToken = ''
        uni.removeStorageSync('token');
        uni.removeStorageSync('refresh-token');
      } else {
        this.isLogin = true;
        uni.setStorageSync('token', token);
        this.refreshToken = refreshToken
        uni.setStorageSync('refresh-token', refreshToken);
        this.loginAfter();
      }
      return this.isLogin;
    },

    // 更新用户相关信息 (手动限流，5 秒之内不刷新)
    async updateUserData() {
      if (!this.isLogin) {
        this.resetUserData();
        return;
      }
      // 防抖，5 秒之内不刷新
      const nowTime = new Date().getTime();
      if (this.lastUpdateTime + 5000 > nowTime) {
        return;
      }
      this.lastUpdateTime = nowTime;
    },

    // 重置用户默认数据
    resetUserData() {
      // 清空 token
      this.setToken();
      // 清空用户相关的缓存
      this.userInfo = {}
      this.phone = ''
      this.userAccountInfo = {}
      this.accountInfo = { ...defaultAccountInfo };
    },

    // 登录后，加载各种信息
    async loginAfter() {
      await this.updateUserData();
    },

    // 登出系统
    async handleLogout() {
      await logout(uni.getStorageSync('token'))
      this.resetUserData();
      return !this.isLogin;
    },
    // 账号注册-回到首页
    async handleUserLogout () {
      await userLogout()
      this.resetUserData()
      return !this.isLogin
    },
    // 字典对应中文
    async getFieldText (data) {
      if (!data || !Object.keys(data).length) return {}
      if (data.birthday && data.birthday !== 0) {
        data.birthdayText = timesTampChange(data.birthday, 'Y-M-D') // 出生日期
      }
      if (data.firstWorkTime && data.firstWorkTime !== 0) {
        data.firstWorkTimeText = timesTampChange(data.firstWorkTime, 'Y-M-D') // 首次工作时间
      }
      if (data.areaId && data.areaId !== 0) {
        await getBaseInfoDictOfName(0, data, data.areaId, 'areaName') // 现居住地text
        await getBaseInfoDictOfName(0, data, data.regId, 'regName') // 户籍地text
      }
      if (data.eduType && data.eduType !== 0) {
        await getBaseInfoDictOfName(1, data, data.eduType, 'eduTypeText') // 学历
      }
      if (data.expType && data.expType !== 0) {
        await getBaseInfoDictOfName(2, data, data.expType, 'expTypeText') // 工作经验
      }
      if (data.sex && data.sex !== 0) {
        await getBaseInfoDictOfName(3, data, data.sex, 'sexTypeText') // 性别
      }
      if (data.jobType && data.jobType !== 0) {
        await getBaseInfoDictOfName(4, data, data.jobType, 'jobTypeText') // 求职类型
      }
      if (data.jobStatus && data.jobStatus !== 0) {
        await getBaseInfoDictOfName(5, data, data.jobStatus, 'jobStatusText') // 	求职状态
      }
      if (data.maritalStatus && data.maritalStatus !== 0) {
        await getBaseInfoDictOfName(6, data, data.maritalStatus, 'maritalText') // 	婚姻状况
      }
      return data
    }
  },
  persist: {
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },
      getItem(key) {
        return uni.getStorageSync(key)
      },
    },

  }
})