import {
  axios,
  userLogin,
  uploadFile as uploadFileUrl,
  userInfo,
} from "@/request";
import { encodePwd } from "@/util";
import { user } from "./user";
import { refreshRole } from "./role";
import { appConstant } from "@/app";
import { ref, watchEffect } from "vue";

export type LoginProps = {
  phoneNum: string;
  code: string;
  password: string;
};

export const title = ref(appConstant.title);
export const desc = ref(appConstant.desc);

watchEffect(
  () => (document.title = title.value + (desc.value ? " | " + desc.value : ""))
);

const refreshUserInfo = async (data: any) => {
  user.value.info = data;
  await refreshRole();
};

export const login = async (props: LoginProps) => {
  const res = await axios.post(userLogin, {
    ...props,
    deptId: appConstant.deptId,
    password: encodePwd(props.password),
  });
  user.value.token = res.data.token;
  refreshUserInfo(res.data.tmUser);
};

if (user.value.token) {
  axios.get(userInfo).then((res) => {
    refreshUserInfo(res.data);
  });
}

export const uploadFile = async (file: File) => {
  return (await axios.post<string>(uploadFileUrl, { file })).data;
};
