import { Apis } from "@/gen/Apis";
import { defineStore } from "pinia";
import { ref } from "vue";
import { getApiLoading } from "../libraries/apiLoading";
import { setTabBar } from "../libraries/setTabBar";

type DataType = {
  user?: {
    id: number;
    username: string;
  };
  orgs?: { id?: number; name?: string }[];
  selectedOrg?: { id?: number; name?: string; is_show_procedure?: number };
};

export const useWeAppAuthStore = defineStore("we_app_auth", () => {
  const loading = ref<boolean>(true);
  const hasError = ref<boolean>(false);
  const data = ref<DataType>({
    user: { id: 0, username: "" },
  });

  function login(app: any) {
    uni.login({
      provider: "weixin", //使用微信登录
      success: function (loginRes) {
        console.log(loginRes.code)
        return false
        Apis.Login.Auth.Login({ code: loginRes.code })
          .then((res) => {
            console.log("登录", res?.data);
            data.value.user = res.data?.user;
            loading.value = false;
            uni.setStorageSync(
              import.meta.env.VITE_ACCESS_TOKEN_KEY,
              res?.data?.token?.token
            );
            app?.appContext.config.globalProperties.$isResolve();
            if (!res.data?.user) {
              //未绑定账号
              uni.redirectTo({
                url: "/pages/login",
              });
              return false;
            }
          })
          .catch(() => {
            loading.value = false;
            hasError.value = true;
          });
      },
    });
  }

  function me() {
    getApiLoading(Apis.Login.Auth.Me, {}).then((res) => {
      data.value.user = res.data.user;
      console.log("me", res.data);
      loading.value = false;
      hasError.value = false;
    });
  }

  const handleUserLogin = async (from_data: {
    username: string;
    password: string;
  }) => {
    getApiLoading(Apis.Login.Auth.BindPhoneNumber, from_data).then((res) => {
      me();
    });
  };

  return {
    loading,
    hasError,
    data,
    login,
    me,
    handleUserLogin,
  };
});
