import { defineStore } from 'pinia';
import { getBaseInfo, getUserInfo } 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 { updateEventList } from '@/utils/eventList'
import { checkPersonBaseInfo } from '@/utils/check'

// 默认用户信息
const defaultBaseInfo = {
  avatar: '', // 头像
  nickname: '', // 昵称
  gender: 0, // 性别
  mobile: '', // 手机号
  point: 0, // 积分
};

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

const tabUrl = [
  'pages/index/position',
  'pages/index/communicate',
  'pages/index/my'
]
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 }, // 账号信息
    }
  },

  actions: {
    setLogin (val) {
      this.isLogin = val
    },
    // 登录
    async handleSmsLogin (query, index = 0) {
      this.phone = query.phone
      const apiList = [weChatLogin, smsLogin, passwordLogin] 
      const { data, code } = await apiList[index](query)
      if (code === 0) {
        uni.showToast({
          title: '登录成功'
        })
      }
      this.accountInfo = data
      const res = await this.getInfo()
      this.getUserInfo()
      return Promise.resolve(res);
    },

    async handleRegister (query) {
      this.phone = query.phone
      const { data, code } = await userRegister(query)
      if (code === 0) {
        uni.showToast({
          title: '注册成功'
        })
      }
      this.accountInfo = data
      const res = await this.getInfo()
      this.getUserInfo()
      return Promise.resolve(res);
    },
    // 扫码注册登录
    async handleShareUserRegister (query) {
      try {
        this.phone = query.phone
        const { data, code } = await shareUserRegister(query)
        if (code === 0) {
          uni.showToast({
            title: '登录成功'
          })
          this.accountInfo = data
          await this.getInfo()
          this.getUserInfo()
        }
        return Promise.resolve(data);
      } catch (err) {
        uni.showToast({
          icon: 'none',
          title: err.msg
        })
      }
    },

    // 校验是否完善人才必填信息
    checkPersonBaseInfoFun(data) {
      data = data || {}
      const necessaryInfoReady = checkPersonBaseInfo(data)
      data.necessaryInfoReady = necessaryInfoReady
      if (necessaryInfoReady) closeAuthModal()
      else showAuthModal('necessaryInfo')
      uni.setStorageSync('necessaryInfoReady', necessaryInfoReady ? 'ready' : 'fddeaddc47868b');
    },

    // 获取人才信息
    async getInfo() {
      const { code, data } = await getBaseInfo({ userId: this.accountInfo.userId });
      updateEventList() // 更新事件列表
      await this.checkPersonBaseInfoFun(data) // 校验是否完善人才必填信息
      if (code !== 0) {
        return;
      }
      if (!data) return
      const _data = await this.getFieldText(data)
      this.baseInfo = _data
      return Promise.resolve(data);
    },
    // 获取用户信息
    async getUserInfo() {
      const { code, data } = await getUserInfo({ id: this.accountInfo.userId });
      if (code !== 0) {
        return;
      }
      this.userInfo = 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;

      // 获取最新信息
      return this.baseInfo;
    },

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

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

    // 登出系统
    async handleLogout() {
      await logout()
      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: {
    // enabled: true,
    // strategies: [
    //   {
    //     key: 'user-store'
    //   }
    // ]
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },
      getItem(key) {
        return uni.getStorageSync(key)
      },
    },

  }
})