import { defineStore } from "pinia";
import verConfig from "../ver.config";
import { LOGIN, GET_USERINFO, USER_STATICS, USERS_AUTH, USER_LOGOUT } from "@/api";
import { Toast, uniappStorage, removeStorage, setStorage, getStorage } from '@/utils'
import { useTabbarStore } from "./tabbar"
import { useSocketStore } from "./socket"
import { useMessageStore } from "./message"
import { useShopStore } from "./shop"

const state = () => ({
  getLoadingNum: 0,
  theme: verConfig.theme,
  userInfo: getStorage(verConfig.infoName) || {},
  token: getStorage(verConfig.tokenName) || '',
  statics: {},
  auth_id: '',
  is_seller: getStorage('is_seller') || 0
})

export const useUserStore = defineStore('user', {
  state,
  // persist: {
  //   enabled: true,
  //   strategies: [{
  //     key: verConfig.infoName,
  //     storage: uniappStorage,
  //     paths: ['userInfo']
  //   }, {
  //     key: verConfig.tokenName,
  //     storage: uniappStorage,
  //     paths: ['token']
  //   }]
  // },
  getters: {
    getNum() {
      return this.getLoadingNum;
    },
    getTheme() {
      return this.theme
    },
    getuserInfo() {
      return this.userInfo
    },
    getToken() {
      return this.token
    },
    getStatics() {
      return this.statics
    },
    getAuthId() {
      return this.auth_id
    },
    getUserType() {
      return this.is_seller
    }
  },
  actions: {
    login(params, isLogin = false) {
      return new Promise(async (resolve, reject) => {
        const useSocket = useSocketStore()
        try {
          LOGIN(params).then(res => {
            this.userInfo = res.data;
            this.token = res.data.token;
            setStorage(verConfig.tokenName, res.data.token);
            setStorage(verConfig.infoName, res.data);
            setStorage('is_seller', res.data.is_seller);
            this.setAuth({ id: res.data.id, socket_id: useSocket.socketId });
            const useTabbar = useTabbarStore();
            Toast(res.msg, 1000).then(() => {
              if (!isLogin) {
                let timer = setTimeout(() => {
                  const backUrl = getStorage('beforeLoginPage');
                  if (backUrl) {
                    removeStorage('beforeLoginPage');
                    const arr = ["/pages/index/index", "/pages/shop/cart", "/pages/community/index", "/pages/order/index", "/pages/user/index", "/pages/chat/index"];
                    const hasAny = arr.some(s => backUrl.includes(s));
                    if (hasAny) {
                      uni.switchTab({ url: backUrl });
                    } else {
                      uni.redirectTo({ url: backUrl });
                    }

                  } else {
                    uni.switchTab({ url: '/pages/index/index' });
                    useTabbar.getPageCur('index');
                  }
                  // uni.switchTab({ url: '/pages/index/index' });
                  // useTabbar.getPageCur('index');
                  clearTimeout(timer)
                }, 1000)
              }
            })
            resolve(res)
          }).catch(err => {
            Toast(err.msg)
            reject(err);
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    getUserInfo(params = {}, other = {}) {
      try {
        GET_USERINFO(params, other).then(res => {
          this.userInfo = res.data;
          this.token = res.data.token;
          setStorage(verConfig.tokenName, res.data.token);
          setStorage(verConfig.infoName, res.data);
          setStorage('is_seller', res.data.is_seller);
        })
      } catch (error) { }
    },
    setAuth({ id, socket_id }) {
      return new Promise(async (resolve, reject) => {
        const useSocket = useSocketStore()
        const useMessage = useMessageStore()
        try {
          const channel_name = `private-user-${id}`;
          const res = await USERS_AUTH({
            channel_name,
            socket_id,
            last_time: {
              service: getStorage("serviceChannel") ? getStorage("serviceChannel") : 0,
              notice: getStorage("noticeChannel") ? getStorage("noticeChannel") : 0,
            }
          })
          useSocket.send({
            event: "pusher:subscribe",
            data: res.data
          })
          for (let key in res.data.unread) {
            useMessage.updateGlobalMapUnreadCount(`${key}Channel`, res.data.unread[key])
          }
          useMessage.getTotalUnreadCount()
          resolve(res)
        } catch (error) {
          reject(error)
        }
      })
    },
    setTheme(_theme_) {
      this.theme = _theme_;
    },
    setloadingNum(_num_) {
      this.getLoadingNum = _num_;
    },
    loginOut(flag = false) {
      const useMessage = useMessageStore()
      const useShop = useShopStore()
      removeStorage(verConfig.infoName);
      removeStorage(verConfig.tokenName);
      removeStorage('userType'); // 清除用户类型存储
      this.userType = 1; // 重置为默认卖家类型
      USER_LOGOUT();
      useShop.setCartNum(0);
      useMessage.resetAllGlobalUnreadCount();
      // #ifdef APP-PLUS
      plus.runtime.setBadgeNumber(0);
      // #endif
      if (!flag) {
        uni.reLaunch({ url: '/pages/login/login' });
      }
    },
    async setStatics() {
      try {
        const res = await USER_STATICS();
        this.statics = res.data
      } catch (error) { }
    },
    setUserInfo(_userInfo_) {
      this.userInfo = _userInfo_;
      this.token = _userInfo_.token;
      setStorage(verConfig.tokenName, _userInfo_.token);
      setStorage(verConfig.infoName, _userInfo_);
    },
    setInitId(_auth_id) {
      this.auth_id = _auth_id
    },
    // 设置用户类型：1为卖家，0为买家
    setUserType(userType) {
      this.is_seller = userType;
      setStorage('is_seller', userType);
    }
  }
})