import { defineStore } from 'pinia';
import type { providerType, UserBean } from './types';
import { getTerminal, getUserProfile, login, logout as userLogout, register } from '@/api/user/index';
import { clearToken, setCompanyId, setToken } from '@/utils/auth';
import type { LoginResult, RegisterParams, TerminalBean } from '@/api/user/types';

const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {} as UserBean,
    terminalInfo: {} as TerminalBean
  }),

  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'userState',
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value); // [!code warning]
      },
      getItem(key) {
        return uni.getStorageSync(key); // [!code warning]
      }
    },
    // 部分持久化状态的点符号路径数组，[]意味着没有状态被持久化(默认为undefined，持久化整个状态)
    paths: undefined
  },

  getters: {
    // getUserInfo(state: UserState): UserState {
    //   return state.address;
    // }
  },

  actions: {
    // 设置用户的信息
    setUserInfo(partial: Partial<UserBean>) {
      this.userInfo = partial as UserBean;
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async getProfile() {
      const result = await getUserProfile();
      this.setUserInfo(result);
      await this.fetchTerminal();
    },

    userRegister(registerForm: RegisterParams) {
      return new Promise(async (resolve, reject) => {
        try {
          const result = await register(registerForm);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
    },

    // Logout
    async logout() {
      await userLogout();
      this.resetInfo();
      clearToken();
    },

    // 小程序授权登录
    authLogin(provider: providerType = 'weixin') {
      return new Promise((resolve, reject) => {
        uni.login({
          provider,
          success: async (result: UniApp.LoginRes) => {
            if(result.code) {
              const wechatUserInfo = await uni.getUserInfo();
              const userInfo = {
                ...wechatUserInfo.userInfo,
                encryptedData: wechatUserInfo?.encryptedData,
                rawData: JSON.parse(wechatUserInfo?.rawData),
                signature: wechatUserInfo?.signature,
                iv: wechatUserInfo.iv
              };

              const res = await login({
                code: result.code,
                userInfo: userInfo,
                referrerUserId: '1727303781559697409'
                // referrerUserId: '1731886841265598466'
              });

              if(res.user == undefined || res.user.id === null) {
                const registerForm = {
                  unionId: res.user.unionId,
                  openId: res.user.openId,
                  maOpenId: res.user.maOpenId,
                  image: res.user.image,
                  nickName: res.user.nickName,
                  telephone: res.user.telephone,
                  birthday: res.user.birthday,
                  companyId: res.user.companyId,
                  creatorId: res.user.creatorId,
                  gender: res.user.gender
                };
                const registerResult = await this.userRegister(registerForm);
                this.setUserInfo(registerResult as LoginResult);
                setToken(res.token);
                setCompanyId(res.user.companyId);
              } else {
                this.setUserInfo(res.user);
                setToken(res.token);
                setCompanyId(res.user.companyId);
              }
              resolve(res);
            } else {
              reject(new Error(result.errMsg));
            }
          },
          fail: (err: any) => {
            console.error(`login error: ${err}`);
            reject(err);
          }
        });
      });
    },

    async fetchTerminal() {
      this.terminalInfo = await getTerminal(this.userInfo.companyId);
    }
  }
});

export default useUserStore;
