import { defineStore } from "pinia";
import { getCaUserInfo, caAuth, closeAutoSign, startAutoSign, autoSignVerifyCA } from "./ca-api";
import { ref } from "vue";
import message from "../../TUIKit/locales/en/message";
export const caStore = defineStore("ca", () => {
  async function getUserCaInfo() {
    const { data, success } = await getCaUserInfo({
      uniqueId: sessionStorage.getItem("uniqueId"),
    });
    if (success) {
      sessionStorage.setItem("caUserId", data.data.userId);
    }
  }
  async function getAuthCode() {
    const { success, data } = await caAuth({
      uniqueId: sessionStorage.getItem("uniqueId"),
    });
    if (success) {
      return data.data;
    } else {
      return false;
    }
  }
  async function enableAutoSign() {
    const res = await autoSignVerifyCA({
      code: sessionStorage.getItem("uniqueId"),
    });
    if (res.success) {
      return {
        success: false,
        message: "时效签名已开启",
      };
    }
    if (res.message === "用户不存在") {
      return {
        success: false,
        message: "用户不存在",
      };
    }
    const { success, data, message } = await startAutoSign({
      userId: res.data.userId,
    });
    if (success) {
      return {
        success: true,
        data: data.data,
        caTimeRegion: data.caTimeRegion,
      };
    } else {
      return {
        success: false,
        message,
      };
    }
  }
  async function disableAutoSign() {
    const res = await closeAutoSign({
      uniqueId: sessionStorage.getItem("uniqueId"),
    });
    return res;
  }

  return {
    getUserCaInfo,
    getAuthCode,
    disableAutoSign,
    enableAutoSign,
  };
});
