import { getLocal, changSaveLocal } from "@/util/localUtil";
import { ref, watchEffect } from "vue";
import {
  PaggingReq,
  PaggingRes,
  axios,
  changeUserStatus as changeUserStatusUrl,
  deleUser,
  getSWToken,
  getUserList,
  getUserListSelect,
  sendUserMsg,
  setAuthHook,
  updatePsw,
  userAdd,
  userEdit,
  userLogout,
  userReg,
} from "@/request/index";
import { QuoteScene } from "./scene";
import { encodePwd } from "@/util";
import { countdownFactory } from "@/hook/countdown";
import { appConstant } from "@/app";

export type UserInfo = {
  avatar: string;
  deptId: string;
  deptName: string;
  id: string;
  deptLevel: number;
  departmentId: string;
  cameraSns: string[];
  status: 1 | 0;
  isAdmin: 1 | 0;
  permsList: string[];
  nickName: string;
  roleId: string;
  password: string;
  userName: string;
};

type Params = Pick<UserInfo, "nickName" | "status" | "userName"> & {
  deptId: string;
};
export const getUserPagging = async (params: PaggingReq<Params>) =>
  (await axios.get<PaggingRes<UserInfo>>(getUserList, { params })).data;

export const getUsers = async (deptId?: string) =>
  (await axios.get<UserInfo[]>(getUserListSelect, { params: { deptId } })).data;
// 当前用户的信息

export const user = ref({
  token: getLocal(`${appConstant.deptId}Token`, ""),
  info: getLocal("info", {} as UserInfo),
});

export const logout = async () => {
  await axios.post(userLogout);
  user.value.token = "";
  user.value.info = {} as any;
};

type UpdataPassowrdParams = {
  userName: string;
  code: string;
  password: string;
};
export const updatePassword = async (params: UpdataPassowrdParams) => {
  const password = encodePwd(params.password);
  await axios.post(updatePsw, {
    ...params,
    password,
    confirmPwd: password,
  });
};

type RegisterParams = Pick<
  UserInfo,
  "deptId" | "userName" | "nickName" | "password"
> & {
  code: string;
};
export const register = async (params: RegisterParams) => {
  const password = encodePwd(params.password);
  await axios.post(userReg, {
    ...params,
    password,
    confirmPwd: password,
  });
};

export const addUser = async (
  params: Omit<UserInfo, "id">,
  deptPath: string[]
) => {
  await axios.post(userAdd, {
    ...params,
    deptIdList: deptPath.join(","),
  });
};

export const setUser = async (params: UserInfo, deptPath: string[]) => {
  await axios.post(userEdit, {
    ...params,
    deptIdList: deptPath.join(","),
  });
};

export const delUser = (id: string) => axios.post(deleUser, { id });

export const changeUserStatus = (user: UserInfo) =>
  axios.post(changeUserStatusUrl, {
    status: Number(!user.status),
    id: user.id,
  });

// 发送手机验证码
export { CountdownStuts } from "@/hook/countdown";
export type { CountdownStore } from "@/hook/countdown";
const countdownStore = countdownFactory(60, "phoneCode");
export const sendPhoneCode = async (phone: string) => {
  await countdownStore.set(phone, () =>
    axios.get(sendUserMsg, {
      params: {
        areaNum: 86,
        phoneNum: phone,
        type: 2,
      },
    })
  );
  return countdownStore.get(phone);
};

export const transformSWToken = async (scene: QuoteScene) => {
  const res = await axios.get(getSWToken, { params: { num: scene.num } });
  return res.data.token;
};

changSaveLocal(`${appConstant.deptId}Token`, () => user.value.token);
changSaveLocal("info", () => user.value.info);

// 设置全局请求hook
setAuthHook(() => {
  return {
    token: user.value.token,
    userId: user.value.info.id,
    clear: () => {
      user.value = {
        token: "",
        info: {} as UserInfo,
      };
    },
  };
});
